5f42ad2e34c0ef1440355e661a9cb05ef7e33286
[shibboleth/cpp-xmltooling.git] / xmltooling / security / impl / AbstractPKIXTrustEngine.cpp
1 /*
2  *  Copyright 2001-2010 Internet2
3  * 
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
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 /**
18  * AbstractPKIXTrustEngine.cpp
19  * 
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.
22  */
23
24 #include "internal.h"
25 #include "logging.h"
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"
36 #include "util/NDC.h"
37 #include "util/PathResolver.h"
38
39 #include <fstream>
40 #include <openssl/x509_vfy.h>
41 #include <openssl/x509v3.h>
42 #include <xercesc/util/XMLUniDefs.hpp>
43 #include <xsec/enc/OpenSSL/OpenSSLCryptoX509.hpp>
44
45 using namespace xmlsignature;
46 using namespace xmltooling::logging;
47 using namespace xmltooling;
48 using namespace std;
49
50
51 namespace {
52     static int XMLTOOL_DLLLOCAL error_callback(int ok, X509_STORE_CTX* ctx)
53     {
54         if (!ok)
55             Category::getInstance("OpenSSL").error("path validation failure: %s", X509_verify_cert_error_string(ctx->error));
56         return ok;
57     }
58
59     static string XMLTOOL_DLLLOCAL X509_NAME_to_string(X509_NAME* n)
60     {
61         string s;
62         BIO* b = BIO_new(BIO_s_mem());
63         X509_NAME_print_ex(b,n,0,XN_FLAG_RFC2253);
64         BIO_flush(b);
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);
69         }
70         BIO_free(b);
71         return s;
72     }
73
74     static time_t XMLTOOL_DLLLOCAL getCRLTime(const ASN1_TIME *a)
75     {
76         struct tm t;
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
89                 t.tm_year += 100;
90             }
91             t.tm_mon--;
92 #if defined(HAVE_TIMEGM)
93             return timegm(&t);
94 #else
95             // Windows, and hopefully most others...?
96             return mktime(&t) - timezone;
97 #endif
98         }
99         return (time_t)-1;
100     }
101
102     static bool XMLTOOL_DLLLOCAL isFreshCRL(XSECCryptoX509CRL *c, Category* log=nullptr)
103     {
104         // eventually, these should be made configurable
105         #define MIN_SECS_REMAINING 86400
106         #define MIN_PERCENT_REMAINING 10
107         if (c) {
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);
112
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;
117                 if (log) {
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());
120                 }
121                 return (X509_cmp_time(X509_CRL_get_nextUpdate(crl), &exp) > 0) ? true : false;
122             }
123             else {
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));
128                 }
129
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);
135             }
136         }
137         return false;
138     }
139
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.
145
146         // minimum number of seconds between re-attempting a download from one particular CRLDP
147         #define MIN_RETRY_WAIT 60
148
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";
154
155         time_t now = time(nullptr);
156         vector<XSECCryptoX509CRL*> crls;
157
158         try {
159             // While holding the lock, check for a cached copy of the CRL, and remove "expired" ones.
160             Locker glock(&XMLToolingConfig::getConfig());
161 #ifdef WIN32
162             struct _stat stat_buf;
163             if (_stat(cdpfile.c_str(), &stat_buf) == 0) {
164 #else
165             struct stat stat_buf;
166             if (stat(cdpfile.c_str(), &stat_buf) == 0) {
167 #endif
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>());
172                     crls.clear();
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);
176                 }
177             }
178         }
179         catch (exception& ex) {
180             log.error("exception loading cached copy of CRL from %s: %s", cdpuri, ex.what());
181         }
182
183         if (crls.empty() || !isFreshCRL(crls.front(), &log)) {
184             bool updateTimestamp = true;
185             try {
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.
190                 time_t ts = 0;
191                 try {
192                     Locker glock(&XMLToolingConfig::getConfig());
193                     ifstream tssrc(tsfile.c_str());
194                     if (tssrc)
195                         tssrc >> ts;
196                 }
197                 catch (exception&) {
198                     ts = 0;
199                 }
200
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));
205                     soap->send();
206                     istream& msg = soap->receive();
207                     Locker glock(&XMLToolingConfig::getConfig());
208                     ofstream out(cdpstaging.c_str(), fstream::trunc|fstream::binary);
209                     out << msg.rdbuf();
210                     out.close();
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>());
216                         crls.clear();
217                         remove(cdpstaging.c_str());
218                         log.error("ignoring CRL retrieved from %s with nextUpdate field in the past", cdpuri);
219                     }
220                     else {
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");
227                     }
228                 }
229                 else {
230                     updateTimestamp = false;    // don't update if we're within the backoff window
231                 }
232             }
233             catch (exception& ex) {
234                 log.error("exception downloading/caching CRL from %s: %s", cdpuri, ex.what());
235             }
236
237             if (updateTimestamp) {
238                 // update the timestamp file
239                 Locker glock(&XMLToolingConfig::getConfig());
240                 ofstream tssink(tsfile.c_str(), fstream::trunc);
241                 tssink << now;
242                 tssink.close();
243             }
244         }
245
246         if (crls.empty())
247             return nullptr;
248         for_each(crls.begin() + 1, crls.end(), xmltooling::cleanup<XSECCryptoX509CRL>());
249         return crls.front();
250     }
251
252     static bool XMLTOOL_DLLLOCAL validate(
253         X509* EE,
254         STACK_OF(X509)* untrusted,
255         AbstractPKIXTrustEngine::PKIXValidationInfoIterator* pkixInfo,
256                 bool useCRL,
257         bool fullCRLChain,
258         const vector<XSECCryptoX509CRL*>* inlineCRLs=nullptr
259         )
260     {
261         Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine");
262     
263         // First we build a stack of CA certs. These objects are all referenced in place.
264         log.debug("supplying PKIX Validation information");
265     
266         // We need this for CRL support.
267         X509_STORE* store=X509_STORE_new();
268         if (!store) {
269             log_openssl();
270             return false;
271         }
272     
273         // This contains the state of the validate operation.
274         int count=0;
275         X509_STORE_CTX ctx;
276
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) {
280             log_openssl();
281             log.error("unable to initialize X509_STORE_CTX");
282             X509_STORE_free(store);
283             return false;
284         }
285 #else
286         X509_STORE_CTX_init(&ctx,store,EE,untrusted);
287 #endif
288
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());
294                 ++count;
295             }
296         }
297         log.debug("supplied (%d) CA certificate(s)", count);
298
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);
303
304         // Do a first pass verify. If CRLs aren't used, this is the only pass.
305         int ret=X509_verify_cert(&ctx);
306         if (ret==1) {
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) {
310                 log.error(
311                     "certificate chain was too long (%d intermediates, only %d allowed)",
312                     (depth==-1) ? 0 : depth,
313                     pkixInfo->getVerificationDepth()
314                     );
315                 ret=0;
316             }
317         }
318
319         if (useCRL) {
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);
326             if (inlineCRLs) {
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)) {
330                         // owned by store
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);
336                         }
337                     }
338                 }
339             }
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)) {
344                     // owned by store
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);
350                     }
351                 }
352             }
353
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.
359                    continue;
360                 }
361
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)
367                         continue;
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))) {
373 #else
374                         if (gen->type == GEN_URI && (!strnicmp((const char*)gen->d.ia5->data, "http:", 5))) {
375 #endif
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))) {
380                                 // owned by store
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;
385                             }
386                         }
387                     }
388                 }
389                 sk_DIST_POINT_free(dps);
390             }
391
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);
395 #else
396             log.warn("CRL checking is enabled, but OpenSSL version is too old");
397             ret = 0;
398 #endif
399         }
400
401         // Clean up...
402         X509_STORE_CTX_cleanup(&ctx);
403         X509_STORE_free(store);
404         sk_X509_free(CAstack);
405     
406         if (ret==1) {
407             log.debug("successfully validated certificate chain");
408             return true;
409         }
410         
411         return false;
412     }
413
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);
416 };
417
418 AbstractPKIXTrustEngine::PKIXValidationInfoIterator::PKIXValidationInfoIterator()
419 {
420 }
421
422 AbstractPKIXTrustEngine::PKIXValidationInfoIterator::~PKIXValidationInfoIterator()
423 {
424 }
425
426 AbstractPKIXTrustEngine::AbstractPKIXTrustEngine(const xercesc::DOMElement* e)
427         : TrustEngine(e),
428                 m_fullCRLChain(XMLHelper::getAttrBool(e, false, fullCRLChain)),
429                 m_checkRevocation(XMLHelper::getAttrString(e, nullptr, checkRevocation))
430 {
431     if (m_fullCRLChain) {
432         Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX").warn(
433             "fullCRLChain option is deprecated, setting checkRevocation to \"fullChain\""
434             );
435         m_checkRevocation = "fullChain";
436     }
437     else if (m_checkRevocation == "fullChain") {
438         m_fullCRLChain = true; // in case anything's using this
439     }
440 }
441
442 AbstractPKIXTrustEngine::~AbstractPKIXTrustEngine()
443 {
444 }
445
446 bool AbstractPKIXTrustEngine::checkEntityNames(
447     X509* certEE, const CredentialResolver& credResolver, const CredentialCriteria& criteria
448     ) const
449 {
450     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX");
451
452     // We resolve to a set of trusted credentials.
453     vector<const Credential*> creds;
454     credResolver.resolve(creds,&criteria);
455
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());
461
462     X509_NAME* subject=X509_get_subject_name(certEE);
463     if (subject) {
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);
470         BIO_flush(b);
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);
473         BIO_flush(b2);
474
475         BUF_MEM* bptr=nullptr;
476         BUF_MEM* bptr2=nullptr;
477         BIO_get_mem_ptr(b, &bptr);
478         BIO_get_mem_ptr(b2, &bptr2);
479
480         if (bptr && bptr->length > 0 && log.isDebugEnabled()) {
481             string subjectstr(bptr->data, bptr->length);
482             log.debug("certificate subject: %s", subjectstr.c_str());
483         }
484         
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))) {
490 #else
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))) {
493 #endif
494                 log.debug("matched full subject DN to a key name (%s)", n->c_str());
495                 BIO_free(b);
496                 BIO_free(b2);
497                 return true;
498             }
499         }
500         BIO_free(b);
501         BIO_free(b2);
502
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);
505         if (altnames) {
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))
515 #else
516                         if ((check->type==GEN_DNS && n->length()==altlen && !strnicmp(altptr,n->c_str(),altlen))
517 #endif
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);
521                             return true;
522                         }
523                     }
524                 }
525             }
526         }
527         GENERAL_NAMES_free(altnames);
528             
529         log.debug("unable to match subjectAltName, trying TLS CN match");
530
531         // Fetch the last CN RDN.
532         char* peer_CN = nullptr;
533         int j,i = -1;
534         while ((j=X509_NAME_get_index_by_NID(subject, NID_commonName, i)) >= 0)
535             i = j;
536         if (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);
544                 if(j >= 0) {
545                     peer_CN = (char*)OPENSSL_malloc(j + 1);
546                     memcpy(peer_CN, ASN1_STRING_data(tmp), j);
547                     peer_CN[j] = '\0';
548                 }
549             }
550             else /* not a UTF8 name */ {
551                 j = ASN1_STRING_to_UTF8(reinterpret_cast<unsigned char**>(&peer_CN), tmp);
552             }
553
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)) {
557 #else
558                 if (n->length() == j && !strnicmp(peer_CN, n->c_str(), j)) {
559 #endif
560                     log.debug("matched subject CN to a key name (%s)", n->c_str());
561                     if(peer_CN)
562                         OPENSSL_free(peer_CN);
563                     return true;
564                 }
565             }
566             if(peer_CN)
567                 OPENSSL_free(peer_CN);
568         }
569         else {
570             log.warn("no common name in certificate subject");
571         }
572     }
573     else {
574         log.error("certificate has no subject?!");
575     }
576     
577     return false;
578 }
579
580 bool AbstractPKIXTrustEngine::validateWithCRLs(
581     X509* certEE,
582     STACK_OF(X509)* certChain,
583     const CredentialResolver& credResolver,
584     CredentialCriteria* criteria,
585     const std::vector<XSECCryptoX509CRL*>* inlineCRLs
586     ) const
587 {
588 #ifdef _DEBUG
589     NDC ndc("validateWithCRLs");
590 #endif
591     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX");
592
593     if (!certEE) {
594         log.error("X.509 credential was NULL, unable to perform validation");
595         return false;
596     }
597
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");
604             return false;
605         }
606     }
607     
608     log.debug("performing certificate path validation...");
609
610     auto_ptr<PKIXValidationInfoIterator> pkix(getPKIXValidationInfoIterator(credResolver, criteria));
611     while (pkix->next()) {
612         if (::validate(
613                                 certEE,
614                                 certChain,
615                                 pkix.get(),
616                                 (m_checkRevocation=="entityOnly" || m_checkRevocation=="fullChain"),
617                                 (m_checkRevocation=="fullChain"),
618                                 (m_checkRevocation=="entityOnly" || m_checkRevocation=="fullChain") ? inlineCRLs : nullptr
619                                 )) {
620             return true;
621         }
622     }
623
624     log.debug("failed to validate certificate chain using supplied PKIX information");
625     return false;
626 }
627
628 bool AbstractPKIXTrustEngine::validate(
629     X509* certEE,
630     STACK_OF(X509)* certChain,
631     const CredentialResolver& credResolver,
632     CredentialCriteria* criteria
633     ) const
634 {
635     return validateWithCRLs(certEE,certChain,credResolver,criteria);
636 }
637
638 bool AbstractPKIXTrustEngine::validate(
639     XSECCryptoX509* certEE,
640     const vector<XSECCryptoX509*>& certChain,
641     const CredentialResolver& credResolver,
642     CredentialCriteria* criteria
643     ) const
644 {
645 #ifdef _DEBUG
646         NDC ndc("validate");
647 #endif
648     if (!certEE) {
649         Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX").error("X.509 credential was NULL, unable to perform validation");
650         return false;
651     }
652     else if (certEE->getProviderName()!=DSIGConstants::s_unicodeStrPROVOpenSSL) {
653         Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX").error("only the OpenSSL XSEC provider is supported");
654         return false;
655     }
656
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());
660
661     bool ret = validate(static_cast<OpenSSLCryptoX509*>(certEE)->getOpenSSLX509(), untrusted, credResolver, criteria);
662     sk_X509_free(untrusted);
663     return ret;
664 }
665
666 bool AbstractPKIXTrustEngine::validate(
667     Signature& sig,
668     const CredentialResolver& credResolver,
669     CredentialCriteria* criteria
670     ) const
671 {
672 #ifdef _DEBUG
673     NDC ndc("validate");
674 #endif
675     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX");
676
677     const KeyInfoResolver* inlineResolver = m_keyInfoResolver;
678     if (!inlineResolver)
679         inlineResolver = XMLToolingConfig::getConfig().getKeyInfoResolver();
680     if (!inlineResolver) {
681         log.error("unable to perform PKIX validation, no KeyInfoResolver available");
682         return false;
683     }
684
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");
690         return false;
691     }
692     const vector<XSECCryptoX509*>& certs = x509cred->getEntityCertificateChain();
693     if (certs.empty()) {
694         log.error("unable to perform PKIX validation, signature does not contain any certificates");
695         return false;
696     }
697
698     log.debug("validating signature using certificate from within the signature");
699
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) {
705         try {
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...");
710             certEE=(*i);
711         }
712         catch (ValidationException& ex) {
713             log.debug(ex.what());
714         }
715     }
716     
717     if (!certEE) {
718         log.debug("failed to verify signature with embedded certificates");
719         return false;
720     }
721     else if (certEE->getProviderName()!=DSIGConstants::s_unicodeStrPROVOpenSSL) {
722         log.error("only the OpenSSL XSEC provider is supported");
723         return false;
724     }
725
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);
732     return ret;
733 }
734
735 bool AbstractPKIXTrustEngine::validate(
736     const XMLCh* sigAlgorithm,
737     const char* sig,
738     KeyInfo* keyInfo,
739     const char* in,
740     unsigned int in_len,
741     const CredentialResolver& credResolver,
742     CredentialCriteria* criteria
743     ) const
744 {
745 #ifdef _DEBUG
746     NDC ndc("validate");
747 #endif
748     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX");
749
750     if (!keyInfo) {
751         log.error("unable to perform PKIX validation, KeyInfo not present");
752         return false;
753     }
754
755     const KeyInfoResolver* inlineResolver = m_keyInfoResolver;
756     if (!inlineResolver)
757         inlineResolver = XMLToolingConfig::getConfig().getKeyInfoResolver();
758     if (!inlineResolver) {
759         log.error("unable to perform PKIX validation, no KeyInfoResolver available");
760         return false;
761     }
762
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");
768         return false;
769     }
770     const vector<XSECCryptoX509*>& certs = x509cred->getEntityCertificateChain();
771     if (certs.empty()) {
772         log.error("unable to perform PKIX validation, KeyInfo does not contain any certificates");
773         return false;
774     }
775
776     log.debug("validating signature using certificate from within KeyInfo");
777
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) {
782         try {
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...");
786                 certEE=(*i);
787             }
788         }
789         catch (SignatureException& ex) {
790             log.debug(ex.what());
791         }
792     }
793
794     if (!certEE) {
795         log.debug("failed to verify signature with embedded certificates");
796         return false;
797     }
798     else if (certEE->getProviderName()!=DSIGConstants::s_unicodeStrPROVOpenSSL) {
799         log.error("only the OpenSSL XSEC provider is supported");
800         return false;
801     }
802
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);
809     return ret;
810 }