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);
93 #if (OPENSSL_VERSION_NUMBER >= 0x00907000L)
96 for (vector<XSECCryptoX509CRL*>::const_iterator j=inlineCRLs->begin(); j!=inlineCRLs->end(); ++j) {
97 if ((*j)->getProviderName()==DSIGConstants::s_unicodeStrPROVOpenSSL) {
99 X509_STORE_add_crl(store, X509_CRL_dup(static_cast<OpenSSLCryptoX509CRL*>(*j)->getOpenSSLX509CRL()));
104 const vector<XSECCryptoX509CRL*>& crls = pkixInfo->getCRLs();
105 for (vector<XSECCryptoX509CRL*>::const_iterator j=crls.begin(); j!=crls.end(); ++j) {
106 if ((*j)->getProviderName()==DSIGConstants::s_unicodeStrPROVOpenSSL) {
108 X509_STORE_add_crl(store, X509_CRL_dup(static_cast<OpenSSLCryptoX509CRL*>(*j)->getOpenSSLX509CRL()));
112 log.debug("supplied (%d) CRL(s)", count);
114 X509_STORE_set_flags(store, fullCRLChain ? (X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL) : (X509_V_FLAG_CRL_CHECK));
116 else if (requireCRL) {
117 log.warn("CRL checking is required, but none were supplied");
118 sk_X509_free(CAstack);
119 X509_STORE_free(store);
124 log.warn("CRL checking is required, but OpenSSL version is too old");
125 sk_X509_free(CAstack);
126 X509_STORE_free(store);
129 else if ((inlineCRLs && !inlineCRLs->empty()) || !pkixInfo->getCRLs().empty()) {
130 log.warn("OpenSSL versions < 0.9.7 do not support CRL checking");
134 // AFAICT, EE and untrusted are passed in but not owned by the ctx.
135 #if (OPENSSL_VERSION_NUMBER >= 0x00907000L)
136 if (X509_STORE_CTX_init(&ctx,store,EE,untrusted)!=1) {
138 log.error("unable to initialize X509_STORE_CTX");
139 sk_X509_free(CAstack);
140 X509_STORE_free(store);
144 X509_STORE_CTX_init(&ctx,store,EE,untrusted);
147 // Seems to be most efficient to just pass in the CA stack.
148 X509_STORE_CTX_trusted_stack(&ctx,CAstack);
149 X509_STORE_CTX_set_depth(&ctx,100); // we check the depth down below
150 X509_STORE_CTX_set_verify_cb(&ctx,error_callback);
152 int ret=X509_verify_cert(&ctx);
154 // Now see if the depth was acceptable by counting the number of intermediates.
155 int depth=sk_X509_num(ctx.chain)-2;
156 if (pkixInfo->getVerificationDepth() < depth) {
158 "certificate chain was too long (%d intermediates, only %d allowed)",
159 (depth==-1) ? 0 : depth,
160 pkixInfo->getVerificationDepth()
167 X509_STORE_CTX_cleanup(&ctx);
168 X509_STORE_free(store);
169 sk_X509_free(CAstack);
172 log.debug("successfully validated certificate chain");
179 static XMLCh fullCRLChain[] = UNICODE_LITERAL_12(f,u,l,l,C,R,L,C,h,a,i,n);
180 static XMLCh checkRevocation[] = UNICODE_LITERAL_15(c,h,e,c,k,R,e,v,o,c,a,t,i,o,n);
183 AbstractPKIXTrustEngine::PKIXValidationInfoIterator::PKIXValidationInfoIterator()
187 AbstractPKIXTrustEngine::PKIXValidationInfoIterator::~PKIXValidationInfoIterator()
191 AbstractPKIXTrustEngine::AbstractPKIXTrustEngine(const xercesc::DOMElement* e)
193 m_fullCRLChain(XMLHelper::getAttrBool(e, false, fullCRLChain)),
194 m_checkRevocation(XMLHelper::getAttrString(e, nullptr, checkRevocation))
198 AbstractPKIXTrustEngine::~AbstractPKIXTrustEngine()
202 bool AbstractPKIXTrustEngine::checkEntityNames(
203 X509* certEE, const CredentialResolver& credResolver, const CredentialCriteria& criteria
206 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX");
208 // We resolve to a set of trusted credentials.
209 vector<const Credential*> creds;
210 credResolver.resolve(creds,&criteria);
212 // Build a list of acceptable names.
213 set<string> trustednames;
214 trustednames.insert(criteria.getPeerName());
215 for (vector<const Credential*>::const_iterator cred = creds.begin(); cred!=creds.end(); ++cred)
216 trustednames.insert((*cred)->getKeyNames().begin(), (*cred)->getKeyNames().end());
218 X509_NAME* subject=X509_get_subject_name(certEE);
220 // One way is a direct match to the subject DN.
221 // Seems that the way to do the compare is to write the X509_NAME into a BIO.
222 BIO* b = BIO_new(BIO_s_mem());
223 BIO* b2 = BIO_new(BIO_s_mem());
224 // The flags give us LDAP order instead of X.500, with a comma separator.
225 X509_NAME_print_ex(b,subject,0,XN_FLAG_RFC2253);
227 // The flags give us LDAP order instead of X.500, with a comma plus space separator.
228 X509_NAME_print_ex(b2,subject,0,XN_FLAG_RFC2253 + XN_FLAG_SEP_CPLUS_SPC - XN_FLAG_SEP_COMMA_PLUS);
231 BUF_MEM* bptr=nullptr;
232 BUF_MEM* bptr2=nullptr;
233 BIO_get_mem_ptr(b, &bptr);
234 BIO_get_mem_ptr(b2, &bptr2);
236 if (bptr && bptr->length > 0 && log.isDebugEnabled()) {
237 string subjectstr(bptr->data, bptr->length);
238 log.debug("certificate subject: %s", subjectstr.c_str());
241 // Check each keyname.
242 for (set<string>::const_iterator n=trustednames.begin(); bptr && bptr2 && n!=trustednames.end(); n++) {
243 #ifdef HAVE_STRCASECMP
244 if ((n->length() == bptr->length && !strncasecmp(n->c_str(), bptr->data, bptr->length)) ||
245 (n->length() == bptr2->length && !strncasecmp(n->c_str(), bptr2->data, bptr2->length))) {
247 if ((n->length() == bptr->length && !strnicmp(n->c_str(), bptr->data, bptr->length)) ||
248 (n->length() == bptr2->length && !strnicmp(n->c_str(), bptr2->data, bptr2->length))) {
250 log.debug("matched full subject DN to a key name (%s)", n->c_str());
259 log.debug("unable to match DN, trying TLS subjectAltName match");
260 STACK_OF(GENERAL_NAME)* altnames=(STACK_OF(GENERAL_NAME)*)X509_get_ext_d2i(certEE, NID_subject_alt_name, nullptr, nullptr);
262 int numalts = sk_GENERAL_NAME_num(altnames);
263 for (int an=0; an<numalts; an++) {
264 const GENERAL_NAME* check = sk_GENERAL_NAME_value(altnames, an);
265 if (check->type==GEN_DNS || check->type==GEN_URI) {
266 const char* altptr = (char*)ASN1_STRING_data(check->d.ia5);
267 const int altlen = ASN1_STRING_length(check->d.ia5);
268 for (set<string>::const_iterator n=trustednames.begin(); n!=trustednames.end(); n++) {
269 #ifdef HAVE_STRCASECMP
270 if ((check->type==GEN_DNS && n->length()==altlen && !strncasecmp(altptr,n->c_str(),altlen))
272 if ((check->type==GEN_DNS && n->length()==altlen && !strnicmp(altptr,n->c_str(),altlen))
274 || (check->type==GEN_URI && n->length()==altlen && !strncmp(altptr,n->c_str(),altlen))) {
275 log.debug("matched DNS/URI subjectAltName to a key name (%s)", n->c_str());
276 GENERAL_NAMES_free(altnames);
283 GENERAL_NAMES_free(altnames);
285 log.debug("unable to match subjectAltName, trying TLS CN match");
287 // Fetch the last CN RDN.
288 char* peer_CN = nullptr;
290 while ((j=X509_NAME_get_index_by_NID(subject, NID_commonName, i)) >= 0)
293 ASN1_STRING* tmp = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(subject, i));
294 // Copied in from libcurl.
295 /* In OpenSSL 0.9.7d and earlier, ASN1_STRING_to_UTF8 fails if the input
296 is already UTF-8 encoded. We check for this case and copy the raw
297 string manually to avoid the problem. */
298 if(tmp && ASN1_STRING_type(tmp) == V_ASN1_UTF8STRING) {
299 j = ASN1_STRING_length(tmp);
301 peer_CN = (char*)OPENSSL_malloc(j + 1);
302 memcpy(peer_CN, ASN1_STRING_data(tmp), j);
306 else /* not a UTF8 name */ {
307 j = ASN1_STRING_to_UTF8(reinterpret_cast<unsigned char**>(&peer_CN), tmp);
310 for (set<string>::const_iterator n=trustednames.begin(); n!=trustednames.end(); n++) {
311 #ifdef HAVE_STRCASECMP
312 if (n->length() == j && !strncasecmp(peer_CN, n->c_str(), j)) {
314 if (n->length() == j && !strnicmp(peer_CN, n->c_str(), j)) {
316 log.debug("matched subject CN to a key name (%s)", n->c_str());
318 OPENSSL_free(peer_CN);
323 OPENSSL_free(peer_CN);
326 log.warn("no common name in certificate subject");
330 log.error("certificate has no subject?!");
336 bool AbstractPKIXTrustEngine::validateWithCRLs(
338 STACK_OF(X509)* certChain,
339 const CredentialResolver& credResolver,
340 CredentialCriteria* criteria,
341 const std::vector<XSECCryptoX509CRL*>* inlineCRLs
345 NDC ndc("validateWithCRLs");
347 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX");
350 log.error("X.509 credential was NULL, unable to perform validation");
354 if (criteria && criteria->getPeerName() && *(criteria->getPeerName())) {
355 log.debug("checking that the certificate name is acceptable");
356 if (criteria->getUsage()==Credential::UNSPECIFIED_CREDENTIAL)
357 criteria->setUsage(Credential::SIGNING_CREDENTIAL);
358 if (!checkEntityNames(certEE,credResolver,*criteria)) {
359 log.error("certificate name was not acceptable");
364 log.debug("performing certificate path validation...");
366 auto_ptr<PKIXValidationInfoIterator> pkix(getPKIXValidationInfoIterator(credResolver, criteria));
367 while (pkix->next()) {
372 (m_checkRevocation=="entityOnly" || m_checkRevocation=="fullChain"),
373 (m_fullCRLChain || m_checkRevocation=="fullChain"),
380 log.debug("failed to validate certificate chain using supplied PKIX information");
384 bool AbstractPKIXTrustEngine::validate(
386 STACK_OF(X509)* certChain,
387 const CredentialResolver& credResolver,
388 CredentialCriteria* criteria
391 return validateWithCRLs(certEE,certChain,credResolver,criteria);
394 bool AbstractPKIXTrustEngine::validate(
395 XSECCryptoX509* certEE,
396 const vector<XSECCryptoX509*>& certChain,
397 const CredentialResolver& credResolver,
398 CredentialCriteria* criteria
405 Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX").error("X.509 credential was NULL, unable to perform validation");
408 else if (certEE->getProviderName()!=DSIGConstants::s_unicodeStrPROVOpenSSL) {
409 Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX").error("only the OpenSSL XSEC provider is supported");
413 STACK_OF(X509)* untrusted=sk_X509_new_null();
414 for (vector<XSECCryptoX509*>::const_iterator i=certChain.begin(); i!=certChain.end(); ++i)
415 sk_X509_push(untrusted,static_cast<OpenSSLCryptoX509*>(*i)->getOpenSSLX509());
417 bool ret = validate(static_cast<OpenSSLCryptoX509*>(certEE)->getOpenSSLX509(), untrusted, credResolver, criteria);
418 sk_X509_free(untrusted);
422 bool AbstractPKIXTrustEngine::validate(
424 const CredentialResolver& credResolver,
425 CredentialCriteria* criteria
431 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX");
433 const KeyInfoResolver* inlineResolver = m_keyInfoResolver;
435 inlineResolver = XMLToolingConfig::getConfig().getKeyInfoResolver();
436 if (!inlineResolver) {
437 log.error("unable to perform PKIX validation, no KeyInfoResolver available");
441 // Pull the certificate chain out of the signature.
442 X509Credential* x509cred;
443 auto_ptr<Credential> cred(inlineResolver->resolve(&sig,X509Credential::RESOLVE_CERTS|X509Credential::RESOLVE_CRLS));
444 if (!cred.get() || !(x509cred=dynamic_cast<X509Credential*>(cred.get()))) {
445 log.error("unable to perform PKIX validation, signature does not contain any certificates");
448 const vector<XSECCryptoX509*>& certs = x509cred->getEntityCertificateChain();
450 log.error("unable to perform PKIX validation, signature does not contain any certificates");
454 log.debug("validating signature using certificate from within the signature");
456 // Find and save off a pointer to the certificate that unlocks the object.
457 // Most of the time, this will be the first one anyway.
458 XSECCryptoX509* certEE=nullptr;
459 SignatureValidator keyValidator;
460 for (vector<XSECCryptoX509*>::const_iterator i=certs.begin(); !certEE && i!=certs.end(); ++i) {
462 auto_ptr<XSECCryptoKey> key((*i)->clonePublicKey());
463 keyValidator.setKey(key.get());
464 keyValidator.validate(&sig);
465 log.debug("signature verified with key inside signature, attempting certificate validation...");
468 catch (ValidationException& ex) {
469 log.debug(ex.what());
474 log.debug("failed to verify signature with embedded certificates");
477 else if (certEE->getProviderName()!=DSIGConstants::s_unicodeStrPROVOpenSSL) {
478 log.error("only the OpenSSL XSEC provider is supported");
482 STACK_OF(X509)* untrusted=sk_X509_new_null();
483 for (vector<XSECCryptoX509*>::const_iterator i=certs.begin(); i!=certs.end(); ++i)
484 sk_X509_push(untrusted,static_cast<OpenSSLCryptoX509*>(*i)->getOpenSSLX509());
485 const vector<XSECCryptoX509CRL*>& crls = x509cred->getCRLs();
486 bool ret = validateWithCRLs(static_cast<OpenSSLCryptoX509*>(certEE)->getOpenSSLX509(), untrusted, credResolver, criteria, &crls);
487 sk_X509_free(untrusted);
491 bool AbstractPKIXTrustEngine::validate(
492 const XMLCh* sigAlgorithm,
497 const CredentialResolver& credResolver,
498 CredentialCriteria* criteria
504 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX");
507 log.error("unable to perform PKIX validation, KeyInfo not present");
511 const KeyInfoResolver* inlineResolver = m_keyInfoResolver;
513 inlineResolver = XMLToolingConfig::getConfig().getKeyInfoResolver();
514 if (!inlineResolver) {
515 log.error("unable to perform PKIX validation, no KeyInfoResolver available");
519 // Pull the certificate chain out of the signature.
520 X509Credential* x509cred;
521 auto_ptr<Credential> cred(inlineResolver->resolve(keyInfo,X509Credential::RESOLVE_CERTS));
522 if (!cred.get() || !(x509cred=dynamic_cast<X509Credential*>(cred.get()))) {
523 log.error("unable to perform PKIX validation, KeyInfo does not contain any certificates");
526 const vector<XSECCryptoX509*>& certs = x509cred->getEntityCertificateChain();
528 log.error("unable to perform PKIX validation, KeyInfo does not contain any certificates");
532 log.debug("validating signature using certificate from within KeyInfo");
534 // Find and save off a pointer to the certificate that unlocks the object.
535 // Most of the time, this will be the first one anyway.
536 XSECCryptoX509* certEE=nullptr;
537 for (vector<XSECCryptoX509*>::const_iterator i=certs.begin(); !certEE && i!=certs.end(); ++i) {
539 auto_ptr<XSECCryptoKey> key((*i)->clonePublicKey());
540 if (Signature::verifyRawSignature(key.get(), sigAlgorithm, sig, in, in_len)) {
541 log.debug("signature verified with key inside signature, attempting certificate validation...");
545 catch (SignatureException& ex) {
546 log.debug(ex.what());
551 log.debug("failed to verify signature with embedded certificates");
554 else if (certEE->getProviderName()!=DSIGConstants::s_unicodeStrPROVOpenSSL) {
555 log.error("only the OpenSSL XSEC provider is supported");
559 STACK_OF(X509)* untrusted=sk_X509_new_null();
560 for (vector<XSECCryptoX509*>::const_iterator i=certs.begin(); i!=certs.end(); ++i)
561 sk_X509_push(untrusted,static_cast<OpenSSLCryptoX509*>(*i)->getOpenSSLX509());
562 const vector<XSECCryptoX509CRL*>& crls = x509cred->getCRLs();
563 bool ret = validateWithCRLs(static_cast<OpenSSLCryptoX509*>(certEE)->getOpenSSLX509(), untrusted, credResolver, criteria, &crls);
564 sk_X509_free(untrusted);