2 * Copyright 2001-2009 Internet2
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * AbstractPKIXTrustEngine.cpp
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.
26 #include "security/AbstractPKIXTrustEngine.h"
27 #include "signature/KeyInfo.h"
28 #include "signature/Signature.h"
30 #include <openssl/x509_vfy.h>
31 #include <openssl/x509v3.h>
32 #include <xmltooling/security/CredentialCriteria.h>
33 #include <xmltooling/security/CredentialResolver.h>
34 #include <xmltooling/security/KeyInfoResolver.h>
35 #include <xmltooling/security/OpenSSLCryptoX509CRL.h>
36 #include <xmltooling/security/X509Credential.h>
37 #include <xmltooling/signature/SignatureValidator.h>
38 #include <xmltooling/util/NDC.h>
39 #include <xercesc/util/XMLUniDefs.hpp>
40 #include <xsec/enc/OpenSSL/OpenSSLCryptoX509.hpp>
42 using namespace xmlsignature;
43 using namespace xmltooling::logging;
44 using namespace xmltooling;
49 static int XMLTOOL_DLLLOCAL error_callback(int ok, X509_STORE_CTX* ctx)
52 Category::getInstance("OpenSSL").error("path validation failure: %s", X509_verify_cert_error_string(ctx->error));
56 static bool XMLTOOL_DLLLOCAL validate(
58 STACK_OF(X509)* untrusted,
59 AbstractPKIXTrustEngine::PKIXValidationInfoIterator* pkixInfo,
61 const vector<XSECCryptoX509CRL*>* inlineCRLs=NULL
64 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine");
66 // First we build a stack of CA certs. These objects are all referenced in place.
67 log.debug("supplying PKIX Validation information");
69 // We need this for CRL support.
70 X509_STORE* store=X509_STORE_new();
76 STACK_OF(X509)* CAstack = sk_X509_new_null();
78 // This contains the state of the validate operation.
82 const vector<XSECCryptoX509*>& CAcerts = pkixInfo->getTrustAnchors();
83 for (vector<XSECCryptoX509*>::const_iterator i=CAcerts.begin(); i!=CAcerts.end(); ++i) {
84 if ((*i)->getProviderName()==DSIGConstants::s_unicodeStrPROVOpenSSL) {
85 sk_X509_push(CAstack,static_cast<OpenSSLCryptoX509*>(*i)->getOpenSSLX509());
90 log.debug("supplied (%d) CA certificate(s)", count);
92 #if (OPENSSL_VERSION_NUMBER >= 0x00907000L)
95 for (vector<XSECCryptoX509CRL*>::const_iterator j=inlineCRLs->begin(); j!=inlineCRLs->end(); ++j) {
96 if ((*j)->getProviderName()==DSIGConstants::s_unicodeStrPROVOpenSSL) {
98 X509_STORE_add_crl(store, X509_CRL_dup(static_cast<OpenSSLCryptoX509CRL*>(*j)->getOpenSSLX509CRL()));
103 const vector<XSECCryptoX509CRL*>& crls = pkixInfo->getCRLs();
104 for (vector<XSECCryptoX509CRL*>::const_iterator j=crls.begin(); j!=crls.end(); ++j) {
105 if ((*j)->getProviderName()==DSIGConstants::s_unicodeStrPROVOpenSSL) {
107 X509_STORE_add_crl(store, X509_CRL_dup(static_cast<OpenSSLCryptoX509CRL*>(*j)->getOpenSSLX509CRL()));
111 log.debug("supplied (%d) CRL(s)", count);
113 X509_STORE_set_flags(store, fullCRLChain ? (X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL) : (X509_V_FLAG_CRL_CHECK));
115 if ((inlineCRLs && !inlineCRLs->empty()) || !pkixInfo->getCRLs().empty()) {
116 log.warn("OpenSSL versions < 0.9.7 do not support CRL checking");
120 // AFAICT, EE and untrusted are passed in but not owned by the ctx.
121 #if (OPENSSL_VERSION_NUMBER >= 0x00907000L)
122 if (X509_STORE_CTX_init(&ctx,store,EE,untrusted)!=1) {
124 log.error("unable to initialize X509_STORE_CTX");
125 sk_X509_free(CAstack);
126 X509_STORE_free(store);
130 X509_STORE_CTX_init(&ctx,store,EE,untrusted);
133 // Seems to be most efficient to just pass in the CA stack.
134 X509_STORE_CTX_trusted_stack(&ctx,CAstack);
135 X509_STORE_CTX_set_depth(&ctx,100); // we check the depth down below
136 X509_STORE_CTX_set_verify_cb(&ctx,error_callback);
138 int ret=X509_verify_cert(&ctx);
140 // Now see if the depth was acceptable by counting the number of intermediates.
141 int depth=sk_X509_num(ctx.chain)-2;
142 if (pkixInfo->getVerificationDepth() < depth) {
144 "certificate chain was too long (%d intermediates, only %d allowed)",
145 (depth==-1) ? 0 : depth,
146 pkixInfo->getVerificationDepth()
153 X509_STORE_CTX_cleanup(&ctx);
154 X509_STORE_free(store);
155 sk_X509_free(CAstack);
158 log.debug("successfully validated certificate chain");
166 AbstractPKIXTrustEngine::PKIXValidationInfoIterator::PKIXValidationInfoIterator()
170 AbstractPKIXTrustEngine::PKIXValidationInfoIterator::~PKIXValidationInfoIterator()
174 AbstractPKIXTrustEngine::AbstractPKIXTrustEngine(const xercesc::DOMElement* e) : TrustEngine(e), m_fullCRLChain(false)
176 static XMLCh fullCRLChain[] = UNICODE_LITERAL_12(f,u,l,l,C,R,L,C,h,a,i,n);
177 const XMLCh* flag = e ? e->getAttributeNS(NULL, fullCRLChain) : NULL;
178 m_fullCRLChain = (flag && (*flag == xercesc::chLatin_t || *flag == xercesc::chDigit_1));
181 AbstractPKIXTrustEngine::~AbstractPKIXTrustEngine()
185 bool AbstractPKIXTrustEngine::checkEntityNames(
186 X509* certEE, const CredentialResolver& credResolver, const CredentialCriteria& criteria
189 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX");
191 // We resolve to a set of trusted credentials.
192 vector<const Credential*> creds;
193 credResolver.resolve(creds,&criteria);
195 // Build a list of acceptable names.
196 set<string> trustednames;
197 trustednames.insert(criteria.getPeerName());
198 for (vector<const Credential*>::const_iterator cred = creds.begin(); cred!=creds.end(); ++cred)
199 trustednames.insert((*cred)->getKeyNames().begin(), (*cred)->getKeyNames().end());
201 X509_NAME* subject=X509_get_subject_name(certEE);
203 // One way is a direct match to the subject DN.
204 // Seems that the way to do the compare is to write the X509_NAME into a BIO.
205 BIO* b = BIO_new(BIO_s_mem());
206 BIO* b2 = BIO_new(BIO_s_mem());
207 // The flags give us LDAP order instead of X.500, with a comma separator.
208 X509_NAME_print_ex(b,subject,0,XN_FLAG_RFC2253);
210 // The flags give us LDAP order instead of X.500, with a comma plus space separator.
211 X509_NAME_print_ex(b2,subject,0,XN_FLAG_RFC2253 + XN_FLAG_SEP_CPLUS_SPC - XN_FLAG_SEP_COMMA_PLUS);
216 BIO_get_mem_ptr(b, &bptr);
217 BIO_get_mem_ptr(b2, &bptr2);
219 if (bptr && bptr->length > 0 && log.isDebugEnabled()) {
220 string subjectstr(bptr->data, bptr->length);
221 log.debug("certificate subject: %s", subjectstr.c_str());
224 // Check each keyname.
225 for (set<string>::const_iterator n=trustednames.begin(); bptr && bptr2 && n!=trustednames.end(); n++) {
226 #ifdef HAVE_STRCASECMP
227 if ((n->length() == bptr->length && !strncasecmp(n->c_str(), bptr->data, bptr->length)) ||
228 (n->length() == bptr2->length && !strncasecmp(n->c_str(), bptr2->data, bptr2->length))) {
230 if ((n->length() == bptr->length && !strnicmp(n->c_str(), bptr->data, bptr->length)) ||
231 (n->length() == bptr2->length && !strnicmp(n->c_str(), bptr2->data, bptr2->length))) {
233 log.debug("matched full subject DN to a key name (%s)", n->c_str());
242 log.debug("unable to match DN, trying TLS subjectAltName match");
243 STACK_OF(GENERAL_NAME)* altnames=(STACK_OF(GENERAL_NAME)*)X509_get_ext_d2i(certEE, NID_subject_alt_name, NULL, NULL);
245 int numalts = sk_GENERAL_NAME_num(altnames);
246 for (int an=0; an<numalts; an++) {
247 const GENERAL_NAME* check = sk_GENERAL_NAME_value(altnames, an);
248 if (check->type==GEN_DNS || check->type==GEN_URI) {
249 const char* altptr = (char*)ASN1_STRING_data(check->d.ia5);
250 const int altlen = ASN1_STRING_length(check->d.ia5);
251 for (set<string>::const_iterator n=trustednames.begin(); n!=trustednames.end(); n++) {
252 #ifdef HAVE_STRCASECMP
253 if ((check->type==GEN_DNS && n->length()==altlen && !strncasecmp(altptr,n->c_str(),altlen))
255 if ((check->type==GEN_DNS && n->length()==altlen && !strnicmp(altptr,n->c_str(),altlen))
257 || (check->type==GEN_URI && n->length()==altlen && !strncmp(altptr,n->c_str(),altlen))) {
258 log.debug("matched DNS/URI subjectAltName to a key name (%s)", n->c_str());
259 GENERAL_NAMES_free(altnames);
266 GENERAL_NAMES_free(altnames);
268 log.debug("unable to match subjectAltName, trying TLS CN match");
270 // Fetch the last CN RDN.
271 char* peer_CN = NULL;
273 while ((j=X509_NAME_get_index_by_NID(subject, NID_commonName, i)) >= 0)
276 ASN1_STRING* tmp = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(subject, i));
277 // Copied in from libcurl.
278 /* In OpenSSL 0.9.7d and earlier, ASN1_STRING_to_UTF8 fails if the input
279 is already UTF-8 encoded. We check for this case and copy the raw
280 string manually to avoid the problem. */
281 if(tmp && ASN1_STRING_type(tmp) == V_ASN1_UTF8STRING) {
282 j = ASN1_STRING_length(tmp);
284 peer_CN = (char*)OPENSSL_malloc(j + 1);
285 memcpy(peer_CN, ASN1_STRING_data(tmp), j);
289 else /* not a UTF8 name */ {
290 j = ASN1_STRING_to_UTF8(reinterpret_cast<unsigned char**>(&peer_CN), tmp);
293 for (set<string>::const_iterator n=trustednames.begin(); n!=trustednames.end(); n++) {
294 #ifdef HAVE_STRCASECMP
295 if (n->length() == j && !strncasecmp(peer_CN, n->c_str(), j)) {
297 if (n->length() == j && !strnicmp(peer_CN, n->c_str(), j)) {
299 log.debug("matched subject CN to a key name (%s)", n->c_str());
301 OPENSSL_free(peer_CN);
306 OPENSSL_free(peer_CN);
309 log.warn("no common name in certificate subject");
313 log.error("certificate has no subject?!");
319 bool AbstractPKIXTrustEngine::validateWithCRLs(
321 STACK_OF(X509)* certChain,
322 const CredentialResolver& credResolver,
323 CredentialCriteria* criteria,
324 const std::vector<XSECCryptoX509CRL*>* inlineCRLs
328 NDC ndc("validateWithCRLs");
330 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX");
333 log.error("X.509 credential was NULL, unable to perform validation");
337 if (criteria && criteria->getPeerName() && *(criteria->getPeerName())) {
338 log.debug("checking that the certificate name is acceptable");
339 if (criteria->getUsage()==Credential::UNSPECIFIED_CREDENTIAL)
340 criteria->setUsage(Credential::SIGNING_CREDENTIAL);
341 if (!checkEntityNames(certEE,credResolver,*criteria)) {
342 log.error("certificate name was not acceptable");
347 log.debug("performing certificate path validation...");
349 auto_ptr<PKIXValidationInfoIterator> pkix(getPKIXValidationInfoIterator(credResolver, criteria));
350 while (pkix->next()) {
351 if (::validate(certEE,certChain,pkix.get(),m_fullCRLChain,inlineCRLs)) {
356 log.debug("failed to validate certificate chain using supplied PKIX information");
360 bool AbstractPKIXTrustEngine::validate(
362 STACK_OF(X509)* certChain,
363 const CredentialResolver& credResolver,
364 CredentialCriteria* criteria
367 return validateWithCRLs(certEE,certChain,credResolver,criteria);
370 bool AbstractPKIXTrustEngine::validate(
371 XSECCryptoX509* certEE,
372 const vector<XSECCryptoX509*>& certChain,
373 const CredentialResolver& credResolver,
374 CredentialCriteria* criteria
381 Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX").error("X.509 credential was NULL, unable to perform validation");
384 else if (certEE->getProviderName()!=DSIGConstants::s_unicodeStrPROVOpenSSL) {
385 Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX").error("only the OpenSSL XSEC provider is supported");
389 STACK_OF(X509)* untrusted=sk_X509_new_null();
390 for (vector<XSECCryptoX509*>::const_iterator i=certChain.begin(); i!=certChain.end(); ++i)
391 sk_X509_push(untrusted,static_cast<OpenSSLCryptoX509*>(*i)->getOpenSSLX509());
393 bool ret = validate(static_cast<OpenSSLCryptoX509*>(certEE)->getOpenSSLX509(), untrusted, credResolver, criteria);
394 sk_X509_free(untrusted);
398 bool AbstractPKIXTrustEngine::validate(
400 const CredentialResolver& credResolver,
401 CredentialCriteria* criteria
407 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX");
409 const KeyInfoResolver* inlineResolver = m_keyInfoResolver;
411 inlineResolver = XMLToolingConfig::getConfig().getKeyInfoResolver();
412 if (!inlineResolver) {
413 log.error("unable to perform PKIX validation, no KeyInfoResolver available");
417 // Pull the certificate chain out of the signature.
418 X509Credential* x509cred;
419 auto_ptr<Credential> cred(inlineResolver->resolve(&sig,X509Credential::RESOLVE_CERTS|X509Credential::RESOLVE_CRLS));
420 if (!cred.get() || !(x509cred=dynamic_cast<X509Credential*>(cred.get()))) {
421 log.error("unable to perform PKIX validation, signature does not contain any certificates");
424 const vector<XSECCryptoX509*>& certs = x509cred->getEntityCertificateChain();
426 log.error("unable to perform PKIX validation, signature does not contain any certificates");
430 log.debug("validating signature using certificate from within the signature");
432 // Find and save off a pointer to the certificate that unlocks the object.
433 // Most of the time, this will be the first one anyway.
434 XSECCryptoX509* certEE=NULL;
435 SignatureValidator keyValidator;
436 for (vector<XSECCryptoX509*>::const_iterator i=certs.begin(); !certEE && i!=certs.end(); ++i) {
438 auto_ptr<XSECCryptoKey> key((*i)->clonePublicKey());
439 keyValidator.setKey(key.get());
440 keyValidator.validate(&sig);
441 log.debug("signature verified with key inside signature, attempting certificate validation...");
444 catch (ValidationException& ex) {
445 log.debug(ex.what());
450 log.debug("failed to verify signature with embedded certificates");
453 else if (certEE->getProviderName()!=DSIGConstants::s_unicodeStrPROVOpenSSL) {
454 log.error("only the OpenSSL XSEC provider is supported");
458 STACK_OF(X509)* untrusted=sk_X509_new_null();
459 for (vector<XSECCryptoX509*>::const_iterator i=certs.begin(); i!=certs.end(); ++i)
460 sk_X509_push(untrusted,static_cast<OpenSSLCryptoX509*>(*i)->getOpenSSLX509());
461 const vector<XSECCryptoX509CRL*>& crls = x509cred->getCRLs();
462 bool ret = validateWithCRLs(static_cast<OpenSSLCryptoX509*>(certEE)->getOpenSSLX509(), untrusted, credResolver, criteria, &crls);
463 sk_X509_free(untrusted);
467 bool AbstractPKIXTrustEngine::validate(
468 const XMLCh* sigAlgorithm,
473 const CredentialResolver& credResolver,
474 CredentialCriteria* criteria
480 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX");
483 log.error("unable to perform PKIX validation, KeyInfo not present");
487 const KeyInfoResolver* inlineResolver = m_keyInfoResolver;
489 inlineResolver = XMLToolingConfig::getConfig().getKeyInfoResolver();
490 if (!inlineResolver) {
491 log.error("unable to perform PKIX validation, no KeyInfoResolver available");
495 // Pull the certificate chain out of the signature.
496 X509Credential* x509cred;
497 auto_ptr<Credential> cred(inlineResolver->resolve(keyInfo,X509Credential::RESOLVE_CERTS));
498 if (!cred.get() || !(x509cred=dynamic_cast<X509Credential*>(cred.get()))) {
499 log.error("unable to perform PKIX validation, KeyInfo does not contain any certificates");
502 const vector<XSECCryptoX509*>& certs = x509cred->getEntityCertificateChain();
504 log.error("unable to perform PKIX validation, KeyInfo does not contain any certificates");
508 log.debug("validating signature using certificate from within KeyInfo");
510 // Find and save off a pointer to the certificate that unlocks the object.
511 // Most of the time, this will be the first one anyway.
512 XSECCryptoX509* certEE=NULL;
513 for (vector<XSECCryptoX509*>::const_iterator i=certs.begin(); !certEE && i!=certs.end(); ++i) {
515 auto_ptr<XSECCryptoKey> key((*i)->clonePublicKey());
516 if (Signature::verifyRawSignature(key.get(), sigAlgorithm, sig, in, in_len)) {
517 log.debug("signature verified with key inside signature, attempting certificate validation...");
521 catch (SignatureException& ex) {
522 log.debug(ex.what());
527 return validate(certEE,certs,credResolver,criteria);
529 log.debug("failed to verify signature with embedded certificates");