2 * Licensed to the University Corporation for Advanced Internet
3 * Development, Inc. (UCAID) under one or more contributor license
4 * agreements. See the NOTICE file distributed with this work for
5 * additional information regarding copyright ownership.
7 * UCAID licenses this file to you under the Apache License,
8 * Version 2.0 (the "License"); you may not use this file except
9 * in compliance with the License. You may obtain a copy of the
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17 * either express or implied. See the License for the specific
18 * language governing permissions and limitations under the License.
22 * AbstractPKIXTrustEngine.cpp
24 * A trust engine that uses X.509 trust anchors and CRLs associated with a KeyInfoSource
25 * to perform PKIX validation of signatures and certificates.
30 #include "security/AbstractPKIXTrustEngine.h"
31 #include "signature/KeyInfo.h"
32 #include "signature/Signature.h"
33 #include "security/CredentialCriteria.h"
34 #include "security/CredentialResolver.h"
35 #include "security/KeyInfoResolver.h"
36 #include "security/OpenSSLCryptoX509CRL.h"
37 #include "security/SecurityHelper.h"
38 #include "security/X509Credential.h"
39 #include "signature/SignatureValidator.h"
41 #include "util/PathResolver.h"
44 #include <openssl/x509_vfy.h>
45 #include <openssl/x509v3.h>
46 #include <xercesc/util/XMLUniDefs.hpp>
47 #include <xsec/enc/OpenSSL/OpenSSLCryptoX509.hpp>
49 using namespace xmlsignature;
50 using namespace xmltooling::logging;
51 using namespace xmltooling;
56 static int XMLTOOL_DLLLOCAL error_callback(int ok, X509_STORE_CTX* ctx)
59 Category::getInstance("OpenSSL").error("path validation failure: %s", X509_verify_cert_error_string(ctx->error));
63 static string XMLTOOL_DLLLOCAL X509_NAME_to_string(X509_NAME* n)
66 BIO* b = BIO_new(BIO_s_mem());
67 X509_NAME_print_ex(b,n,0,XN_FLAG_RFC2253);
69 BUF_MEM* bptr=nullptr;
70 BIO_get_mem_ptr(b, &bptr);
71 if (bptr && bptr->length > 0) {
72 s.append(bptr->data, bptr->length);
78 static time_t XMLTOOL_DLLLOCAL getCRLTime(const ASN1_TIME *a)
81 memset(&t, 0, sizeof(t));
82 // RFC 5280, sections 5.1.2.4 and 5.1.2.5 require thisUpdate and nextUpdate
83 // to be encoded as UTCTime until 2049, and RFC 5280 section 4.1.2.5.1
84 // further restricts the format to "YYMMDDHHMMSSZ" ("even where the number
85 // of seconds is zero").
86 // As long as OpenSSL doesn't provide any API to convert ASN1_TIME values
87 // time_t, we therefore have to parse it ourselves, unfortunately.
88 if (sscanf((const char*)a->data, "%2d%2d%2d%2d%2d%2dZ",
89 &t.tm_year, &t.tm_mon, &t.tm_mday,
90 &t.tm_hour, &t.tm_min, &t.tm_sec) == 6) {
91 if (t.tm_year <= 50) {
92 // RFC 5280, section 4.1.2.5.1
96 #if defined(HAVE_TIMEGM)
99 // Windows, and hopefully most others...?
100 return mktime(&t) - timezone;
106 static bool XMLTOOL_DLLLOCAL isFreshCRL(XSECCryptoX509CRL *c, Category* log=nullptr)
108 // eventually, these should be made configurable
109 #define MIN_SECS_REMAINING 86400
110 #define MIN_PERCENT_REMAINING 10
112 const X509_CRL* crl = static_cast<OpenSSLCryptoX509CRL*>(c)->getOpenSSLX509CRL();
113 time_t thisUpdate = getCRLTime(X509_CRL_get_lastUpdate(crl));
114 time_t nextUpdate = getCRLTime(X509_CRL_get_nextUpdate(crl));
115 time_t now = time(nullptr);
117 if (thisUpdate < 0 || nextUpdate < 0) {
118 // we failed to parse at least one of the fields (they were not encoded
119 // as required by RFC 5280, actually)
120 time_t exp = now + MIN_SECS_REMAINING;
122 log->warn("isFreshCRL (issuer '%s'): improperly encoded thisUpdate or nextUpdate field - falling back to simple time comparison",
123 (X509_NAME_to_string(X509_CRL_get_issuer(crl))).c_str());
125 return (X509_cmp_time(X509_CRL_get_nextUpdate(crl), &exp) > 0) ? true : false;
128 if (log && log->isDebugEnabled()) {
129 log->debug("isFreshCRL (issuer '%s'): %.0f seconds until nextUpdate (%3.2f%% elapsed since thisUpdate)",
130 (X509_NAME_to_string(X509_CRL_get_issuer(crl))).c_str(),
131 difftime(nextUpdate, now), (difftime(now, thisUpdate) * 100) / difftime(nextUpdate, thisUpdate));
134 // consider it recent enough if there are at least MIN_SECS_REMAINING
135 // to the nextUpdate, and at least MIN_PERCENT_REMAINING of its
136 // overall "validity" are remaining to the nextUpdate
137 return (now + MIN_SECS_REMAINING < nextUpdate) &&
138 ((difftime(nextUpdate, now) * 100) / difftime(nextUpdate, thisUpdate) > MIN_PERCENT_REMAINING);
144 static XSECCryptoX509CRL* XMLTOOL_DLLLOCAL getRemoteCRLs(const char* cdpuri, Category& log) {
145 // This is a temporary CRL cache implementation to avoid breaking binary compatibility
146 // for the library. Caching can't rely on any member objects within the TrustEngine,
147 // including locks, so we're using the global library lock for the time being.
148 // All other state is kept in the file system.
150 // minimum number of seconds between re-attempting a download from one particular CRLDP
151 #define MIN_RETRY_WAIT 60
153 // The filenames for the CRL cache are based on a hash of the CRL location.
154 string cdpfile = SecurityHelper::doHash("SHA1", cdpuri, strlen(cdpuri)) + ".crl";
155 XMLToolingConfig::getConfig().getPathResolver()->resolve(cdpfile, PathResolver::XMLTOOLING_RUN_FILE);
156 string cdpstaging = cdpfile + ".tmp";
157 string tsfile = cdpfile + ".ts";
159 time_t now = time(nullptr);
160 vector<XSECCryptoX509CRL*> crls;
163 // While holding the lock, check for a cached copy of the CRL, and remove "expired" ones.
164 Locker glock(&XMLToolingConfig::getConfig());
166 struct _stat stat_buf;
167 if (_stat(cdpfile.c_str(), &stat_buf) == 0) {
169 struct stat stat_buf;
170 if (stat(cdpfile.c_str(), &stat_buf) == 0) {
172 SecurityHelper::loadCRLsFromFile(crls, cdpfile.c_str());
173 if (crls.empty() || crls.front()->getProviderName() != DSIGConstants::s_unicodeStrPROVOpenSSL ||
174 X509_cmp_time(X509_CRL_get_nextUpdate(static_cast<OpenSSLCryptoX509CRL*>(crls.front())->getOpenSSLX509CRL()), &now) < 0) {
175 for_each(crls.begin(), crls.end(), xmltooling::cleanup<XSECCryptoX509CRL>());
177 remove(cdpfile.c_str()); // may as well delete the local copy
178 remove(tsfile.c_str());
179 log.info("deleting cached CRL from %s with nextUpdate field in the past", cdpuri);
183 catch (exception& ex) {
184 log.error("exception loading cached copy of CRL from %s: %s", cdpuri, ex.what());
187 if (crls.empty() || !isFreshCRL(crls.front(), &log)) {
188 bool updateTimestamp = true;
190 // If we get here, the cached copy didn't exist yet, or it's time to refresh.
191 // To limit the rate of unsuccessful attempts when a CRLDP is unreachable,
192 // we remember the timestamp of the last attempt (both successful/unsuccessful).
193 // We store this in the file system because of the binary compatibility issue.
196 Locker glock(&XMLToolingConfig::getConfig());
197 ifstream tssrc(tsfile.c_str());
205 if (difftime(now, ts) > MIN_RETRY_WAIT) {
206 SOAPTransport::Address addr("AbstractPKIXTrustEngine", cdpuri, cdpuri);
207 string scheme(addr.m_endpoint, strchr(addr.m_endpoint,':') - addr.m_endpoint);
208 auto_ptr<SOAPTransport> soap(XMLToolingConfig::getConfig().SOAPTransportManager.newPlugin(scheme.c_str(), addr));
210 istream& msg = soap->receive();
211 Locker glock(&XMLToolingConfig::getConfig());
212 ofstream out(cdpstaging.c_str(), fstream::trunc|fstream::binary);
215 SecurityHelper::loadCRLsFromFile(crls, cdpstaging.c_str());
216 if (crls.empty() || crls.front()->getProviderName() != DSIGConstants::s_unicodeStrPROVOpenSSL ||
217 X509_cmp_time(X509_CRL_get_nextUpdate(static_cast<OpenSSLCryptoX509CRL*>(crls.front())->getOpenSSLX509CRL()), &now) < 0) {
218 // The "new" CRL wasn't usable, so get rid of it.
219 for_each(crls.begin(), crls.end(), xmltooling::cleanup<XSECCryptoX509CRL>());
221 remove(cdpstaging.c_str());
222 log.error("ignoring CRL retrieved from %s with nextUpdate field in the past", cdpuri);
225 // "Commit" the new CRL. Note that we might add a CRL which doesn't pass
226 // isFreshCRL, but that's preferrable over adding none at all.
227 log.info("CRL refreshed from %s", cdpuri);
228 remove(cdpfile.c_str());
229 if (rename(cdpstaging.c_str(), cdpfile.c_str()) != 0)
230 log.error("unable to rename CRL staging file");
234 updateTimestamp = false; // don't update if we're within the backoff window
237 catch (exception& ex) {
238 log.error("exception downloading/caching CRL from %s: %s", cdpuri, ex.what());
241 if (updateTimestamp) {
242 // update the timestamp file
243 Locker glock(&XMLToolingConfig::getConfig());
244 ofstream tssink(tsfile.c_str(), fstream::trunc);
252 for_each(crls.begin() + 1, crls.end(), xmltooling::cleanup<XSECCryptoX509CRL>());
256 static bool XMLTOOL_DLLLOCAL validate(
258 STACK_OF(X509)* untrusted,
259 AbstractPKIXTrustEngine::PKIXValidationInfoIterator* pkixInfo,
262 const vector<XSECCryptoX509CRL*>* inlineCRLs=nullptr
265 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine");
267 // First we build a stack of CA certs. These objects are all referenced in place.
268 log.debug("supplying PKIX Validation information");
270 // We need this for CRL support.
271 X509_STORE* store=X509_STORE_new();
277 // This contains the state of the validate operation.
281 // AFAICT, EE and untrusted are passed in but not owned by the ctx.
282 #if (OPENSSL_VERSION_NUMBER >= 0x00907000L)
283 if (X509_STORE_CTX_init(&ctx,store,EE,untrusted)!=1) {
285 log.error("unable to initialize X509_STORE_CTX");
286 X509_STORE_free(store);
290 X509_STORE_CTX_init(&ctx,store,EE,untrusted);
293 STACK_OF(X509)* CAstack = sk_X509_new_null();
294 const vector<XSECCryptoX509*>& CAcerts = pkixInfo->getTrustAnchors();
295 for (vector<XSECCryptoX509*>::const_iterator i=CAcerts.begin(); i!=CAcerts.end(); ++i) {
296 if ((*i)->getProviderName()==DSIGConstants::s_unicodeStrPROVOpenSSL) {
297 sk_X509_push(CAstack,static_cast<OpenSSLCryptoX509*>(*i)->getOpenSSLX509());
301 log.debug("supplied (%d) CA certificate(s)", count);
303 // Seems to be most efficient to just pass in the CA stack.
304 X509_STORE_CTX_trusted_stack(&ctx,CAstack);
305 X509_STORE_CTX_set_depth(&ctx,100); // we check the depth down below
306 X509_STORE_CTX_set_verify_cb(&ctx,error_callback);
308 // Do a first pass verify. If CRLs aren't used, this is the only pass.
309 int ret=X509_verify_cert(&ctx);
311 // Now see if the depth was acceptable by counting the number of intermediates.
312 int depth=sk_X509_num(ctx.chain)-2;
313 if (pkixInfo->getVerificationDepth() < depth) {
315 "certificate chain was too long (%d intermediates, only %d allowed)",
316 (depth==-1) ? 0 : depth,
317 pkixInfo->getVerificationDepth()
324 #if (OPENSSL_VERSION_NUMBER >= 0x00907000L)
325 // When we add CRLs, we have to be sure the nextUpdate hasn't passed, because OpenSSL won't accept
326 // the CRL in that case. If we end up not adding a CRL for a particular link in the chain, the
327 // validation will fail (if the fullChain option was set).
328 set<string> crlissuers;
329 time_t now = time(nullptr);
331 for (vector<XSECCryptoX509CRL*>::const_iterator j=inlineCRLs->begin(); j!=inlineCRLs->end(); ++j) {
332 if ((*j)->getProviderName()==DSIGConstants::s_unicodeStrPROVOpenSSL &&
333 (X509_cmp_time(X509_CRL_get_nextUpdate(static_cast<OpenSSLCryptoX509CRL*>(*j)->getOpenSSLX509CRL()), &now) > 0)) {
335 X509_STORE_add_crl(store, X509_CRL_dup(static_cast<OpenSSLCryptoX509CRL*>(*j)->getOpenSSLX509CRL()));
336 string crlissuer(X509_NAME_to_string(X509_CRL_get_issuer(static_cast<OpenSSLCryptoX509CRL*>(*j)->getOpenSSLX509CRL())));
337 if (!crlissuer.empty()) {
338 log.debug("added inline CRL issued by (%s)", crlissuer.c_str());
339 crlissuers.insert(crlissuer);
344 const vector<XSECCryptoX509CRL*>& crls = pkixInfo->getCRLs();
345 for (vector<XSECCryptoX509CRL*>::const_iterator j=crls.begin(); j!=crls.end(); ++j) {
346 if ((*j)->getProviderName()==DSIGConstants::s_unicodeStrPROVOpenSSL &&
347 (X509_cmp_time(X509_CRL_get_nextUpdate(static_cast<OpenSSLCryptoX509CRL*>(*j)->getOpenSSLX509CRL()), &now) > 0)) {
349 X509_STORE_add_crl(store, X509_CRL_dup(static_cast<OpenSSLCryptoX509CRL*>(*j)->getOpenSSLX509CRL()));
350 string crlissuer(X509_NAME_to_string(X509_CRL_get_issuer(static_cast<OpenSSLCryptoX509CRL*>(*j)->getOpenSSLX509CRL())));
351 if (!crlissuer.empty()) {
352 log.debug("added CRL issued by (%s)", crlissuer.c_str());
353 crlissuers.insert(crlissuer);
358 for (int i = 0; i < sk_X509_num(untrusted); ++i) {
359 X509 *cert = sk_X509_value(untrusted, i);
360 string crlissuer(X509_NAME_to_string(X509_get_issuer_name(cert)));
361 if (crlissuers.count(crlissuer)) {
362 // We already have a CRL for this cert, so skip CRLDP processing for this one.
366 bool foundUsableCDP = false;
367 STACK_OF(DIST_POINT)* dps = (STACK_OF(DIST_POINT)*)X509_get_ext_d2i(cert, NID_crl_distribution_points, nullptr, nullptr);
368 for (int ii = 0; !foundUsableCDP && ii < sk_DIST_POINT_num(dps); ++ii) {
369 DIST_POINT* dp = sk_DIST_POINT_value(dps, ii);
370 if (!dp->distpoint || dp->distpoint->type != 0)
372 for (int iii = 0; !foundUsableCDP && iii < sk_GENERAL_NAME_num(dp->distpoint->name.fullname); ++iii) {
373 GENERAL_NAME* gen = sk_GENERAL_NAME_value(dp->distpoint->name.fullname, iii);
374 // Only consider HTTP URIs, and stop after the first one we find.
375 #ifdef HAVE_STRCASECMP
376 if (gen->type == GEN_URI && (!strncasecmp((const char*)gen->d.ia5->data, "http:", 5))) {
378 if (gen->type == GEN_URI && (!strnicmp((const char*)gen->d.ia5->data, "http:", 5))) {
380 const char* cdpuri = (const char*)gen->d.ia5->data;
381 auto_ptr<XSECCryptoX509CRL> crl(getRemoteCRLs(cdpuri, log));
382 if (crl.get() && crl->getProviderName()==DSIGConstants::s_unicodeStrPROVOpenSSL &&
383 (isFreshCRL(crl.get()) || (ii == sk_DIST_POINT_num(dps)-1 && iii == sk_GENERAL_NAME_num(dp->distpoint->name.fullname)-1))) {
385 X509_STORE_add_crl(store, X509_CRL_dup(static_cast<OpenSSLCryptoX509CRL*>(crl.get())->getOpenSSLX509CRL()));
386 log.debug("added CRL issued by (%s)", crlissuer.c_str());
387 crlissuers.insert(crlissuer);
388 foundUsableCDP = true;
393 sk_DIST_POINT_free(dps);
396 // Do a second pass verify with CRLs in place.
397 X509_STORE_CTX_set_flags(&ctx, fullCRLChain ? (X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL) : (X509_V_FLAG_CRL_CHECK));
398 ret=X509_verify_cert(&ctx);
400 log.warn("CRL checking is enabled, but OpenSSL version is too old");
406 X509_STORE_CTX_cleanup(&ctx);
407 X509_STORE_free(store);
408 sk_X509_free(CAstack);
411 log.debug("successfully validated certificate chain");
418 static XMLCh fullCRLChain[] = UNICODE_LITERAL_12(f,u,l,l,C,R,L,C,h,a,i,n);
419 static XMLCh checkRevocation[] = UNICODE_LITERAL_15(c,h,e,c,k,R,e,v,o,c,a,t,i,o,n);
422 AbstractPKIXTrustEngine::PKIXValidationInfoIterator::PKIXValidationInfoIterator()
426 AbstractPKIXTrustEngine::PKIXValidationInfoIterator::~PKIXValidationInfoIterator()
430 AbstractPKIXTrustEngine::AbstractPKIXTrustEngine(const xercesc::DOMElement* e)
432 m_fullCRLChain(XMLHelper::getAttrBool(e, false, fullCRLChain)),
433 m_checkRevocation(XMLHelper::getAttrString(e, nullptr, checkRevocation))
435 if (m_fullCRLChain) {
436 Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX").warn(
437 "fullCRLChain option is deprecated, setting checkRevocation to \"fullChain\""
439 m_checkRevocation = "fullChain";
441 else if (m_checkRevocation == "fullChain") {
442 m_fullCRLChain = true; // in case anything's using this
446 AbstractPKIXTrustEngine::~AbstractPKIXTrustEngine()
450 bool AbstractPKIXTrustEngine::checkEntityNames(
451 X509* certEE, const CredentialResolver& credResolver, const CredentialCriteria& criteria
454 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX");
456 // We resolve to a set of trusted credentials.
457 vector<const Credential*> creds;
458 credResolver.resolve(creds,&criteria);
460 // Build a list of acceptable names.
461 set<string> trustednames;
462 trustednames.insert(criteria.getPeerName());
463 for (vector<const Credential*>::const_iterator cred = creds.begin(); cred!=creds.end(); ++cred)
464 trustednames.insert((*cred)->getKeyNames().begin(), (*cred)->getKeyNames().end());
466 X509_NAME* subject=X509_get_subject_name(certEE);
468 // One way is a direct match to the subject DN.
469 // Seems that the way to do the compare is to write the X509_NAME into a BIO.
470 BIO* b = BIO_new(BIO_s_mem());
471 BIO* b2 = BIO_new(BIO_s_mem());
472 // The flags give us LDAP order instead of X.500, with a comma separator.
473 X509_NAME_print_ex(b,subject,0,XN_FLAG_RFC2253);
475 // The flags give us LDAP order instead of X.500, with a comma plus space separator.
476 X509_NAME_print_ex(b2,subject,0,XN_FLAG_RFC2253 + XN_FLAG_SEP_CPLUS_SPC - XN_FLAG_SEP_COMMA_PLUS);
479 BUF_MEM* bptr=nullptr;
480 BUF_MEM* bptr2=nullptr;
481 BIO_get_mem_ptr(b, &bptr);
482 BIO_get_mem_ptr(b2, &bptr2);
484 if (bptr && bptr->length > 0 && log.isDebugEnabled()) {
485 string subjectstr(bptr->data, bptr->length);
486 log.debug("certificate subject: %s", subjectstr.c_str());
489 // Check each keyname.
490 for (set<string>::const_iterator n=trustednames.begin(); bptr && bptr2 && n!=trustednames.end(); n++) {
491 #ifdef HAVE_STRCASECMP
492 if ((n->length() == bptr->length && !strncasecmp(n->c_str(), bptr->data, bptr->length)) ||
493 (n->length() == bptr2->length && !strncasecmp(n->c_str(), bptr2->data, bptr2->length))) {
495 if ((n->length() == bptr->length && !strnicmp(n->c_str(), bptr->data, bptr->length)) ||
496 (n->length() == bptr2->length && !strnicmp(n->c_str(), bptr2->data, bptr2->length))) {
498 log.debug("matched full subject DN to a key name (%s)", n->c_str());
507 log.debug("unable to match DN, trying TLS subjectAltName match");
508 STACK_OF(GENERAL_NAME)* altnames=(STACK_OF(GENERAL_NAME)*)X509_get_ext_d2i(certEE, NID_subject_alt_name, nullptr, nullptr);
510 int numalts = sk_GENERAL_NAME_num(altnames);
511 for (int an=0; an<numalts; an++) {
512 const GENERAL_NAME* check = sk_GENERAL_NAME_value(altnames, an);
513 if (check->type==GEN_DNS || check->type==GEN_URI) {
514 const char* altptr = (char*)ASN1_STRING_data(check->d.ia5);
515 const int altlen = ASN1_STRING_length(check->d.ia5);
516 for (set<string>::const_iterator n=trustednames.begin(); n!=trustednames.end(); n++) {
517 #ifdef HAVE_STRCASECMP
518 if ((check->type==GEN_DNS && n->length()==altlen && !strncasecmp(altptr,n->c_str(),altlen))
520 if ((check->type==GEN_DNS && n->length()==altlen && !strnicmp(altptr,n->c_str(),altlen))
522 || (check->type==GEN_URI && n->length()==altlen && !strncmp(altptr,n->c_str(),altlen))) {
523 log.debug("matched DNS/URI subjectAltName to a key name (%s)", n->c_str());
524 GENERAL_NAMES_free(altnames);
531 GENERAL_NAMES_free(altnames);
533 log.debug("unable to match subjectAltName, trying TLS CN match");
535 // Fetch the last CN RDN.
536 char* peer_CN = nullptr;
538 while ((j=X509_NAME_get_index_by_NID(subject, NID_commonName, i)) >= 0)
541 ASN1_STRING* tmp = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(subject, i));
542 // Copied in from libcurl.
543 /* In OpenSSL 0.9.7d and earlier, ASN1_STRING_to_UTF8 fails if the input
544 is already UTF-8 encoded. We check for this case and copy the raw
545 string manually to avoid the problem. */
546 if(tmp && ASN1_STRING_type(tmp) == V_ASN1_UTF8STRING) {
547 j = ASN1_STRING_length(tmp);
549 peer_CN = (char*)OPENSSL_malloc(j + 1);
550 memcpy(peer_CN, ASN1_STRING_data(tmp), j);
554 else /* not a UTF8 name */ {
555 j = ASN1_STRING_to_UTF8(reinterpret_cast<unsigned char**>(&peer_CN), tmp);
558 for (set<string>::const_iterator n=trustednames.begin(); n!=trustednames.end(); n++) {
559 #ifdef HAVE_STRCASECMP
560 if (n->length() == j && !strncasecmp(peer_CN, n->c_str(), j)) {
562 if (n->length() == j && !strnicmp(peer_CN, n->c_str(), j)) {
564 log.debug("matched subject CN to a key name (%s)", n->c_str());
566 OPENSSL_free(peer_CN);
571 OPENSSL_free(peer_CN);
574 log.warn("no common name in certificate subject");
578 log.error("certificate has no subject?!");
584 bool AbstractPKIXTrustEngine::validateWithCRLs(
586 STACK_OF(X509)* certChain,
587 const CredentialResolver& credResolver,
588 CredentialCriteria* criteria,
589 const std::vector<XSECCryptoX509CRL*>* inlineCRLs
593 NDC ndc("validateWithCRLs");
595 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX");
598 log.error("X.509 credential was NULL, unable to perform validation");
602 if (criteria && criteria->getPeerName() && *(criteria->getPeerName())) {
603 log.debug("checking that the certificate name is acceptable");
604 if (criteria->getUsage()==Credential::UNSPECIFIED_CREDENTIAL)
605 criteria->setUsage(Credential::SIGNING_CREDENTIAL);
606 if (!checkEntityNames(certEE,credResolver,*criteria)) {
607 log.error("certificate name was not acceptable");
612 log.debug("performing certificate path validation...");
614 auto_ptr<PKIXValidationInfoIterator> pkix(getPKIXValidationInfoIterator(credResolver, criteria));
615 while (pkix->next()) {
620 (m_checkRevocation=="entityOnly" || m_checkRevocation=="fullChain"),
621 (m_checkRevocation=="fullChain"),
622 (m_checkRevocation=="entityOnly" || m_checkRevocation=="fullChain") ? inlineCRLs : nullptr
628 log.debug("failed to validate certificate chain using supplied PKIX information");
632 bool AbstractPKIXTrustEngine::validate(
634 STACK_OF(X509)* certChain,
635 const CredentialResolver& credResolver,
636 CredentialCriteria* criteria
639 return validateWithCRLs(certEE,certChain,credResolver,criteria);
642 bool AbstractPKIXTrustEngine::validate(
643 XSECCryptoX509* certEE,
644 const vector<XSECCryptoX509*>& certChain,
645 const CredentialResolver& credResolver,
646 CredentialCriteria* criteria
653 Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX").error("X.509 credential was NULL, unable to perform validation");
656 else if (certEE->getProviderName()!=DSIGConstants::s_unicodeStrPROVOpenSSL) {
657 Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX").error("only the OpenSSL XSEC provider is supported");
661 STACK_OF(X509)* untrusted=sk_X509_new_null();
662 for (vector<XSECCryptoX509*>::const_iterator i=certChain.begin(); i!=certChain.end(); ++i)
663 sk_X509_push(untrusted,static_cast<OpenSSLCryptoX509*>(*i)->getOpenSSLX509());
665 bool ret = validate(static_cast<OpenSSLCryptoX509*>(certEE)->getOpenSSLX509(), untrusted, credResolver, criteria);
666 sk_X509_free(untrusted);
670 bool AbstractPKIXTrustEngine::validate(
672 const CredentialResolver& credResolver,
673 CredentialCriteria* criteria
679 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX");
681 const KeyInfoResolver* inlineResolver = m_keyInfoResolver;
683 inlineResolver = XMLToolingConfig::getConfig().getKeyInfoResolver();
684 if (!inlineResolver) {
685 log.error("unable to perform PKIX validation, no KeyInfoResolver available");
689 // Pull the certificate chain out of the signature.
690 X509Credential* x509cred;
691 auto_ptr<Credential> cred(inlineResolver->resolve(&sig,X509Credential::RESOLVE_CERTS|X509Credential::RESOLVE_CRLS));
692 if (!cred.get() || !(x509cred=dynamic_cast<X509Credential*>(cred.get()))) {
693 log.error("unable to perform PKIX validation, signature does not contain any certificates");
696 const vector<XSECCryptoX509*>& certs = x509cred->getEntityCertificateChain();
698 log.error("unable to perform PKIX validation, signature does not contain any certificates");
702 log.debug("validating signature using certificate from within the signature");
704 // Find and save off a pointer to the certificate that unlocks the object.
705 // Most of the time, this will be the first one anyway.
706 XSECCryptoX509* certEE=nullptr;
707 SignatureValidator keyValidator;
708 for (vector<XSECCryptoX509*>::const_iterator i=certs.begin(); !certEE && i!=certs.end(); ++i) {
710 auto_ptr<XSECCryptoKey> key((*i)->clonePublicKey());
711 keyValidator.setKey(key.get());
712 keyValidator.validate(&sig);
713 log.debug("signature verified with key inside signature, attempting certificate validation...");
716 catch (ValidationException& ex) {
717 log.debug(ex.what());
722 log.debug("failed to verify signature with embedded certificates");
725 else if (certEE->getProviderName()!=DSIGConstants::s_unicodeStrPROVOpenSSL) {
726 log.error("only the OpenSSL XSEC provider is supported");
730 STACK_OF(X509)* untrusted=sk_X509_new_null();
731 for (vector<XSECCryptoX509*>::const_iterator i=certs.begin(); i!=certs.end(); ++i)
732 sk_X509_push(untrusted,static_cast<OpenSSLCryptoX509*>(*i)->getOpenSSLX509());
733 const vector<XSECCryptoX509CRL*>& crls = x509cred->getCRLs();
734 bool ret = validateWithCRLs(static_cast<OpenSSLCryptoX509*>(certEE)->getOpenSSLX509(), untrusted, credResolver, criteria, &crls);
735 sk_X509_free(untrusted);
739 bool AbstractPKIXTrustEngine::validate(
740 const XMLCh* sigAlgorithm,
745 const CredentialResolver& credResolver,
746 CredentialCriteria* criteria
752 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX");
755 log.error("unable to perform PKIX validation, KeyInfo not present");
759 const KeyInfoResolver* inlineResolver = m_keyInfoResolver;
761 inlineResolver = XMLToolingConfig::getConfig().getKeyInfoResolver();
762 if (!inlineResolver) {
763 log.error("unable to perform PKIX validation, no KeyInfoResolver available");
767 // Pull the certificate chain out of the signature.
768 X509Credential* x509cred;
769 auto_ptr<Credential> cred(inlineResolver->resolve(keyInfo,X509Credential::RESOLVE_CERTS));
770 if (!cred.get() || !(x509cred=dynamic_cast<X509Credential*>(cred.get()))) {
771 log.error("unable to perform PKIX validation, KeyInfo does not contain any certificates");
774 const vector<XSECCryptoX509*>& certs = x509cred->getEntityCertificateChain();
776 log.error("unable to perform PKIX validation, KeyInfo does not contain any certificates");
780 log.debug("validating signature using certificate from within KeyInfo");
782 // Find and save off a pointer to the certificate that unlocks the object.
783 // Most of the time, this will be the first one anyway.
784 XSECCryptoX509* certEE=nullptr;
785 for (vector<XSECCryptoX509*>::const_iterator i=certs.begin(); !certEE && i!=certs.end(); ++i) {
787 auto_ptr<XSECCryptoKey> key((*i)->clonePublicKey());
788 if (Signature::verifyRawSignature(key.get(), sigAlgorithm, sig, in, in_len)) {
789 log.debug("signature verified with key inside signature, attempting certificate validation...");
793 catch (SignatureException& ex) {
794 log.debug(ex.what());
799 log.debug("failed to verify signature with embedded certificates");
802 else if (certEE->getProviderName()!=DSIGConstants::s_unicodeStrPROVOpenSSL) {
803 log.error("only the OpenSSL XSEC provider is supported");
807 STACK_OF(X509)* untrusted=sk_X509_new_null();
808 for (vector<XSECCryptoX509*>::const_iterator i=certs.begin(); i!=certs.end(); ++i)
809 sk_X509_push(untrusted,static_cast<OpenSSLCryptoX509*>(*i)->getOpenSSLX509());
810 const vector<XSECCryptoX509CRL*>& crls = x509cred->getCRLs();
811 bool ret = validateWithCRLs(static_cast<OpenSSLCryptoX509*>(certEE)->getOpenSSLX509(), untrusted, credResolver, criteria, &crls);
812 sk_X509_free(untrusted);