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)-1 && iii == sk_GENERAL_NAME_num(dp->distpoint->name.fullname)-1))) {
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 // Do a second pass verify with CRLs in place.
393 X509_STORE_CTX_set_flags(&ctx, fullCRLChain ? (X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL) : (X509_V_FLAG_CRL_CHECK));
394 ret=X509_verify_cert(&ctx);
396 log.warn("CRL checking is enabled, but OpenSSL version is too old");
402 X509_STORE_CTX_cleanup(&ctx);
403 X509_STORE_free(store);
404 sk_X509_free(CAstack);
407 log.debug("successfully validated certificate chain");
414 static XMLCh fullCRLChain[] = UNICODE_LITERAL_12(f,u,l,l,C,R,L,C,h,a,i,n);
415 static XMLCh checkRevocation[] = UNICODE_LITERAL_15(c,h,e,c,k,R,e,v,o,c,a,t,i,o,n);
418 AbstractPKIXTrustEngine::PKIXValidationInfoIterator::PKIXValidationInfoIterator()
422 AbstractPKIXTrustEngine::PKIXValidationInfoIterator::~PKIXValidationInfoIterator()
426 AbstractPKIXTrustEngine::AbstractPKIXTrustEngine(const xercesc::DOMElement* e)
428 m_fullCRLChain(XMLHelper::getAttrBool(e, false, fullCRLChain)),
429 m_checkRevocation(XMLHelper::getAttrString(e, nullptr, checkRevocation))
431 if (m_fullCRLChain) {
432 Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX").warn(
433 "fullCRLChain option is deprecated, setting checkRevocation to \"fullChain\""
435 m_checkRevocation = "fullChain";
437 else if (m_checkRevocation == "fullChain") {
438 m_fullCRLChain = true; // in case anything's using this
442 AbstractPKIXTrustEngine::~AbstractPKIXTrustEngine()
446 bool AbstractPKIXTrustEngine::checkEntityNames(
447 X509* certEE, const CredentialResolver& credResolver, const CredentialCriteria& criteria
450 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX");
452 // We resolve to a set of trusted credentials.
453 vector<const Credential*> creds;
454 credResolver.resolve(creds,&criteria);
456 // Build a list of acceptable names.
457 set<string> trustednames;
458 trustednames.insert(criteria.getPeerName());
459 for (vector<const Credential*>::const_iterator cred = creds.begin(); cred!=creds.end(); ++cred)
460 trustednames.insert((*cred)->getKeyNames().begin(), (*cred)->getKeyNames().end());
462 X509_NAME* subject=X509_get_subject_name(certEE);
464 // One way is a direct match to the subject DN.
465 // Seems that the way to do the compare is to write the X509_NAME into a BIO.
466 BIO* b = BIO_new(BIO_s_mem());
467 BIO* b2 = BIO_new(BIO_s_mem());
468 // The flags give us LDAP order instead of X.500, with a comma separator.
469 X509_NAME_print_ex(b,subject,0,XN_FLAG_RFC2253);
471 // The flags give us LDAP order instead of X.500, with a comma plus space separator.
472 X509_NAME_print_ex(b2,subject,0,XN_FLAG_RFC2253 + XN_FLAG_SEP_CPLUS_SPC - XN_FLAG_SEP_COMMA_PLUS);
475 BUF_MEM* bptr=nullptr;
476 BUF_MEM* bptr2=nullptr;
477 BIO_get_mem_ptr(b, &bptr);
478 BIO_get_mem_ptr(b2, &bptr2);
480 if (bptr && bptr->length > 0 && log.isDebugEnabled()) {
481 string subjectstr(bptr->data, bptr->length);
482 log.debug("certificate subject: %s", subjectstr.c_str());
485 // Check each keyname.
486 for (set<string>::const_iterator n=trustednames.begin(); bptr && bptr2 && n!=trustednames.end(); n++) {
487 #ifdef HAVE_STRCASECMP
488 if ((n->length() == bptr->length && !strncasecmp(n->c_str(), bptr->data, bptr->length)) ||
489 (n->length() == bptr2->length && !strncasecmp(n->c_str(), bptr2->data, bptr2->length))) {
491 if ((n->length() == bptr->length && !strnicmp(n->c_str(), bptr->data, bptr->length)) ||
492 (n->length() == bptr2->length && !strnicmp(n->c_str(), bptr2->data, bptr2->length))) {
494 log.debug("matched full subject DN to a key name (%s)", n->c_str());
503 log.debug("unable to match DN, trying TLS subjectAltName match");
504 STACK_OF(GENERAL_NAME)* altnames=(STACK_OF(GENERAL_NAME)*)X509_get_ext_d2i(certEE, NID_subject_alt_name, nullptr, nullptr);
506 int numalts = sk_GENERAL_NAME_num(altnames);
507 for (int an=0; an<numalts; an++) {
508 const GENERAL_NAME* check = sk_GENERAL_NAME_value(altnames, an);
509 if (check->type==GEN_DNS || check->type==GEN_URI) {
510 const char* altptr = (char*)ASN1_STRING_data(check->d.ia5);
511 const int altlen = ASN1_STRING_length(check->d.ia5);
512 for (set<string>::const_iterator n=trustednames.begin(); n!=trustednames.end(); n++) {
513 #ifdef HAVE_STRCASECMP
514 if ((check->type==GEN_DNS && n->length()==altlen && !strncasecmp(altptr,n->c_str(),altlen))
516 if ((check->type==GEN_DNS && n->length()==altlen && !strnicmp(altptr,n->c_str(),altlen))
518 || (check->type==GEN_URI && n->length()==altlen && !strncmp(altptr,n->c_str(),altlen))) {
519 log.debug("matched DNS/URI subjectAltName to a key name (%s)", n->c_str());
520 GENERAL_NAMES_free(altnames);
527 GENERAL_NAMES_free(altnames);
529 log.debug("unable to match subjectAltName, trying TLS CN match");
531 // Fetch the last CN RDN.
532 char* peer_CN = nullptr;
534 while ((j=X509_NAME_get_index_by_NID(subject, NID_commonName, i)) >= 0)
537 ASN1_STRING* tmp = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(subject, i));
538 // Copied in from libcurl.
539 /* In OpenSSL 0.9.7d and earlier, ASN1_STRING_to_UTF8 fails if the input
540 is already UTF-8 encoded. We check for this case and copy the raw
541 string manually to avoid the problem. */
542 if(tmp && ASN1_STRING_type(tmp) == V_ASN1_UTF8STRING) {
543 j = ASN1_STRING_length(tmp);
545 peer_CN = (char*)OPENSSL_malloc(j + 1);
546 memcpy(peer_CN, ASN1_STRING_data(tmp), j);
550 else /* not a UTF8 name */ {
551 j = ASN1_STRING_to_UTF8(reinterpret_cast<unsigned char**>(&peer_CN), tmp);
554 for (set<string>::const_iterator n=trustednames.begin(); n!=trustednames.end(); n++) {
555 #ifdef HAVE_STRCASECMP
556 if (n->length() == j && !strncasecmp(peer_CN, n->c_str(), j)) {
558 if (n->length() == j && !strnicmp(peer_CN, n->c_str(), j)) {
560 log.debug("matched subject CN to a key name (%s)", n->c_str());
562 OPENSSL_free(peer_CN);
567 OPENSSL_free(peer_CN);
570 log.warn("no common name in certificate subject");
574 log.error("certificate has no subject?!");
580 bool AbstractPKIXTrustEngine::validateWithCRLs(
582 STACK_OF(X509)* certChain,
583 const CredentialResolver& credResolver,
584 CredentialCriteria* criteria,
585 const std::vector<XSECCryptoX509CRL*>* inlineCRLs
589 NDC ndc("validateWithCRLs");
591 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX");
594 log.error("X.509 credential was NULL, unable to perform validation");
598 if (criteria && criteria->getPeerName() && *(criteria->getPeerName())) {
599 log.debug("checking that the certificate name is acceptable");
600 if (criteria->getUsage()==Credential::UNSPECIFIED_CREDENTIAL)
601 criteria->setUsage(Credential::SIGNING_CREDENTIAL);
602 if (!checkEntityNames(certEE,credResolver,*criteria)) {
603 log.error("certificate name was not acceptable");
608 log.debug("performing certificate path validation...");
610 auto_ptr<PKIXValidationInfoIterator> pkix(getPKIXValidationInfoIterator(credResolver, criteria));
611 while (pkix->next()) {
616 (m_checkRevocation=="entityOnly" || m_checkRevocation=="fullChain"),
617 (m_checkRevocation=="fullChain"),
618 (m_checkRevocation=="entityOnly" || m_checkRevocation=="fullChain") ? inlineCRLs : nullptr
624 log.debug("failed to validate certificate chain using supplied PKIX information");
628 bool AbstractPKIXTrustEngine::validate(
630 STACK_OF(X509)* certChain,
631 const CredentialResolver& credResolver,
632 CredentialCriteria* criteria
635 return validateWithCRLs(certEE,certChain,credResolver,criteria);
638 bool AbstractPKIXTrustEngine::validate(
639 XSECCryptoX509* certEE,
640 const vector<XSECCryptoX509*>& certChain,
641 const CredentialResolver& credResolver,
642 CredentialCriteria* criteria
649 Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX").error("X.509 credential was NULL, unable to perform validation");
652 else if (certEE->getProviderName()!=DSIGConstants::s_unicodeStrPROVOpenSSL) {
653 Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX").error("only the OpenSSL XSEC provider is supported");
657 STACK_OF(X509)* untrusted=sk_X509_new_null();
658 for (vector<XSECCryptoX509*>::const_iterator i=certChain.begin(); i!=certChain.end(); ++i)
659 sk_X509_push(untrusted,static_cast<OpenSSLCryptoX509*>(*i)->getOpenSSLX509());
661 bool ret = validate(static_cast<OpenSSLCryptoX509*>(certEE)->getOpenSSLX509(), untrusted, credResolver, criteria);
662 sk_X509_free(untrusted);
666 bool AbstractPKIXTrustEngine::validate(
668 const CredentialResolver& credResolver,
669 CredentialCriteria* criteria
675 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX");
677 const KeyInfoResolver* inlineResolver = m_keyInfoResolver;
679 inlineResolver = XMLToolingConfig::getConfig().getKeyInfoResolver();
680 if (!inlineResolver) {
681 log.error("unable to perform PKIX validation, no KeyInfoResolver available");
685 // Pull the certificate chain out of the signature.
686 X509Credential* x509cred;
687 auto_ptr<Credential> cred(inlineResolver->resolve(&sig,X509Credential::RESOLVE_CERTS|X509Credential::RESOLVE_CRLS));
688 if (!cred.get() || !(x509cred=dynamic_cast<X509Credential*>(cred.get()))) {
689 log.error("unable to perform PKIX validation, signature does not contain any certificates");
692 const vector<XSECCryptoX509*>& certs = x509cred->getEntityCertificateChain();
694 log.error("unable to perform PKIX validation, signature does not contain any certificates");
698 log.debug("validating signature using certificate from within the signature");
700 // Find and save off a pointer to the certificate that unlocks the object.
701 // Most of the time, this will be the first one anyway.
702 XSECCryptoX509* certEE=nullptr;
703 SignatureValidator keyValidator;
704 for (vector<XSECCryptoX509*>::const_iterator i=certs.begin(); !certEE && i!=certs.end(); ++i) {
706 auto_ptr<XSECCryptoKey> key((*i)->clonePublicKey());
707 keyValidator.setKey(key.get());
708 keyValidator.validate(&sig);
709 log.debug("signature verified with key inside signature, attempting certificate validation...");
712 catch (ValidationException& ex) {
713 log.debug(ex.what());
718 log.debug("failed to verify signature with embedded certificates");
721 else if (certEE->getProviderName()!=DSIGConstants::s_unicodeStrPROVOpenSSL) {
722 log.error("only the OpenSSL XSEC provider is supported");
726 STACK_OF(X509)* untrusted=sk_X509_new_null();
727 for (vector<XSECCryptoX509*>::const_iterator i=certs.begin(); i!=certs.end(); ++i)
728 sk_X509_push(untrusted,static_cast<OpenSSLCryptoX509*>(*i)->getOpenSSLX509());
729 const vector<XSECCryptoX509CRL*>& crls = x509cred->getCRLs();
730 bool ret = validateWithCRLs(static_cast<OpenSSLCryptoX509*>(certEE)->getOpenSSLX509(), untrusted, credResolver, criteria, &crls);
731 sk_X509_free(untrusted);
735 bool AbstractPKIXTrustEngine::validate(
736 const XMLCh* sigAlgorithm,
741 const CredentialResolver& credResolver,
742 CredentialCriteria* criteria
748 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX");
751 log.error("unable to perform PKIX validation, KeyInfo not present");
755 const KeyInfoResolver* inlineResolver = m_keyInfoResolver;
757 inlineResolver = XMLToolingConfig::getConfig().getKeyInfoResolver();
758 if (!inlineResolver) {
759 log.error("unable to perform PKIX validation, no KeyInfoResolver available");
763 // Pull the certificate chain out of the signature.
764 X509Credential* x509cred;
765 auto_ptr<Credential> cred(inlineResolver->resolve(keyInfo,X509Credential::RESOLVE_CERTS));
766 if (!cred.get() || !(x509cred=dynamic_cast<X509Credential*>(cred.get()))) {
767 log.error("unable to perform PKIX validation, KeyInfo does not contain any certificates");
770 const vector<XSECCryptoX509*>& certs = x509cred->getEntityCertificateChain();
772 log.error("unable to perform PKIX validation, KeyInfo does not contain any certificates");
776 log.debug("validating signature using certificate from within KeyInfo");
778 // Find and save off a pointer to the certificate that unlocks the object.
779 // Most of the time, this will be the first one anyway.
780 XSECCryptoX509* certEE=nullptr;
781 for (vector<XSECCryptoX509*>::const_iterator i=certs.begin(); !certEE && i!=certs.end(); ++i) {
783 auto_ptr<XSECCryptoKey> key((*i)->clonePublicKey());
784 if (Signature::verifyRawSignature(key.get(), sigAlgorithm, sig, in, in_len)) {
785 log.debug("signature verified with key inside signature, attempting certificate validation...");
789 catch (SignatureException& ex) {
790 log.debug(ex.what());
795 log.debug("failed to verify signature with embedded certificates");
798 else if (certEE->getProviderName()!=DSIGConstants::s_unicodeStrPROVOpenSSL) {
799 log.error("only the OpenSSL XSEC provider is supported");
803 STACK_OF(X509)* untrusted=sk_X509_new_null();
804 for (vector<XSECCryptoX509*>::const_iterator i=certs.begin(); i!=certs.end(); ++i)
805 sk_X509_push(untrusted,static_cast<OpenSSLCryptoX509*>(*i)->getOpenSSLX509());
806 const vector<XSECCryptoX509CRL*>& crls = x509cred->getCRLs();
807 bool ret = validateWithCRLs(static_cast<OpenSSLCryptoX509*>(certEE)->getOpenSSLX509(), untrusted, credResolver, criteria, &crls);
808 sk_X509_free(untrusted);