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