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/SecurityHelper.h"
34 #include "security/X509Credential.h"
35 #include "signature/SignatureValidator.h"
37 #include "util/PathResolver.h"
40 #include <openssl/x509_vfy.h>
41 #include <openssl/x509v3.h>
42 #include <xercesc/util/XMLUniDefs.hpp>
43 #include <xsec/enc/OpenSSL/OpenSSLCryptoX509.hpp>
45 using namespace xmlsignature;
46 using namespace xmltooling::logging;
47 using namespace xmltooling;
52 static int XMLTOOL_DLLLOCAL error_callback(int ok, X509_STORE_CTX* ctx)
55 Category::getInstance("OpenSSL").error("path validation failure: %s", X509_verify_cert_error_string(ctx->error));
59 static string XMLTOOL_DLLLOCAL X509_NAME_to_string(X509_NAME* n)
62 BIO* b = BIO_new(BIO_s_mem());
63 X509_NAME_print_ex(b,n,0,XN_FLAG_RFC2253);
65 BUF_MEM* bptr=nullptr;
66 BIO_get_mem_ptr(b, &bptr);
67 if (bptr && bptr->length > 0) {
68 s.append(bptr->data, bptr->length);
74 static time_t XMLTOOL_DLLLOCAL getCRLTime(const ASN1_TIME *a)
77 memset(&t, 0, sizeof(t));
78 // RFC 5280, sections 5.1.2.4 and 5.1.2.5 require thisUpdate and nextUpdate
79 // to be encoded as UTCTime until 2049, and RFC 5280 section 4.1.2.5.1
80 // further restricts the format to "YYMMDDHHMMSSZ" ("even where the number
81 // of seconds is zero").
82 // As long as OpenSSL doesn't provide any API to convert ASN1_TIME values
83 // time_t, we therefore have to parse it ourselves, unfortunately.
84 if (sscanf((const char*)a->data, "%2d%2d%2d%2d%2d%2dZ",
85 &t.tm_year, &t.tm_mon, &t.tm_mday,
86 &t.tm_hour, &t.tm_min, &t.tm_sec) == 6) {
87 if (t.tm_year <= 50) {
88 // RFC 5280, section 4.1.2.5.1
92 #if defined(HAVE_TIMEGM)
95 // Windows, and hopefully most others...?
96 return mktime(&t) - timezone;
102 static bool XMLTOOL_DLLLOCAL isFreshCRL(XSECCryptoX509CRL *c, Category* log=nullptr)
104 // eventually, these should be made configurable
105 #define MIN_SECS_REMAINING 86400
106 #define MIN_PERCENT_REMAINING 10
108 const X509_CRL* crl = static_cast<OpenSSLCryptoX509CRL*>(c)->getOpenSSLX509CRL();
109 time_t thisUpdate = getCRLTime(X509_CRL_get_lastUpdate(crl));
110 time_t nextUpdate = getCRLTime(X509_CRL_get_nextUpdate(crl));
111 time_t now = time(nullptr);
113 if (thisUpdate < 0 || nextUpdate < 0) {
114 // we failed to parse at least one of the fields (they were not encoded
115 // as required by RFC 5280, actually)
116 time_t exp = now + MIN_SECS_REMAINING;
118 log->warn("isFreshCRL (issuer '%s'): improperly encoded thisUpdate or nextUpdate field - falling back to simple time comparison",
119 (X509_NAME_to_string(X509_CRL_get_issuer(crl))).c_str());
121 return (X509_cmp_time(X509_CRL_get_nextUpdate(crl), &exp) > 0) ? true : false;
124 if (log && log->isDebugEnabled()) {
125 log->debug("isFreshCRL (issuer '%s'): %.0f seconds until nextUpdate (%3.2f%% elapsed since thisUpdate)",
126 (X509_NAME_to_string(X509_CRL_get_issuer(crl))).c_str(),
127 difftime(nextUpdate, now), (difftime(now, thisUpdate) * 100) / difftime(nextUpdate, thisUpdate));
130 // consider it recent enough if there are at least MIN_SECS_REMAINING
131 // to the nextUpdate, and at least MIN_PERCENT_REMAINING of its
132 // overall "validity" are remaining to the nextUpdate
133 return (now + MIN_SECS_REMAINING < nextUpdate) &&
134 ((difftime(nextUpdate, now) * 100) / difftime(nextUpdate, thisUpdate) > MIN_PERCENT_REMAINING);
140 static XSECCryptoX509CRL* XMLTOOL_DLLLOCAL getRemoteCRLs(const char* cdpuri, Category& log) {
141 // This is a temporary CRL cache implementation to avoid breaking binary compatibility
142 // for the library. Caching can't rely on any member objects within the TrustEngine,
143 // including locks, so we're using the global library lock for the time being.
144 // All other state is kept in the file system.
146 // minimum number of seconds between re-attempting a download from one particular CRLDP
147 #define MIN_RETRY_WAIT 60
149 // The filenames for the CRL cache are based on a hash of the CRL location.
150 string cdpfile = SecurityHelper::doHash("SHA1", cdpuri, strlen(cdpuri)) + ".crl";
151 XMLToolingConfig::getConfig().getPathResolver()->resolve(cdpfile, PathResolver::XMLTOOLING_RUN_FILE);
152 string cdpstaging = cdpfile + ".tmp";
153 string tsfile = cdpfile + ".ts";
155 time_t now = time(nullptr);
156 vector<XSECCryptoX509CRL*> crls;
159 // While holding the lock, check for a cached copy of the CRL, and remove "expired" ones.
160 Locker glock(&XMLToolingConfig::getConfig());
162 struct _stat stat_buf;
163 if (_stat(cdpfile.c_str(), &stat_buf) == 0) {
165 struct stat stat_buf;
166 if (stat(cdpfile.c_str(), &stat_buf) == 0) {
168 SecurityHelper::loadCRLsFromFile(crls, cdpfile.c_str());
169 if (crls.empty() || crls.front()->getProviderName() != DSIGConstants::s_unicodeStrPROVOpenSSL ||
170 X509_cmp_time(X509_CRL_get_nextUpdate(static_cast<OpenSSLCryptoX509CRL*>(crls.front())->getOpenSSLX509CRL()), &now) < 0) {
171 for_each(crls.begin(), crls.end(), xmltooling::cleanup<XSECCryptoX509CRL>());
173 remove(cdpfile.c_str()); // may as well delete the local copy
174 remove(tsfile.c_str());
175 log.info("deleting cached CRL from %s with nextUpdate field in the past", cdpuri);
179 catch (exception& ex) {
180 log.error("exception loading cached copy of CRL from %s: %s", cdpuri, ex.what());
183 if (crls.empty() || !isFreshCRL(crls.front(), &log)) {
184 bool updateTimestamp = true;
186 // If we get here, the cached copy didn't exist yet, or it's time to refresh.
187 // To limit the rate of unsuccessful attempts when a CRLDP is unreachable,
188 // we remember the timestamp of the last attempt (both successful/unsuccessful).
189 // We store this in the file system because of the binary compatibility issue.
192 Locker glock(&XMLToolingConfig::getConfig());
193 ifstream tssrc(tsfile.c_str());
201 if (difftime(now, ts) > MIN_RETRY_WAIT) {
202 SOAPTransport::Address addr("AbstractPKIXTrustEngine", cdpuri, cdpuri);
203 string scheme(addr.m_endpoint, strchr(addr.m_endpoint,':') - addr.m_endpoint);
204 auto_ptr<SOAPTransport> soap(XMLToolingConfig::getConfig().SOAPTransportManager.newPlugin(scheme.c_str(), addr));
206 istream& msg = soap->receive();
207 Locker glock(&XMLToolingConfig::getConfig());
208 ofstream out(cdpstaging.c_str(), fstream::trunc|fstream::binary);
211 SecurityHelper::loadCRLsFromFile(crls, cdpstaging.c_str());
212 if (crls.empty() || crls.front()->getProviderName() != DSIGConstants::s_unicodeStrPROVOpenSSL ||
213 X509_cmp_time(X509_CRL_get_nextUpdate(static_cast<OpenSSLCryptoX509CRL*>(crls.front())->getOpenSSLX509CRL()), &now) < 0) {
214 // The "new" CRL wasn't usable, so get rid of it.
215 for_each(crls.begin(), crls.end(), xmltooling::cleanup<XSECCryptoX509CRL>());
217 remove(cdpstaging.c_str());
218 log.error("ignoring CRL retrieved from %s with nextUpdate field in the past", cdpuri);
221 // "Commit" the new CRL. Note that we might add a CRL which doesn't pass
222 // isFreshCRL, but that's preferrable over adding none at all.
223 log.info("CRL refreshed from %s", cdpuri);
224 remove(cdpfile.c_str());
225 if (rename(cdpstaging.c_str(), cdpfile.c_str()) != 0)
226 log.error("unable to rename CRL staging file");
230 updateTimestamp = false; // don't update if we're within the backoff window
233 catch (exception& ex) {
234 log.error("exception downloading/caching CRL from %s: %s", cdpuri, ex.what());
237 if (updateTimestamp) {
238 // update the timestamp file
239 Locker glock(&XMLToolingConfig::getConfig());
240 ofstream tssink(tsfile.c_str(), fstream::trunc);
248 for_each(crls.begin() + 1, crls.end(), xmltooling::cleanup<XSECCryptoX509CRL>());
252 static bool XMLTOOL_DLLLOCAL validate(
254 STACK_OF(X509)* untrusted,
255 AbstractPKIXTrustEngine::PKIXValidationInfoIterator* pkixInfo,
258 const vector<XSECCryptoX509CRL*>* inlineCRLs=nullptr
261 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine");
263 // First we build a stack of CA certs. These objects are all referenced in place.
264 log.debug("supplying PKIX Validation information");
266 // We need this for CRL support.
267 X509_STORE* store=X509_STORE_new();
273 // This contains the state of the validate operation.
277 // AFAICT, EE and untrusted are passed in but not owned by the ctx.
278 #if (OPENSSL_VERSION_NUMBER >= 0x00907000L)
279 if (X509_STORE_CTX_init(&ctx,store,EE,untrusted)!=1) {
281 log.error("unable to initialize X509_STORE_CTX");
282 X509_STORE_free(store);
286 X509_STORE_CTX_init(&ctx,store,EE,untrusted);
289 STACK_OF(X509)* CAstack = sk_X509_new_null();
290 const vector<XSECCryptoX509*>& CAcerts = pkixInfo->getTrustAnchors();
291 for (vector<XSECCryptoX509*>::const_iterator i=CAcerts.begin(); i!=CAcerts.end(); ++i) {
292 if ((*i)->getProviderName()==DSIGConstants::s_unicodeStrPROVOpenSSL) {
293 sk_X509_push(CAstack,static_cast<OpenSSLCryptoX509*>(*i)->getOpenSSLX509());
297 log.debug("supplied (%d) CA certificate(s)", count);
299 // Seems to be most efficient to just pass in the CA stack.
300 X509_STORE_CTX_trusted_stack(&ctx,CAstack);
301 X509_STORE_CTX_set_depth(&ctx,100); // we check the depth down below
302 X509_STORE_CTX_set_verify_cb(&ctx,error_callback);
304 // Do a first pass verify. If CRLs aren't used, this is the only pass.
305 int ret=X509_verify_cert(&ctx);
307 // Now see if the depth was acceptable by counting the number of intermediates.
308 int depth=sk_X509_num(ctx.chain)-2;
309 if (pkixInfo->getVerificationDepth() < depth) {
311 "certificate chain was too long (%d intermediates, only %d allowed)",
312 (depth==-1) ? 0 : depth,
313 pkixInfo->getVerificationDepth()
320 #if (OPENSSL_VERSION_NUMBER >= 0x00907000L)
321 // When we add CRLs, we have to be sure the nextUpdate hasn't passed, because OpenSSL won't accept
322 // the CRL in that case. If we end up not adding a CRL for a particular link in the chain, the
323 // validation will fail (if the fullChain option was set).
324 set<string> crlissuers;
325 time_t now = time(nullptr);
327 for (vector<XSECCryptoX509CRL*>::const_iterator j=inlineCRLs->begin(); j!=inlineCRLs->end(); ++j) {
328 if ((*j)->getProviderName()==DSIGConstants::s_unicodeStrPROVOpenSSL &&
329 (X509_cmp_time(X509_CRL_get_nextUpdate(static_cast<OpenSSLCryptoX509CRL*>(*j)->getOpenSSLX509CRL()), &now) > 0)) {
331 X509_STORE_add_crl(store, X509_CRL_dup(static_cast<OpenSSLCryptoX509CRL*>(*j)->getOpenSSLX509CRL()));
332 string crlissuer(X509_NAME_to_string(X509_CRL_get_issuer(static_cast<OpenSSLCryptoX509CRL*>(*j)->getOpenSSLX509CRL())));
333 if (!crlissuer.empty()) {
334 log.debug("added inline CRL issued by (%s)", crlissuer.c_str());
335 crlissuers.insert(crlissuer);
340 const vector<XSECCryptoX509CRL*>& crls = pkixInfo->getCRLs();
341 for (vector<XSECCryptoX509CRL*>::const_iterator j=crls.begin(); j!=crls.end(); ++j) {
342 if ((*j)->getProviderName()==DSIGConstants::s_unicodeStrPROVOpenSSL &&
343 (X509_cmp_time(X509_CRL_get_nextUpdate(static_cast<OpenSSLCryptoX509CRL*>(*j)->getOpenSSLX509CRL()), &now) > 0)) {
345 X509_STORE_add_crl(store, X509_CRL_dup(static_cast<OpenSSLCryptoX509CRL*>(*j)->getOpenSSLX509CRL()));
346 string crlissuer(X509_NAME_to_string(X509_CRL_get_issuer(static_cast<OpenSSLCryptoX509CRL*>(*j)->getOpenSSLX509CRL())));
347 if (!crlissuer.empty()) {
348 log.debug("added CRL issued by (%s)", crlissuer.c_str());
349 crlissuers.insert(crlissuer);
354 for (int i = 0; i < sk_X509_num(untrusted); ++i) {
355 X509 *cert = sk_X509_value(untrusted, i);
356 string crlissuer(X509_NAME_to_string(X509_get_issuer_name(cert)));
357 if (crlissuers.count(crlissuer)) {
358 // We already have a CRL for this cert, so skip CRLDP processing for this one.
362 bool foundUsableCDP = false;
363 STACK_OF(DIST_POINT)* dps = (STACK_OF(DIST_POINT)*)X509_get_ext_d2i(cert, NID_crl_distribution_points, nullptr, nullptr);
364 for (int ii = 0; !foundUsableCDP && ii < sk_DIST_POINT_num(dps); ++ii) {
365 DIST_POINT* dp = sk_DIST_POINT_value(dps, ii);
366 if (!dp->distpoint || dp->distpoint->type != 0)
368 for (int iii = 0; !foundUsableCDP && iii < sk_GENERAL_NAME_num(dp->distpoint->name.fullname); ++iii) {
369 GENERAL_NAME* gen = sk_GENERAL_NAME_value(dp->distpoint->name.fullname, iii);
370 // Only consider HTTP URIs, and stop after the first one we find.
371 #ifdef HAVE_STRCASECMP
372 if (gen->type == GEN_URI && (!strncasecmp((const char*)gen->d.ia5->data, "http:", 5))) {
374 if (gen->type == GEN_URI && (!strnicmp((const char*)gen->d.ia5->data, "http:", 5))) {
376 const char* cdpuri = (const char*)gen->d.ia5->data;
377 auto_ptr<XSECCryptoX509CRL> crl(getRemoteCRLs(cdpuri, log));
378 if (crl.get() && crl->getProviderName()==DSIGConstants::s_unicodeStrPROVOpenSSL &&
379 (isFreshCRL(crl.get()) || (ii == sk_DIST_POINT_num(dps) && iii == sk_GENERAL_NAME_num(dp->distpoint->name.fullname)))) {
381 X509_STORE_add_crl(store, X509_CRL_dup(static_cast<OpenSSLCryptoX509CRL*>(crl.get())->getOpenSSLX509CRL()));
382 log.debug("added CRL issued by (%s)", crlissuer.c_str());
383 crlissuers.insert(crlissuer);
384 foundUsableCDP = true;
389 sk_DIST_POINT_free(dps);
392 if (!crlissuers.empty()) {
393 X509_STORE_set_flags(store, fullCRLChain ? (X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL) : (X509_V_FLAG_CRL_CHECK));
396 log.warn("CRL checking is enabled, but none were supplied");
397 X509_STORE_CTX_cleanup(&ctx);
398 X509_STORE_free(store);
399 sk_X509_free(CAstack);
403 log.warn("CRL checking is enabled, but OpenSSL version is too old");
404 X509_STORE_CTX_cleanup(&ctx);
405 X509_STORE_free(store);
406 sk_X509_free(CAstack);
409 // Do a second pass verify with CRLs in place.
410 ret=X509_verify_cert(&ctx);
414 X509_STORE_CTX_cleanup(&ctx);
415 X509_STORE_free(store);
416 sk_X509_free(CAstack);
419 log.debug("successfully validated certificate chain");
426 static XMLCh fullCRLChain[] = UNICODE_LITERAL_12(f,u,l,l,C,R,L,C,h,a,i,n);
427 static XMLCh checkRevocation[] = UNICODE_LITERAL_15(c,h,e,c,k,R,e,v,o,c,a,t,i,o,n);
430 AbstractPKIXTrustEngine::PKIXValidationInfoIterator::PKIXValidationInfoIterator()
434 AbstractPKIXTrustEngine::PKIXValidationInfoIterator::~PKIXValidationInfoIterator()
438 AbstractPKIXTrustEngine::AbstractPKIXTrustEngine(const xercesc::DOMElement* e)
440 m_fullCRLChain(XMLHelper::getAttrBool(e, false, fullCRLChain)),
441 m_checkRevocation(XMLHelper::getAttrString(e, nullptr, checkRevocation))
443 if (m_fullCRLChain) {
444 Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX").warn(
445 "fullCRLChain option is deprecated, setting checkRevocation to \"fullChain\""
447 m_checkRevocation = "fullChain";
449 else if (m_checkRevocation == "fullChain") {
450 m_fullCRLChain = true; // in case anything's using this
454 AbstractPKIXTrustEngine::~AbstractPKIXTrustEngine()
458 bool AbstractPKIXTrustEngine::checkEntityNames(
459 X509* certEE, const CredentialResolver& credResolver, const CredentialCriteria& criteria
462 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX");
464 // We resolve to a set of trusted credentials.
465 vector<const Credential*> creds;
466 credResolver.resolve(creds,&criteria);
468 // Build a list of acceptable names.
469 set<string> trustednames;
470 trustednames.insert(criteria.getPeerName());
471 for (vector<const Credential*>::const_iterator cred = creds.begin(); cred!=creds.end(); ++cred)
472 trustednames.insert((*cred)->getKeyNames().begin(), (*cred)->getKeyNames().end());
474 X509_NAME* subject=X509_get_subject_name(certEE);
476 // One way is a direct match to the subject DN.
477 // Seems that the way to do the compare is to write the X509_NAME into a BIO.
478 BIO* b = BIO_new(BIO_s_mem());
479 BIO* b2 = BIO_new(BIO_s_mem());
480 // The flags give us LDAP order instead of X.500, with a comma separator.
481 X509_NAME_print_ex(b,subject,0,XN_FLAG_RFC2253);
483 // The flags give us LDAP order instead of X.500, with a comma plus space separator.
484 X509_NAME_print_ex(b2,subject,0,XN_FLAG_RFC2253 + XN_FLAG_SEP_CPLUS_SPC - XN_FLAG_SEP_COMMA_PLUS);
487 BUF_MEM* bptr=nullptr;
488 BUF_MEM* bptr2=nullptr;
489 BIO_get_mem_ptr(b, &bptr);
490 BIO_get_mem_ptr(b2, &bptr2);
492 if (bptr && bptr->length > 0 && log.isDebugEnabled()) {
493 string subjectstr(bptr->data, bptr->length);
494 log.debug("certificate subject: %s", subjectstr.c_str());
497 // Check each keyname.
498 for (set<string>::const_iterator n=trustednames.begin(); bptr && bptr2 && n!=trustednames.end(); n++) {
499 #ifdef HAVE_STRCASECMP
500 if ((n->length() == bptr->length && !strncasecmp(n->c_str(), bptr->data, bptr->length)) ||
501 (n->length() == bptr2->length && !strncasecmp(n->c_str(), bptr2->data, bptr2->length))) {
503 if ((n->length() == bptr->length && !strnicmp(n->c_str(), bptr->data, bptr->length)) ||
504 (n->length() == bptr2->length && !strnicmp(n->c_str(), bptr2->data, bptr2->length))) {
506 log.debug("matched full subject DN to a key name (%s)", n->c_str());
515 log.debug("unable to match DN, trying TLS subjectAltName match");
516 STACK_OF(GENERAL_NAME)* altnames=(STACK_OF(GENERAL_NAME)*)X509_get_ext_d2i(certEE, NID_subject_alt_name, nullptr, nullptr);
518 int numalts = sk_GENERAL_NAME_num(altnames);
519 for (int an=0; an<numalts; an++) {
520 const GENERAL_NAME* check = sk_GENERAL_NAME_value(altnames, an);
521 if (check->type==GEN_DNS || check->type==GEN_URI) {
522 const char* altptr = (char*)ASN1_STRING_data(check->d.ia5);
523 const int altlen = ASN1_STRING_length(check->d.ia5);
524 for (set<string>::const_iterator n=trustednames.begin(); n!=trustednames.end(); n++) {
525 #ifdef HAVE_STRCASECMP
526 if ((check->type==GEN_DNS && n->length()==altlen && !strncasecmp(altptr,n->c_str(),altlen))
528 if ((check->type==GEN_DNS && n->length()==altlen && !strnicmp(altptr,n->c_str(),altlen))
530 || (check->type==GEN_URI && n->length()==altlen && !strncmp(altptr,n->c_str(),altlen))) {
531 log.debug("matched DNS/URI subjectAltName to a key name (%s)", n->c_str());
532 GENERAL_NAMES_free(altnames);
539 GENERAL_NAMES_free(altnames);
541 log.debug("unable to match subjectAltName, trying TLS CN match");
543 // Fetch the last CN RDN.
544 char* peer_CN = nullptr;
546 while ((j=X509_NAME_get_index_by_NID(subject, NID_commonName, i)) >= 0)
549 ASN1_STRING* tmp = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(subject, i));
550 // Copied in from libcurl.
551 /* In OpenSSL 0.9.7d and earlier, ASN1_STRING_to_UTF8 fails if the input
552 is already UTF-8 encoded. We check for this case and copy the raw
553 string manually to avoid the problem. */
554 if(tmp && ASN1_STRING_type(tmp) == V_ASN1_UTF8STRING) {
555 j = ASN1_STRING_length(tmp);
557 peer_CN = (char*)OPENSSL_malloc(j + 1);
558 memcpy(peer_CN, ASN1_STRING_data(tmp), j);
562 else /* not a UTF8 name */ {
563 j = ASN1_STRING_to_UTF8(reinterpret_cast<unsigned char**>(&peer_CN), tmp);
566 for (set<string>::const_iterator n=trustednames.begin(); n!=trustednames.end(); n++) {
567 #ifdef HAVE_STRCASECMP
568 if (n->length() == j && !strncasecmp(peer_CN, n->c_str(), j)) {
570 if (n->length() == j && !strnicmp(peer_CN, n->c_str(), j)) {
572 log.debug("matched subject CN to a key name (%s)", n->c_str());
574 OPENSSL_free(peer_CN);
579 OPENSSL_free(peer_CN);
582 log.warn("no common name in certificate subject");
586 log.error("certificate has no subject?!");
592 bool AbstractPKIXTrustEngine::validateWithCRLs(
594 STACK_OF(X509)* certChain,
595 const CredentialResolver& credResolver,
596 CredentialCriteria* criteria,
597 const std::vector<XSECCryptoX509CRL*>* inlineCRLs
601 NDC ndc("validateWithCRLs");
603 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX");
606 log.error("X.509 credential was NULL, unable to perform validation");
610 if (criteria && criteria->getPeerName() && *(criteria->getPeerName())) {
611 log.debug("checking that the certificate name is acceptable");
612 if (criteria->getUsage()==Credential::UNSPECIFIED_CREDENTIAL)
613 criteria->setUsage(Credential::SIGNING_CREDENTIAL);
614 if (!checkEntityNames(certEE,credResolver,*criteria)) {
615 log.error("certificate name was not acceptable");
620 log.debug("performing certificate path validation...");
622 auto_ptr<PKIXValidationInfoIterator> pkix(getPKIXValidationInfoIterator(credResolver, criteria));
623 while (pkix->next()) {
628 (m_checkRevocation=="entityOnly" || m_checkRevocation=="fullChain"),
629 (m_checkRevocation=="fullChain"),
630 (m_checkRevocation=="entityOnly" || m_checkRevocation=="fullChain") ? inlineCRLs : nullptr
636 log.debug("failed to validate certificate chain using supplied PKIX information");
640 bool AbstractPKIXTrustEngine::validate(
642 STACK_OF(X509)* certChain,
643 const CredentialResolver& credResolver,
644 CredentialCriteria* criteria
647 return validateWithCRLs(certEE,certChain,credResolver,criteria);
650 bool AbstractPKIXTrustEngine::validate(
651 XSECCryptoX509* certEE,
652 const vector<XSECCryptoX509*>& certChain,
653 const CredentialResolver& credResolver,
654 CredentialCriteria* criteria
661 Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX").error("X.509 credential was NULL, unable to perform validation");
664 else if (certEE->getProviderName()!=DSIGConstants::s_unicodeStrPROVOpenSSL) {
665 Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX").error("only the OpenSSL XSEC provider is supported");
669 STACK_OF(X509)* untrusted=sk_X509_new_null();
670 for (vector<XSECCryptoX509*>::const_iterator i=certChain.begin(); i!=certChain.end(); ++i)
671 sk_X509_push(untrusted,static_cast<OpenSSLCryptoX509*>(*i)->getOpenSSLX509());
673 bool ret = validate(static_cast<OpenSSLCryptoX509*>(certEE)->getOpenSSLX509(), untrusted, credResolver, criteria);
674 sk_X509_free(untrusted);
678 bool AbstractPKIXTrustEngine::validate(
680 const CredentialResolver& credResolver,
681 CredentialCriteria* criteria
687 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX");
689 const KeyInfoResolver* inlineResolver = m_keyInfoResolver;
691 inlineResolver = XMLToolingConfig::getConfig().getKeyInfoResolver();
692 if (!inlineResolver) {
693 log.error("unable to perform PKIX validation, no KeyInfoResolver available");
697 // Pull the certificate chain out of the signature.
698 X509Credential* x509cred;
699 auto_ptr<Credential> cred(inlineResolver->resolve(&sig,X509Credential::RESOLVE_CERTS|X509Credential::RESOLVE_CRLS));
700 if (!cred.get() || !(x509cred=dynamic_cast<X509Credential*>(cred.get()))) {
701 log.error("unable to perform PKIX validation, signature does not contain any certificates");
704 const vector<XSECCryptoX509*>& certs = x509cred->getEntityCertificateChain();
706 log.error("unable to perform PKIX validation, signature does not contain any certificates");
710 log.debug("validating signature using certificate from within the signature");
712 // Find and save off a pointer to the certificate that unlocks the object.
713 // Most of the time, this will be the first one anyway.
714 XSECCryptoX509* certEE=nullptr;
715 SignatureValidator keyValidator;
716 for (vector<XSECCryptoX509*>::const_iterator i=certs.begin(); !certEE && i!=certs.end(); ++i) {
718 auto_ptr<XSECCryptoKey> key((*i)->clonePublicKey());
719 keyValidator.setKey(key.get());
720 keyValidator.validate(&sig);
721 log.debug("signature verified with key inside signature, attempting certificate validation...");
724 catch (ValidationException& ex) {
725 log.debug(ex.what());
730 log.debug("failed to verify signature with embedded certificates");
733 else if (certEE->getProviderName()!=DSIGConstants::s_unicodeStrPROVOpenSSL) {
734 log.error("only the OpenSSL XSEC provider is supported");
738 STACK_OF(X509)* untrusted=sk_X509_new_null();
739 for (vector<XSECCryptoX509*>::const_iterator i=certs.begin(); i!=certs.end(); ++i)
740 sk_X509_push(untrusted,static_cast<OpenSSLCryptoX509*>(*i)->getOpenSSLX509());
741 const vector<XSECCryptoX509CRL*>& crls = x509cred->getCRLs();
742 bool ret = validateWithCRLs(static_cast<OpenSSLCryptoX509*>(certEE)->getOpenSSLX509(), untrusted, credResolver, criteria, &crls);
743 sk_X509_free(untrusted);
747 bool AbstractPKIXTrustEngine::validate(
748 const XMLCh* sigAlgorithm,
753 const CredentialResolver& credResolver,
754 CredentialCriteria* criteria
760 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX");
763 log.error("unable to perform PKIX validation, KeyInfo not present");
767 const KeyInfoResolver* inlineResolver = m_keyInfoResolver;
769 inlineResolver = XMLToolingConfig::getConfig().getKeyInfoResolver();
770 if (!inlineResolver) {
771 log.error("unable to perform PKIX validation, no KeyInfoResolver available");
775 // Pull the certificate chain out of the signature.
776 X509Credential* x509cred;
777 auto_ptr<Credential> cred(inlineResolver->resolve(keyInfo,X509Credential::RESOLVE_CERTS));
778 if (!cred.get() || !(x509cred=dynamic_cast<X509Credential*>(cred.get()))) {
779 log.error("unable to perform PKIX validation, KeyInfo does not contain any certificates");
782 const vector<XSECCryptoX509*>& certs = x509cred->getEntityCertificateChain();
784 log.error("unable to perform PKIX validation, KeyInfo does not contain any certificates");
788 log.debug("validating signature using certificate from within KeyInfo");
790 // Find and save off a pointer to the certificate that unlocks the object.
791 // Most of the time, this will be the first one anyway.
792 XSECCryptoX509* certEE=nullptr;
793 for (vector<XSECCryptoX509*>::const_iterator i=certs.begin(); !certEE && i!=certs.end(); ++i) {
795 auto_ptr<XSECCryptoKey> key((*i)->clonePublicKey());
796 if (Signature::verifyRawSignature(key.get(), sigAlgorithm, sig, in, in_len)) {
797 log.debug("signature verified with key inside signature, attempting certificate validation...");
801 catch (SignatureException& ex) {
802 log.debug(ex.what());
807 log.debug("failed to verify signature with embedded certificates");
810 else if (certEE->getProviderName()!=DSIGConstants::s_unicodeStrPROVOpenSSL) {
811 log.error("only the OpenSSL XSEC provider is supported");
815 STACK_OF(X509)* untrusted=sk_X509_new_null();
816 for (vector<XSECCryptoX509*>::const_iterator i=certs.begin(); i!=certs.end(); ++i)
817 sk_X509_push(untrusted,static_cast<OpenSSLCryptoX509*>(*i)->getOpenSSLX509());
818 const vector<XSECCryptoX509CRL*>& crls = x509cred->getCRLs();
819 bool ret = validateWithCRLs(static_cast<OpenSSLCryptoX509*>(certEE)->getOpenSSLX509(), untrusted, credResolver, criteria, &crls);
820 sk_X509_free(untrusted);