Merge branch '1.x' of ssh://authdev.it.ohio-state.edu/~scantor/git/cpp-xmltooling...
[shibboleth/cpp-xmltooling.git] / xmltooling / security / impl / AbstractPKIXTrustEngine.cpp
1 /**
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.
6  *
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
10  * License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
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.
19  */
20
21 /**
22  * AbstractPKIXTrustEngine.cpp
23  * 
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.
26  */
27
28 #include "internal.h"
29 #include "logging.h"
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"
40 #include "util/NDC.h"
41 #include "util/PathResolver.h"
42
43 #include <fstream>
44 #include <openssl/x509_vfy.h>
45 #include <openssl/x509v3.h>
46 #include <xercesc/util/XMLUniDefs.hpp>
47 #include <xsec/enc/OpenSSL/OpenSSLCryptoX509.hpp>
48
49 using namespace xmlsignature;
50 using namespace xmltooling::logging;
51 using namespace xmltooling;
52 using namespace std;
53
54
55 namespace {
56     static int XMLTOOL_DLLLOCAL error_callback(int ok, X509_STORE_CTX* ctx)
57     {
58         if (!ok)
59             Category::getInstance("OpenSSL").error("path validation failure: %s", X509_verify_cert_error_string(ctx->error));
60         return ok;
61     }
62
63     static string XMLTOOL_DLLLOCAL X509_NAME_to_string(X509_NAME* n)
64     {
65         string s;
66         BIO* b = BIO_new(BIO_s_mem());
67         X509_NAME_print_ex(b,n,0,XN_FLAG_RFC2253);
68         BIO_flush(b);
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);
73         }
74         BIO_free(b);
75         return s;
76     }
77
78     static time_t XMLTOOL_DLLLOCAL getCRLTime(const ASN1_TIME *a)
79     {
80         struct tm t;
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
93                 t.tm_year += 100;
94             }
95             t.tm_mon--;
96 #if defined(HAVE_TIMEGM)
97             return timegm(&t);
98 #else
99             // Windows, and hopefully most others...?
100             return mktime(&t) - timezone;
101 #endif
102         }
103         return (time_t)-1;
104     }
105
106     static bool XMLTOOL_DLLLOCAL isFreshCRL(XSECCryptoX509CRL *c, Category* log=nullptr)
107     {
108         // eventually, these should be made configurable
109         #define MIN_SECS_REMAINING 86400
110         #define MIN_PERCENT_REMAINING 10
111         if (c) {
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);
116
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;
121                 if (log) {
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());
124                 }
125                 return (X509_cmp_time(X509_CRL_get_nextUpdate(crl), &exp) > 0) ? true : false;
126             }
127             else {
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));
132                 }
133
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);
139             }
140         }
141         return false;
142     }
143
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.
149
150         // minimum number of seconds between re-attempting a download from one particular CRLDP
151         #define MIN_RETRY_WAIT 60
152
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";
158
159         time_t now = time(nullptr);
160         vector<XSECCryptoX509CRL*> crls;
161
162         try {
163             // While holding the lock, check for a cached copy of the CRL, and remove "expired" ones.
164             Locker glock(&XMLToolingConfig::getConfig());
165 #ifdef WIN32
166             struct _stat stat_buf;
167             if (_stat(cdpfile.c_str(), &stat_buf) == 0) {
168 #else
169             struct stat stat_buf;
170             if (stat(cdpfile.c_str(), &stat_buf) == 0) {
171 #endif
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>());
176                     crls.clear();
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);
180                 }
181             }
182         }
183         catch (exception& ex) {
184             log.error("exception loading cached copy of CRL from %s: %s", cdpuri, ex.what());
185         }
186
187         if (crls.empty() || !isFreshCRL(crls.front(), &log)) {
188             bool updateTimestamp = true;
189             try {
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.
194                 time_t ts = 0;
195                 try {
196                     Locker glock(&XMLToolingConfig::getConfig());
197                     ifstream tssrc(tsfile.c_str());
198                     if (tssrc)
199                         tssrc >> ts;
200                 }
201                 catch (exception&) {
202                     ts = 0;
203                 }
204
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));
209                     soap->send();
210                     istream& msg = soap->receive();
211                     Locker glock(&XMLToolingConfig::getConfig());
212                     ofstream out(cdpstaging.c_str(), fstream::trunc|fstream::binary);
213                     out << msg.rdbuf();
214                     out.close();
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>());
220                         crls.clear();
221                         remove(cdpstaging.c_str());
222                         log.error("ignoring CRL retrieved from %s with nextUpdate field in the past", cdpuri);
223                     }
224                     else {
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");
231                     }
232                 }
233                 else {
234                     updateTimestamp = false;    // don't update if we're within the backoff window
235                 }
236             }
237             catch (exception& ex) {
238                 log.error("exception downloading/caching CRL from %s: %s", cdpuri, ex.what());
239             }
240
241             if (updateTimestamp) {
242                 // update the timestamp file
243                 Locker glock(&XMLToolingConfig::getConfig());
244                 ofstream tssink(tsfile.c_str(), fstream::trunc);
245                 tssink << now;
246                 tssink.close();
247             }
248         }
249
250         if (crls.empty())
251             return nullptr;
252         for_each(crls.begin() + 1, crls.end(), xmltooling::cleanup<XSECCryptoX509CRL>());
253         return crls.front();
254     }
255
256     static bool XMLTOOL_DLLLOCAL validate(
257         X509* EE,
258         STACK_OF(X509)* untrusted,
259         AbstractPKIXTrustEngine::PKIXValidationInfoIterator* pkixInfo,
260                 bool useCRL,
261         bool fullCRLChain,
262         const vector<XSECCryptoX509CRL*>* inlineCRLs=nullptr
263         )
264     {
265         Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine");
266     
267         // First we build a stack of CA certs. These objects are all referenced in place.
268         log.debug("supplying PKIX Validation information");
269     
270         // We need this for CRL support.
271         X509_STORE* store=X509_STORE_new();
272         if (!store) {
273             log_openssl();
274             return false;
275         }
276     
277         // This contains the state of the validate operation.
278         int count=0;
279         X509_STORE_CTX ctx;
280
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) {
284             log_openssl();
285             log.error("unable to initialize X509_STORE_CTX");
286             X509_STORE_free(store);
287             return false;
288         }
289 #else
290         X509_STORE_CTX_init(&ctx,store,EE,untrusted);
291 #endif
292
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());
298                 ++count;
299             }
300         }
301         log.debug("supplied (%d) CA certificate(s)", count);
302
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);
307
308         // Do a first pass verify. If CRLs aren't used, this is the only pass.
309         int ret=X509_verify_cert(&ctx);
310         if (ret==1) {
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) {
314                 log.error(
315                     "certificate chain was too long (%d intermediates, only %d allowed)",
316                     (depth==-1) ? 0 : depth,
317                     pkixInfo->getVerificationDepth()
318                     );
319                 ret=0;
320             }
321         }
322
323         if (useCRL) {
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);
330             if (inlineCRLs) {
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)) {
334                         // owned by store
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);
340                         }
341                     }
342                 }
343             }
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)) {
348                     // owned by store
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);
354                     }
355                 }
356             }
357
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.
363                    continue;
364                 }
365
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)
371                         continue;
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))) {
377 #else
378                         if (gen->type == GEN_URI && (!strnicmp((const char*)gen->d.ia5->data, "http:", 5))) {
379 #endif
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))) {
384                                 // owned by store
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;
389                             }
390                         }
391                     }
392                 }
393                 sk_DIST_POINT_free(dps);
394             }
395
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);
399 #else
400             log.warn("CRL checking is enabled, but OpenSSL version is too old");
401             ret = 0;
402 #endif
403         }
404
405         // Clean up...
406         X509_STORE_CTX_cleanup(&ctx);
407         X509_STORE_free(store);
408         sk_X509_free(CAstack);
409     
410         if (ret==1) {
411             log.debug("successfully validated certificate chain");
412             return true;
413         }
414         
415         return false;
416     }
417
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);
420 };
421
422 AbstractPKIXTrustEngine::PKIXValidationInfoIterator::PKIXValidationInfoIterator()
423 {
424 }
425
426 AbstractPKIXTrustEngine::PKIXValidationInfoIterator::~PKIXValidationInfoIterator()
427 {
428 }
429
430 AbstractPKIXTrustEngine::AbstractPKIXTrustEngine(const xercesc::DOMElement* e)
431         : TrustEngine(e),
432                 m_fullCRLChain(XMLHelper::getAttrBool(e, false, fullCRLChain)),
433                 m_checkRevocation(XMLHelper::getAttrString(e, nullptr, checkRevocation))
434 {
435     if (m_fullCRLChain) {
436         Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX").warn(
437             "fullCRLChain option is deprecated, setting checkRevocation to \"fullChain\""
438             );
439         m_checkRevocation = "fullChain";
440     }
441     else if (m_checkRevocation == "fullChain") {
442         m_fullCRLChain = true; // in case anything's using this
443     }
444 }
445
446 AbstractPKIXTrustEngine::~AbstractPKIXTrustEngine()
447 {
448 }
449
450 bool AbstractPKIXTrustEngine::checkEntityNames(
451     X509* certEE, const CredentialResolver& credResolver, const CredentialCriteria& criteria
452     ) const
453 {
454     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX");
455
456     // We resolve to a set of trusted credentials.
457     vector<const Credential*> creds;
458     credResolver.resolve(creds,&criteria);
459
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());
465
466     X509_NAME* subject=X509_get_subject_name(certEE);
467     if (subject) {
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);
474         BIO_flush(b);
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);
477         BIO_flush(b2);
478
479         BUF_MEM* bptr=nullptr;
480         BUF_MEM* bptr2=nullptr;
481         BIO_get_mem_ptr(b, &bptr);
482         BIO_get_mem_ptr(b2, &bptr2);
483
484         if (bptr && bptr->length > 0 && log.isDebugEnabled()) {
485             string subjectstr(bptr->data, bptr->length);
486             log.debug("certificate subject: %s", subjectstr.c_str());
487         }
488         
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))) {
494 #else
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))) {
497 #endif
498                 log.debug("matched full subject DN to a key name (%s)", n->c_str());
499                 BIO_free(b);
500                 BIO_free(b2);
501                 return true;
502             }
503         }
504         BIO_free(b);
505         BIO_free(b2);
506
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);
509         if (altnames) {
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))
519 #else
520                         if ((check->type==GEN_DNS && n->length()==altlen && !strnicmp(altptr,n->c_str(),altlen))
521 #endif
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);
525                             return true;
526                         }
527                     }
528                 }
529             }
530         }
531         GENERAL_NAMES_free(altnames);
532             
533         log.debug("unable to match subjectAltName, trying TLS CN match");
534
535         // Fetch the last CN RDN.
536         char* peer_CN = nullptr;
537         int j,i = -1;
538         while ((j=X509_NAME_get_index_by_NID(subject, NID_commonName, i)) >= 0)
539             i = j;
540         if (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);
548                 if(j >= 0) {
549                     peer_CN = (char*)OPENSSL_malloc(j + 1);
550                     memcpy(peer_CN, ASN1_STRING_data(tmp), j);
551                     peer_CN[j] = '\0';
552                 }
553             }
554             else /* not a UTF8 name */ {
555                 j = ASN1_STRING_to_UTF8(reinterpret_cast<unsigned char**>(&peer_CN), tmp);
556             }
557
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)) {
561 #else
562                 if (n->length() == j && !strnicmp(peer_CN, n->c_str(), j)) {
563 #endif
564                     log.debug("matched subject CN to a key name (%s)", n->c_str());
565                     if(peer_CN)
566                         OPENSSL_free(peer_CN);
567                     return true;
568                 }
569             }
570             if(peer_CN)
571                 OPENSSL_free(peer_CN);
572         }
573         else {
574             log.warn("no common name in certificate subject");
575         }
576     }
577     else {
578         log.error("certificate has no subject?!");
579     }
580     
581     return false;
582 }
583
584 bool AbstractPKIXTrustEngine::validateWithCRLs(
585     X509* certEE,
586     STACK_OF(X509)* certChain,
587     const CredentialResolver& credResolver,
588     CredentialCriteria* criteria,
589     const std::vector<XSECCryptoX509CRL*>* inlineCRLs
590     ) const
591 {
592 #ifdef _DEBUG
593     NDC ndc("validateWithCRLs");
594 #endif
595     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX");
596
597     if (!certEE) {
598         log.error("X.509 credential was NULL, unable to perform validation");
599         return false;
600     }
601
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");
608             return false;
609         }
610     }
611     
612     log.debug("performing certificate path validation...");
613
614     auto_ptr<PKIXValidationInfoIterator> pkix(getPKIXValidationInfoIterator(credResolver, criteria));
615     while (pkix->next()) {
616         if (::validate(
617                                 certEE,
618                                 certChain,
619                                 pkix.get(),
620                                 (m_checkRevocation=="entityOnly" || m_checkRevocation=="fullChain"),
621                                 (m_checkRevocation=="fullChain"),
622                                 (m_checkRevocation=="entityOnly" || m_checkRevocation=="fullChain") ? inlineCRLs : nullptr
623                                 )) {
624             return true;
625         }
626     }
627
628     log.debug("failed to validate certificate chain using supplied PKIX information");
629     return false;
630 }
631
632 bool AbstractPKIXTrustEngine::validate(
633     X509* certEE,
634     STACK_OF(X509)* certChain,
635     const CredentialResolver& credResolver,
636     CredentialCriteria* criteria
637     ) const
638 {
639     return validateWithCRLs(certEE,certChain,credResolver,criteria);
640 }
641
642 bool AbstractPKIXTrustEngine::validate(
643     XSECCryptoX509* certEE,
644     const vector<XSECCryptoX509*>& certChain,
645     const CredentialResolver& credResolver,
646     CredentialCriteria* criteria
647     ) const
648 {
649 #ifdef _DEBUG
650         NDC ndc("validate");
651 #endif
652     if (!certEE) {
653         Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX").error("X.509 credential was NULL, unable to perform validation");
654         return false;
655     }
656     else if (certEE->getProviderName()!=DSIGConstants::s_unicodeStrPROVOpenSSL) {
657         Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX").error("only the OpenSSL XSEC provider is supported");
658         return false;
659     }
660
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());
664
665     bool ret = validate(static_cast<OpenSSLCryptoX509*>(certEE)->getOpenSSLX509(), untrusted, credResolver, criteria);
666     sk_X509_free(untrusted);
667     return ret;
668 }
669
670 bool AbstractPKIXTrustEngine::validate(
671     Signature& sig,
672     const CredentialResolver& credResolver,
673     CredentialCriteria* criteria
674     ) const
675 {
676 #ifdef _DEBUG
677     NDC ndc("validate");
678 #endif
679     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX");
680
681     const KeyInfoResolver* inlineResolver = m_keyInfoResolver;
682     if (!inlineResolver)
683         inlineResolver = XMLToolingConfig::getConfig().getKeyInfoResolver();
684     if (!inlineResolver) {
685         log.error("unable to perform PKIX validation, no KeyInfoResolver available");
686         return false;
687     }
688
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");
694         return false;
695     }
696     const vector<XSECCryptoX509*>& certs = x509cred->getEntityCertificateChain();
697     if (certs.empty()) {
698         log.error("unable to perform PKIX validation, signature does not contain any certificates");
699         return false;
700     }
701
702     log.debug("validating signature using certificate from within the signature");
703
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) {
709         try {
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...");
714             certEE=(*i);
715         }
716         catch (ValidationException& ex) {
717             log.debug(ex.what());
718         }
719     }
720     
721     if (!certEE) {
722         log.debug("failed to verify signature with embedded certificates");
723         return false;
724     }
725     else if (certEE->getProviderName()!=DSIGConstants::s_unicodeStrPROVOpenSSL) {
726         log.error("only the OpenSSL XSEC provider is supported");
727         return false;
728     }
729
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);
736     return ret;
737 }
738
739 bool AbstractPKIXTrustEngine::validate(
740     const XMLCh* sigAlgorithm,
741     const char* sig,
742     KeyInfo* keyInfo,
743     const char* in,
744     unsigned int in_len,
745     const CredentialResolver& credResolver,
746     CredentialCriteria* criteria
747     ) const
748 {
749 #ifdef _DEBUG
750     NDC ndc("validate");
751 #endif
752     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX");
753
754     if (!keyInfo) {
755         log.error("unable to perform PKIX validation, KeyInfo not present");
756         return false;
757     }
758
759     const KeyInfoResolver* inlineResolver = m_keyInfoResolver;
760     if (!inlineResolver)
761         inlineResolver = XMLToolingConfig::getConfig().getKeyInfoResolver();
762     if (!inlineResolver) {
763         log.error("unable to perform PKIX validation, no KeyInfoResolver available");
764         return false;
765     }
766
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");
772         return false;
773     }
774     const vector<XSECCryptoX509*>& certs = x509cred->getEntityCertificateChain();
775     if (certs.empty()) {
776         log.error("unable to perform PKIX validation, KeyInfo does not contain any certificates");
777         return false;
778     }
779
780     log.debug("validating signature using certificate from within KeyInfo");
781
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) {
786         try {
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...");
790                 certEE=(*i);
791             }
792         }
793         catch (SignatureException& ex) {
794             log.debug(ex.what());
795         }
796     }
797
798     if (!certEE) {
799         log.debug("failed to verify signature with embedded certificates");
800         return false;
801     }
802     else if (certEE->getProviderName()!=DSIGConstants::s_unicodeStrPROVOpenSSL) {
803         log.error("only the OpenSSL XSEC provider is supported");
804         return false;
805     }
806
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);
813     return ret;
814 }