PKIX TrustEngine.
[shibboleth/cpp-opensaml.git] / saml / security / impl / AbstractPKIXTrustEngine.cpp
1 /*\r
2  *  Copyright 2006 Internet2\r
3  * \r
4  * Licensed under the Apache License, Version 2.0 (the "License");\r
5  * you may not use this file except in compliance with the License.\r
6  * You may obtain a copy of the License at\r
7  *\r
8  *     http://www.apache.org/licenses/LICENSE-2.0\r
9  *\r
10  * Unless required by applicable law or agreed to in writing, software\r
11  * distributed under the License is distributed on an "AS IS" BASIS,\r
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
13  * See the License for the specific language governing permissions and\r
14  * limitations under the License.\r
15  */\r
16 \r
17 /**\r
18  * AbstractPKIXTrustEngine.cpp\r
19  * \r
20  * A trust engine that uses X.509 trust anchors and CRLs associated with a role\r
21  * to perform PKIX validation of signatures and certificates.\r
22  */\r
23 \r
24 #include "internal.h"\r
25 #include "security/AbstractPKIXTrustEngine.h"\r
26 #include "signature/SignatureProfileValidator.h"\r
27 \r
28 #include <openssl/x509_vfy.h>\r
29 #include <openssl/x509v3.h>\r
30 #include <xmltooling/security/OpenSSLCryptoX509CRL.h>\r
31 #include <xmltooling/signature/SignatureValidator.h>\r
32 #include <xmltooling/util/NDC.h>\r
33 #include <xsec/enc/OpenSSL/OpenSSLCryptoX509.hpp>\r
34 #include <log4cpp/Category.hh>\r
35 \r
36 using namespace opensaml::saml2md;\r
37 using namespace opensaml;\r
38 using namespace xmlsignature;\r
39 using namespace xmltooling;\r
40 using namespace log4cpp;\r
41 using namespace std;\r
42 \r
43 AbstractPKIXTrustEngine::AbstractPKIXTrustEngine(const DOMElement* e) : X509TrustEngine(e), m_inlineResolver(NULL)\r
44 {\r
45     m_inlineResolver = XMLToolingConfig::getConfig().KeyResolverManager.newPlugin(INLINE_KEY_RESOLVER,NULL);\r
46 }\r
47 \r
48 AbstractPKIXTrustEngine::~AbstractPKIXTrustEngine()\r
49 {\r
50     delete m_inlineResolver;\r
51 }\r
52 \r
53 namespace {\r
54     static int SAML_DLLLOCAL error_callback(int ok, X509_STORE_CTX* ctx)\r
55     {\r
56         if (!ok)\r
57             Category::getInstance("OpenSSL").error("path validation failure: %s", X509_verify_cert_error_string(ctx->error));\r
58         return ok;\r
59     }\r
60 \r
61     static bool SAML_DLLLOCAL validate(\r
62         X509* EE, STACK_OF(X509)* untrusted, AbstractPKIXTrustEngine::PKIXValidationInfoIterator* pkixInfo\r
63         )\r
64     {\r
65         Category& log=Category::getInstance(SAML_LOGCAT".TrustEngine");\r
66     \r
67         // First we build a stack of CA certs. These objects are all referenced in place.\r
68         log.debug("building CA list from PKIX Validation information");\r
69     \r
70         // We need this for CRL support.\r
71         X509_STORE* store=X509_STORE_new();\r
72         if (!store) {\r
73             log_openssl();\r
74             return false;\r
75         }\r
76     #if (OPENSSL_VERSION_NUMBER >= 0x00907000L)\r
77         X509_STORE_set_flags(store,X509_V_FLAG_CRL_CHECK_ALL);\r
78     #endif\r
79     \r
80         STACK_OF(X509)* CAstack = sk_X509_new_null();\r
81         \r
82         // This contains the state of the validate operation.\r
83         X509_STORE_CTX ctx;\r
84         \r
85         const vector<XSECCryptoX509*>& CAcerts = pkixInfo->getTrustAnchors();\r
86         for (vector<XSECCryptoX509*>::const_iterator i=CAcerts.begin(); i!=CAcerts.end(); ++i) {\r
87             if ((*i)->getProviderName()==DSIGConstants::s_unicodeStrPROVOpenSSL) {\r
88                 sk_X509_push(CAstack,static_cast<OpenSSLCryptoX509*>(*i)->getOpenSSLX509());\r
89             }\r
90         }\r
91 \r
92         const vector<XSECCryptoX509CRL*>& crls = pkixInfo->getCRLs();\r
93         for (vector<XSECCryptoX509CRL*>::const_iterator j=crls.begin(); j!=crls.end(); ++j) {\r
94             if ((*j)->getProviderName()==DSIGConstants::s_unicodeStrPROVOpenSSL) {\r
95                 // owned by store\r
96                 X509_STORE_add_crl(\r
97                     store,\r
98                     X509_CRL_dup(static_cast<OpenSSLCryptoX509CRL*>(*j)->getOpenSSLX509CRL())\r
99                     );\r
100             }\r
101         }\r
102      \r
103         // AFAICT, EE and untrusted are passed in but not owned by the ctx.\r
104     #if (OPENSSL_VERSION_NUMBER >= 0x00907000L)\r
105         if (X509_STORE_CTX_init(&ctx,store,EE,untrusted)!=1) {\r
106             log_openssl();\r
107             log.error("unable to initialize X509_STORE_CTX");\r
108             sk_X509_free(CAstack);\r
109             X509_STORE_free(store);\r
110             return false;\r
111         }\r
112     #else\r
113         X509_STORE_CTX_init(&ctx,store,EE,untrusted);\r
114     #endif\r
115     \r
116         // Seems to be most efficient to just pass in the CA stack.\r
117         X509_STORE_CTX_trusted_stack(&ctx,CAstack);\r
118         X509_STORE_CTX_set_depth(&ctx,100);    // we check the depth down below\r
119         X509_STORE_CTX_set_verify_cb(&ctx,error_callback);\r
120         \r
121         int ret=X509_verify_cert(&ctx);\r
122         if (ret==1) {\r
123             // Now see if the depth was acceptable by counting the number of intermediates.\r
124             int depth=sk_X509_num(ctx.chain)-2;\r
125             if (pkixInfo->getVerificationDepth() < depth) {\r
126                 log.error(\r
127                     "certificate chain was too long (%d intermediates, only %d allowed)",\r
128                     (depth==-1) ? 0 : depth,\r
129                     pkixInfo->getVerificationDepth()\r
130                     );\r
131                 ret=0;\r
132             }\r
133         }\r
134         \r
135         // Clean up...\r
136         X509_STORE_CTX_cleanup(&ctx);\r
137         X509_STORE_free(store);\r
138         sk_X509_free(CAstack);\r
139     \r
140         if (ret==1) {\r
141             log.info("successfully validated certificate chain");\r
142             return true;\r
143         }\r
144         \r
145         return false;\r
146     }\r
147 };\r
148 \r
149 bool AbstractPKIXTrustEngine::checkEntityNames(XSECCryptoX509* certEE, const RoleDescriptor& role) const\r
150 {\r
151     Category& log=Category::getInstance(SAML_LOGCAT".TrustEngine");\r
152     \r
153     // Build a list of acceptable names. Transcode the possible key "names" to UTF-8.\r
154     // For some simple cases, this should handle UTF-8 encoded DNs in certificates.\r
155     vector<string> keynames;\r
156     const vector<KeyDescriptor*>& keydescs=role.getKeyDescriptors();\r
157     for (vector<KeyDescriptor*>::const_iterator kd_i=keydescs.begin(); kd_i!=keydescs.end(); ++kd_i) {\r
158         const XMLCh* use=(*kd_i)->getUse();\r
159         const KeyInfo* keyInfo = (*kd_i)->getKeyInfo();\r
160         if (keyInfo && use && XMLString::equals(use,KeyDescriptor::KEYTYPE_ENCRYPTION))\r
161             continue;\r
162         const vector<KeyName*>& knames=keyInfo->getKeyNames();\r
163         for (vector<KeyName*>::const_iterator kn_i=knames.begin(); kn_i!=knames.end(); ++kn_i) {\r
164             const XMLCh* n=(*kn_i)->getName();\r
165             if (n && *n) {\r
166                 char* kn=toUTF8(n);\r
167                 keynames.push_back(kn);\r
168                 delete[] kn;\r
169             }\r
170         }\r
171     }\r
172     \r
173     EntityDescriptor* parent=dynamic_cast<EntityDescriptor*>(role.getParent());\r
174     if (parent) {\r
175         const XMLCh* eid=parent->getEntityID();\r
176         if (eid && *eid) {\r
177             char* kn=toUTF8(eid);\r
178             keynames.push_back(kn);\r
179             delete[] kn;\r
180         }\r
181     }\r
182     \r
183     char buf[256];\r
184     X509* x=static_cast<OpenSSLCryptoX509*>(certEE)->getOpenSSLX509();\r
185     X509_NAME* subject=X509_get_subject_name(x);\r
186     if (subject) {\r
187         // One way is a direct match to the subject DN.\r
188         // Seems that the way to do the compare is to write the X509_NAME into a BIO.\r
189         BIO* b = BIO_new(BIO_s_mem());\r
190         BIO* b2 = BIO_new(BIO_s_mem());\r
191         BIO_set_mem_eof_return(b, 0);\r
192         BIO_set_mem_eof_return(b2, 0);\r
193         // The flags give us LDAP order instead of X.500, with a comma separator.\r
194         int len=X509_NAME_print_ex(b,subject,0,XN_FLAG_RFC2253);\r
195         string subjectstr,subjectstr2;\r
196         BIO_flush(b);\r
197         while ((len = BIO_read(b, buf, 255)) > 0) {\r
198             buf[len] = '\0';\r
199             subjectstr+=buf;\r
200         }\r
201         log.infoStream() << "certificate subject: " << subjectstr << CategoryStream::ENDLINE;\r
202         // The flags give us LDAP order instead of X.500, with a comma plus space separator.\r
203         len=X509_NAME_print_ex(b2,subject,0,XN_FLAG_RFC2253 + XN_FLAG_SEP_CPLUS_SPC - XN_FLAG_SEP_COMMA_PLUS);\r
204         BIO_flush(b2);\r
205         while ((len = BIO_read(b2, buf, 255)) > 0) {\r
206             buf[len] = '\0';\r
207             subjectstr2+=buf;\r
208         }\r
209         \r
210         // Check each keyname.\r
211         for (vector<string>::const_iterator n=keynames.begin(); n!=keynames.end(); n++) {\r
212 #ifdef HAVE_STRCASECMP\r
213             if (!strcasecmp(n->c_str(),subjectstr.c_str()) || !strcasecmp(n->c_str(),subjectstr2.c_str())) {\r
214 #else\r
215             if (!stricmp(n->c_str(),subjectstr.c_str()) || !stricmp(n->c_str(),subjectstr2.c_str())) {\r
216 #endif\r
217                 log.info("matched full subject DN to a key name (%s)", n->c_str());\r
218                 BIO_free(b);\r
219                 BIO_free(b2);\r
220                 return true;\r
221             }\r
222         }\r
223         BIO_free(b);\r
224         BIO_free(b2);\r
225 \r
226         log.debug("unable to match DN, trying TLS subjectAltName match");\r
227         STACK_OF(GENERAL_NAME)* altnames=(STACK_OF(GENERAL_NAME)*)X509_get_ext_d2i(x, NID_subject_alt_name, NULL, NULL);\r
228         if (altnames) {\r
229             int numalts = sk_GENERAL_NAME_num(altnames);\r
230             for (int an=0; an<numalts; an++) {\r
231                 const GENERAL_NAME* check = sk_GENERAL_NAME_value(altnames, an);\r
232                 if (check->type==GEN_DNS || check->type==GEN_URI) {\r
233                     const char* altptr = (char*)ASN1_STRING_data(check->d.ia5);\r
234                     const int altlen = ASN1_STRING_length(check->d.ia5);\r
235                     \r
236                     for (vector<string>::const_iterator n=keynames.begin(); n!=keynames.end(); n++) {\r
237 #ifdef HAVE_STRCASECMP\r
238                         if ((check->type==GEN_DNS && !strncasecmp(altptr,n->c_str(),altlen))\r
239 #else\r
240                         if ((check->type==GEN_DNS && !strnicmp(altptr,n->c_str(),altlen))\r
241 #endif\r
242                                 || (check->type==GEN_URI && !strncmp(altptr,n->c_str(),altlen))) {\r
243                             log.info("matched DNS/URI subjectAltName to a key name (%s)", n->c_str());\r
244                             GENERAL_NAMES_free(altnames);\r
245                             return true;\r
246                         }\r
247                     }\r
248                 }\r
249             }\r
250         }\r
251         GENERAL_NAMES_free(altnames);\r
252             \r
253         log.debug("unable to match subjectAltName, trying TLS CN match");\r
254         memset(buf,0,sizeof(buf));\r
255         if (X509_NAME_get_text_by_NID(subject,NID_commonName,buf,255)>0) {\r
256             for (vector<string>::const_iterator n=keynames.begin(); n!=keynames.end(); n++) {\r
257 #ifdef HAVE_STRCASECMP\r
258                 if (!strcasecmp(buf,n->c_str())) {\r
259 #else\r
260                 if (!stricmp(buf,n->c_str())) {\r
261 #endif\r
262                     log.info("matched subject CN to a key name (%s)", n->c_str());\r
263                     return true;\r
264                 }\r
265             }\r
266         }\r
267         else\r
268             log.warn("no common name in certificate subject");\r
269     }\r
270     else\r
271         log.error("certificate has no subject?!");\r
272     \r
273     return false;\r
274 }\r
275 \r
276 bool AbstractPKIXTrustEngine::validate(\r
277     XSECCryptoX509* certEE,\r
278     const vector<XSECCryptoX509*>& certChain,\r
279     const RoleDescriptor& role,\r
280     bool checkName,\r
281     const KeyResolver* keyResolver\r
282     )\r
283 {\r
284 #ifdef _DEBUG\r
285     NDC ndc("validate");\r
286 #endif\r
287     Category& log=Category::getInstance(SAML_LOGCAT".TrustEngine");\r
288 \r
289     if (!certEE) {\r
290         log.error("X.509 credential was NULL, unable to perform validation");\r
291         return false;\r
292     }\r
293 \r
294     if (checkName) {\r
295         log.debug("checking that the entity certificate name is acceptable");\r
296         if (!checkEntityNames(certEE,role)) {\r
297             log.error("entity certificate name was not acceptable");\r
298             return false;\r
299         }\r
300     }\r
301     \r
302     log.debug("performing certificate path validation...");\r
303 \r
304     STACK_OF(X509)* untrusted=sk_X509_new_null();\r
305     for (vector<XSECCryptoX509*>::const_iterator i=certChain.begin(); i!=certChain.end(); ++i) {\r
306         sk_X509_push(untrusted,static_cast<OpenSSLCryptoX509*>(*i)->getOpenSSLX509());\r
307     }\r
308     \r
309     auto_ptr<PKIXValidationInfoIterator> pkix(getPKIXValidationInfoIterator(role));\r
310     while (pkix->next()) {\r
311         if (::validate(static_cast<OpenSSLCryptoX509*>(certEE)->getOpenSSLX509(),untrusted,pkix.get())) {\r
312             sk_X509_free(untrusted);\r
313             return true;\r
314         }\r
315     }\r
316 \r
317     sk_X509_free(untrusted);\r
318     log.error("failed to validate certificate chain using supplied PKIX information");\r
319     return false;\r
320 }\r
321 \r
322 bool AbstractPKIXTrustEngine::validate(Signature& sig, const RoleDescriptor& role, const KeyResolver* keyResolver)\r
323 {\r
324 #ifdef _DEBUG\r
325     NDC ndc("validate");\r
326 #endif\r
327     Category& log=Category::getInstance(SAML_LOGCAT".TrustEngine");\r
328 \r
329     log.debug("attempting to validate signature profile");\r
330     SignatureProfileValidator sigValidator;\r
331     try {\r
332         sigValidator.validate(&sig);\r
333         log.debug("signature profile validated");\r
334     }\r
335     catch (ValidationException& e) {\r
336         if (log.isDebugEnabled()) {\r
337             log.debug("signature profile failed to validate: %s", e.what());\r
338         }\r
339         return false;\r
340     }\r
341 \r
342     // Pull the certificate chain out of the signature using an inline KeyResolver.\r
343     KeyResolver::ResolvedCertificates certs;\r
344     if (0==m_inlineResolver->resolveCertificates(&sig, certs)) {\r
345         log.error("unable to perform PKIX validation, signature does not contain any certificates");\r
346         return false;\r
347     }\r
348 \r
349     log.debug("validating signature using certificate from within the signature");\r
350 \r
351     // Find and save off a pointer to the certificate that unlocks the object.\r
352     // Most of the time, this will be the first one anyway.\r
353     XSECCryptoX509* certEE=NULL;\r
354     SignatureValidator keyValidator;\r
355     for (vector<XSECCryptoX509*>::const_iterator i=certs.v().begin(); !certEE && i!=certs.v().end(); ++i) {\r
356         try {\r
357             keyValidator.setKey((*i)->clonePublicKey());\r
358             keyValidator.validate(&sig);\r
359             log.info("signature verified with key inside signature, attempting certificate validation...");\r
360             certEE=(*i);\r
361         }\r
362         catch (ValidationException&) {\r
363             // trap failures\r
364         }\r
365     }\r
366     \r
367     if (certEE)\r
368         return validate(certEE,certs.v(),role,true,keyResolver);\r
369         \r
370     log.error("failed to verify signature with embedded certificates");\r
371     return false;\r
372 }\r