2 * Copyright 2001-2010 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"
29 #include "security/CredentialCriteria.h"
30 #include "security/CredentialResolver.h"
31 #include "security/KeyInfoResolver.h"
32 #include "security/OpenSSLCryptoX509CRL.h"
33 #include "security/X509Credential.h"
34 #include "signature/SignatureValidator.h"
37 #include <openssl/x509_vfy.h>
38 #include <openssl/x509v3.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,
62 const vector<XSECCryptoX509CRL*>* inlineCRLs=nullptr
65 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine");
67 // First we build a stack of CA certs. These objects are all referenced in place.
68 log.debug("supplying PKIX Validation information");
70 // We need this for CRL support.
71 X509_STORE* store=X509_STORE_new();
77 STACK_OF(X509)* CAstack = sk_X509_new_null();
79 // This contains the state of the validate operation.
83 const vector<XSECCryptoX509*>& CAcerts = pkixInfo->getTrustAnchors();
84 for (vector<XSECCryptoX509*>::const_iterator i=CAcerts.begin(); i!=CAcerts.end(); ++i) {
85 if ((*i)->getProviderName()==DSIGConstants::s_unicodeStrPROVOpenSSL) {
86 sk_X509_push(CAstack,static_cast<OpenSSLCryptoX509*>(*i)->getOpenSSLX509());
91 log.debug("supplied (%d) CA certificate(s)", count);
94 #if (OPENSSL_VERSION_NUMBER >= 0x00907000L)
97 for (vector<XSECCryptoX509CRL*>::const_iterator j=inlineCRLs->begin(); j!=inlineCRLs->end(); ++j) {
98 if ((*j)->getProviderName()==DSIGConstants::s_unicodeStrPROVOpenSSL) {
100 X509_STORE_add_crl(store, X509_CRL_dup(static_cast<OpenSSLCryptoX509CRL*>(*j)->getOpenSSLX509CRL()));
105 const vector<XSECCryptoX509CRL*>& crls = pkixInfo->getCRLs();
106 for (vector<XSECCryptoX509CRL*>::const_iterator j=crls.begin(); j!=crls.end(); ++j) {
107 if ((*j)->getProviderName()==DSIGConstants::s_unicodeStrPROVOpenSSL) {
109 X509_STORE_add_crl(store, X509_CRL_dup(static_cast<OpenSSLCryptoX509CRL*>(*j)->getOpenSSLX509CRL()));
113 log.debug("supplied (%d) CRL(s)", count);
115 X509_STORE_set_flags(store, fullCRLChain ? (X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL) : (X509_V_FLAG_CRL_CHECK));
118 log.warn("CRL checking is enabled, but none were supplied");
119 sk_X509_free(CAstack);
120 X509_STORE_free(store);
124 log.warn("CRL checking is enabled, but OpenSSL version is too old");
125 sk_X509_free(CAstack);
126 X509_STORE_free(store);
131 // AFAICT, EE and untrusted are passed in but not owned by the ctx.
132 #if (OPENSSL_VERSION_NUMBER >= 0x00907000L)
133 if (X509_STORE_CTX_init(&ctx,store,EE,untrusted)!=1) {
135 log.error("unable to initialize X509_STORE_CTX");
136 sk_X509_free(CAstack);
137 X509_STORE_free(store);
141 X509_STORE_CTX_init(&ctx,store,EE,untrusted);
144 // Seems to be most efficient to just pass in the CA stack.
145 X509_STORE_CTX_trusted_stack(&ctx,CAstack);
146 X509_STORE_CTX_set_depth(&ctx,100); // we check the depth down below
147 X509_STORE_CTX_set_verify_cb(&ctx,error_callback);
149 int ret=X509_verify_cert(&ctx);
151 // Now see if the depth was acceptable by counting the number of intermediates.
152 int depth=sk_X509_num(ctx.chain)-2;
153 if (pkixInfo->getVerificationDepth() < depth) {
155 "certificate chain was too long (%d intermediates, only %d allowed)",
156 (depth==-1) ? 0 : depth,
157 pkixInfo->getVerificationDepth()
164 X509_STORE_CTX_cleanup(&ctx);
165 X509_STORE_free(store);
166 sk_X509_free(CAstack);
169 log.debug("successfully validated certificate chain");
176 static XMLCh fullCRLChain[] = UNICODE_LITERAL_12(f,u,l,l,C,R,L,C,h,a,i,n);
177 static XMLCh checkRevocation[] = UNICODE_LITERAL_15(c,h,e,c,k,R,e,v,o,c,a,t,i,o,n);
180 AbstractPKIXTrustEngine::PKIXValidationInfoIterator::PKIXValidationInfoIterator()
184 AbstractPKIXTrustEngine::PKIXValidationInfoIterator::~PKIXValidationInfoIterator()
188 AbstractPKIXTrustEngine::AbstractPKIXTrustEngine(const xercesc::DOMElement* e)
190 m_fullCRLChain(XMLHelper::getAttrBool(e, false, fullCRLChain)),
191 m_checkRevocation(XMLHelper::getAttrString(e, nullptr, checkRevocation))
193 if (m_fullCRLChain) {
194 Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX").warn(
195 "fullCRLChain option is deprecated, setting checkRevocation to \"fullChain\""
197 m_checkRevocation = "fullChain";
199 else if (m_checkRevocation == "fullChain") {
200 m_fullCRLChain = true; // in case anything's using this
204 AbstractPKIXTrustEngine::~AbstractPKIXTrustEngine()
208 bool AbstractPKIXTrustEngine::checkEntityNames(
209 X509* certEE, const CredentialResolver& credResolver, const CredentialCriteria& criteria
212 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX");
214 // We resolve to a set of trusted credentials.
215 vector<const Credential*> creds;
216 credResolver.resolve(creds,&criteria);
218 // Build a list of acceptable names.
219 set<string> trustednames;
220 trustednames.insert(criteria.getPeerName());
221 for (vector<const Credential*>::const_iterator cred = creds.begin(); cred!=creds.end(); ++cred)
222 trustednames.insert((*cred)->getKeyNames().begin(), (*cred)->getKeyNames().end());
224 X509_NAME* subject=X509_get_subject_name(certEE);
226 // One way is a direct match to the subject DN.
227 // Seems that the way to do the compare is to write the X509_NAME into a BIO.
228 BIO* b = BIO_new(BIO_s_mem());
229 BIO* b2 = BIO_new(BIO_s_mem());
230 // The flags give us LDAP order instead of X.500, with a comma separator.
231 X509_NAME_print_ex(b,subject,0,XN_FLAG_RFC2253);
233 // The flags give us LDAP order instead of X.500, with a comma plus space separator.
234 X509_NAME_print_ex(b2,subject,0,XN_FLAG_RFC2253 + XN_FLAG_SEP_CPLUS_SPC - XN_FLAG_SEP_COMMA_PLUS);
237 BUF_MEM* bptr=nullptr;
238 BUF_MEM* bptr2=nullptr;
239 BIO_get_mem_ptr(b, &bptr);
240 BIO_get_mem_ptr(b2, &bptr2);
242 if (bptr && bptr->length > 0 && log.isDebugEnabled()) {
243 string subjectstr(bptr->data, bptr->length);
244 log.debug("certificate subject: %s", subjectstr.c_str());
247 // Check each keyname.
248 for (set<string>::const_iterator n=trustednames.begin(); bptr && bptr2 && n!=trustednames.end(); n++) {
249 #ifdef HAVE_STRCASECMP
250 if ((n->length() == bptr->length && !strncasecmp(n->c_str(), bptr->data, bptr->length)) ||
251 (n->length() == bptr2->length && !strncasecmp(n->c_str(), bptr2->data, bptr2->length))) {
253 if ((n->length() == bptr->length && !strnicmp(n->c_str(), bptr->data, bptr->length)) ||
254 (n->length() == bptr2->length && !strnicmp(n->c_str(), bptr2->data, bptr2->length))) {
256 log.debug("matched full subject DN to a key name (%s)", n->c_str());
265 log.debug("unable to match DN, trying TLS subjectAltName match");
266 STACK_OF(GENERAL_NAME)* altnames=(STACK_OF(GENERAL_NAME)*)X509_get_ext_d2i(certEE, NID_subject_alt_name, nullptr, nullptr);
268 int numalts = sk_GENERAL_NAME_num(altnames);
269 for (int an=0; an<numalts; an++) {
270 const GENERAL_NAME* check = sk_GENERAL_NAME_value(altnames, an);
271 if (check->type==GEN_DNS || check->type==GEN_URI) {
272 const char* altptr = (char*)ASN1_STRING_data(check->d.ia5);
273 const int altlen = ASN1_STRING_length(check->d.ia5);
274 for (set<string>::const_iterator n=trustednames.begin(); n!=trustednames.end(); n++) {
275 #ifdef HAVE_STRCASECMP
276 if ((check->type==GEN_DNS && n->length()==altlen && !strncasecmp(altptr,n->c_str(),altlen))
278 if ((check->type==GEN_DNS && n->length()==altlen && !strnicmp(altptr,n->c_str(),altlen))
280 || (check->type==GEN_URI && n->length()==altlen && !strncmp(altptr,n->c_str(),altlen))) {
281 log.debug("matched DNS/URI subjectAltName to a key name (%s)", n->c_str());
282 GENERAL_NAMES_free(altnames);
289 GENERAL_NAMES_free(altnames);
291 log.debug("unable to match subjectAltName, trying TLS CN match");
293 // Fetch the last CN RDN.
294 char* peer_CN = nullptr;
296 while ((j=X509_NAME_get_index_by_NID(subject, NID_commonName, i)) >= 0)
299 ASN1_STRING* tmp = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(subject, i));
300 // Copied in from libcurl.
301 /* In OpenSSL 0.9.7d and earlier, ASN1_STRING_to_UTF8 fails if the input
302 is already UTF-8 encoded. We check for this case and copy the raw
303 string manually to avoid the problem. */
304 if(tmp && ASN1_STRING_type(tmp) == V_ASN1_UTF8STRING) {
305 j = ASN1_STRING_length(tmp);
307 peer_CN = (char*)OPENSSL_malloc(j + 1);
308 memcpy(peer_CN, ASN1_STRING_data(tmp), j);
312 else /* not a UTF8 name */ {
313 j = ASN1_STRING_to_UTF8(reinterpret_cast<unsigned char**>(&peer_CN), tmp);
316 for (set<string>::const_iterator n=trustednames.begin(); n!=trustednames.end(); n++) {
317 #ifdef HAVE_STRCASECMP
318 if (n->length() == j && !strncasecmp(peer_CN, n->c_str(), j)) {
320 if (n->length() == j && !strnicmp(peer_CN, n->c_str(), j)) {
322 log.debug("matched subject CN to a key name (%s)", n->c_str());
324 OPENSSL_free(peer_CN);
329 OPENSSL_free(peer_CN);
332 log.warn("no common name in certificate subject");
336 log.error("certificate has no subject?!");
342 bool AbstractPKIXTrustEngine::validateWithCRLs(
344 STACK_OF(X509)* certChain,
345 const CredentialResolver& credResolver,
346 CredentialCriteria* criteria,
347 const std::vector<XSECCryptoX509CRL*>* inlineCRLs
351 NDC ndc("validateWithCRLs");
353 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX");
356 log.error("X.509 credential was NULL, unable to perform validation");
360 if (criteria && criteria->getPeerName() && *(criteria->getPeerName())) {
361 log.debug("checking that the certificate name is acceptable");
362 if (criteria->getUsage()==Credential::UNSPECIFIED_CREDENTIAL)
363 criteria->setUsage(Credential::SIGNING_CREDENTIAL);
364 if (!checkEntityNames(certEE,credResolver,*criteria)) {
365 log.error("certificate name was not acceptable");
370 log.debug("performing certificate path validation...");
372 auto_ptr<PKIXValidationInfoIterator> pkix(getPKIXValidationInfoIterator(credResolver, criteria));
373 while (pkix->next()) {
378 (m_checkRevocation=="entityOnly" || m_checkRevocation=="fullChain"),
379 (m_checkRevocation=="fullChain"),
380 (m_checkRevocation=="entityOnly" || m_checkRevocation=="fullChain") ? inlineCRLs : nullptr
386 log.debug("failed to validate certificate chain using supplied PKIX information");
390 bool AbstractPKIXTrustEngine::validate(
392 STACK_OF(X509)* certChain,
393 const CredentialResolver& credResolver,
394 CredentialCriteria* criteria
397 return validateWithCRLs(certEE,certChain,credResolver,criteria);
400 bool AbstractPKIXTrustEngine::validate(
401 XSECCryptoX509* certEE,
402 const vector<XSECCryptoX509*>& certChain,
403 const CredentialResolver& credResolver,
404 CredentialCriteria* criteria
411 Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX").error("X.509 credential was NULL, unable to perform validation");
414 else if (certEE->getProviderName()!=DSIGConstants::s_unicodeStrPROVOpenSSL) {
415 Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX").error("only the OpenSSL XSEC provider is supported");
419 STACK_OF(X509)* untrusted=sk_X509_new_null();
420 for (vector<XSECCryptoX509*>::const_iterator i=certChain.begin(); i!=certChain.end(); ++i)
421 sk_X509_push(untrusted,static_cast<OpenSSLCryptoX509*>(*i)->getOpenSSLX509());
423 bool ret = validate(static_cast<OpenSSLCryptoX509*>(certEE)->getOpenSSLX509(), untrusted, credResolver, criteria);
424 sk_X509_free(untrusted);
428 bool AbstractPKIXTrustEngine::validate(
430 const CredentialResolver& credResolver,
431 CredentialCriteria* criteria
437 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX");
439 const KeyInfoResolver* inlineResolver = m_keyInfoResolver;
441 inlineResolver = XMLToolingConfig::getConfig().getKeyInfoResolver();
442 if (!inlineResolver) {
443 log.error("unable to perform PKIX validation, no KeyInfoResolver available");
447 // Pull the certificate chain out of the signature.
448 X509Credential* x509cred;
449 auto_ptr<Credential> cred(inlineResolver->resolve(&sig,X509Credential::RESOLVE_CERTS|X509Credential::RESOLVE_CRLS));
450 if (!cred.get() || !(x509cred=dynamic_cast<X509Credential*>(cred.get()))) {
451 log.error("unable to perform PKIX validation, signature does not contain any certificates");
454 const vector<XSECCryptoX509*>& certs = x509cred->getEntityCertificateChain();
456 log.error("unable to perform PKIX validation, signature does not contain any certificates");
460 log.debug("validating signature using certificate from within the signature");
462 // Find and save off a pointer to the certificate that unlocks the object.
463 // Most of the time, this will be the first one anyway.
464 XSECCryptoX509* certEE=nullptr;
465 SignatureValidator keyValidator;
466 for (vector<XSECCryptoX509*>::const_iterator i=certs.begin(); !certEE && i!=certs.end(); ++i) {
468 auto_ptr<XSECCryptoKey> key((*i)->clonePublicKey());
469 keyValidator.setKey(key.get());
470 keyValidator.validate(&sig);
471 log.debug("signature verified with key inside signature, attempting certificate validation...");
474 catch (ValidationException& ex) {
475 log.debug(ex.what());
480 log.debug("failed to verify signature with embedded certificates");
483 else if (certEE->getProviderName()!=DSIGConstants::s_unicodeStrPROVOpenSSL) {
484 log.error("only the OpenSSL XSEC provider is supported");
488 STACK_OF(X509)* untrusted=sk_X509_new_null();
489 for (vector<XSECCryptoX509*>::const_iterator i=certs.begin(); i!=certs.end(); ++i)
490 sk_X509_push(untrusted,static_cast<OpenSSLCryptoX509*>(*i)->getOpenSSLX509());
491 const vector<XSECCryptoX509CRL*>& crls = x509cred->getCRLs();
492 bool ret = validateWithCRLs(static_cast<OpenSSLCryptoX509*>(certEE)->getOpenSSLX509(), untrusted, credResolver, criteria, &crls);
493 sk_X509_free(untrusted);
497 bool AbstractPKIXTrustEngine::validate(
498 const XMLCh* sigAlgorithm,
503 const CredentialResolver& credResolver,
504 CredentialCriteria* criteria
510 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX");
513 log.error("unable to perform PKIX validation, KeyInfo not present");
517 const KeyInfoResolver* inlineResolver = m_keyInfoResolver;
519 inlineResolver = XMLToolingConfig::getConfig().getKeyInfoResolver();
520 if (!inlineResolver) {
521 log.error("unable to perform PKIX validation, no KeyInfoResolver available");
525 // Pull the certificate chain out of the signature.
526 X509Credential* x509cred;
527 auto_ptr<Credential> cred(inlineResolver->resolve(keyInfo,X509Credential::RESOLVE_CERTS));
528 if (!cred.get() || !(x509cred=dynamic_cast<X509Credential*>(cred.get()))) {
529 log.error("unable to perform PKIX validation, KeyInfo does not contain any certificates");
532 const vector<XSECCryptoX509*>& certs = x509cred->getEntityCertificateChain();
534 log.error("unable to perform PKIX validation, KeyInfo does not contain any certificates");
538 log.debug("validating signature using certificate from within KeyInfo");
540 // Find and save off a pointer to the certificate that unlocks the object.
541 // Most of the time, this will be the first one anyway.
542 XSECCryptoX509* certEE=nullptr;
543 for (vector<XSECCryptoX509*>::const_iterator i=certs.begin(); !certEE && i!=certs.end(); ++i) {
545 auto_ptr<XSECCryptoKey> key((*i)->clonePublicKey());
546 if (Signature::verifyRawSignature(key.get(), sigAlgorithm, sig, in, in_len)) {
547 log.debug("signature verified with key inside signature, attempting certificate validation...");
551 catch (SignatureException& ex) {
552 log.debug(ex.what());
557 log.debug("failed to verify signature with embedded certificates");
560 else if (certEE->getProviderName()!=DSIGConstants::s_unicodeStrPROVOpenSSL) {
561 log.error("only the OpenSSL XSEC provider is supported");
565 STACK_OF(X509)* untrusted=sk_X509_new_null();
566 for (vector<XSECCryptoX509*>::const_iterator i=certs.begin(); i!=certs.end(); ++i)
567 sk_X509_push(untrusted,static_cast<OpenSSLCryptoX509*>(*i)->getOpenSSLX509());
568 const vector<XSECCryptoX509CRL*>& crls = x509cred->getCRLs();
569 bool ret = validateWithCRLs(static_cast<OpenSSLCryptoX509*>(certEE)->getOpenSSLX509(), untrusted, credResolver, criteria, &crls);
570 sk_X509_free(untrusted);