https://issues.shibboleth.net/jira/browse/CPPXT-64
[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) && iii == sk_GENERAL_NAME_num(dp->distpoint->name.fullname)))) {
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             if (!crlissuers.empty()) {
393                 X509_STORE_set_flags(store, fullCRLChain ? (X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL) : (X509_V_FLAG_CRL_CHECK));
394                     }
395                     else {
396                             log.warn("CRL checking is enabled, but none were supplied");
397                 X509_STORE_CTX_cleanup(&ctx);
398                 X509_STORE_free(store);
399                 sk_X509_free(CAstack);
400                 return false;
401                     }
402 #else
403                         log.warn("CRL checking is enabled, but OpenSSL version is too old");
404             X509_STORE_CTX_cleanup(&ctx);
405             X509_STORE_free(store);
406             sk_X509_free(CAstack);
407             return false;
408 #endif
409             // Do a second pass verify with CRLs in place.
410             ret=X509_verify_cert(&ctx);
411         }
412
413         // Clean up...
414         X509_STORE_CTX_cleanup(&ctx);
415         X509_STORE_free(store);
416         sk_X509_free(CAstack);
417     
418         if (ret==1) {
419             log.debug("successfully validated certificate chain");
420             return true;
421         }
422         
423         return false;
424     }
425
426     static XMLCh fullCRLChain[] =               UNICODE_LITERAL_12(f,u,l,l,C,R,L,C,h,a,i,n);
427         static XMLCh checkRevocation[] =        UNICODE_LITERAL_15(c,h,e,c,k,R,e,v,o,c,a,t,i,o,n);
428 };
429
430 AbstractPKIXTrustEngine::PKIXValidationInfoIterator::PKIXValidationInfoIterator()
431 {
432 }
433
434 AbstractPKIXTrustEngine::PKIXValidationInfoIterator::~PKIXValidationInfoIterator()
435 {
436 }
437
438 AbstractPKIXTrustEngine::AbstractPKIXTrustEngine(const xercesc::DOMElement* e)
439         : TrustEngine(e),
440                 m_fullCRLChain(XMLHelper::getAttrBool(e, false, fullCRLChain)),
441                 m_checkRevocation(XMLHelper::getAttrString(e, nullptr, checkRevocation))
442 {
443     if (m_fullCRLChain) {
444         Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX").warn(
445             "fullCRLChain option is deprecated, setting checkRevocation to \"fullChain\""
446             );
447         m_checkRevocation = "fullChain";
448     }
449     else if (m_checkRevocation == "fullChain") {
450         m_fullCRLChain = true; // in case anything's using this
451     }
452 }
453
454 AbstractPKIXTrustEngine::~AbstractPKIXTrustEngine()
455 {
456 }
457
458 bool AbstractPKIXTrustEngine::checkEntityNames(
459     X509* certEE, const CredentialResolver& credResolver, const CredentialCriteria& criteria
460     ) const
461 {
462     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX");
463
464     // We resolve to a set of trusted credentials.
465     vector<const Credential*> creds;
466     credResolver.resolve(creds,&criteria);
467
468     // Build a list of acceptable names.
469     set<string> trustednames;
470     trustednames.insert(criteria.getPeerName());
471     for (vector<const Credential*>::const_iterator cred = creds.begin(); cred!=creds.end(); ++cred)
472         trustednames.insert((*cred)->getKeyNames().begin(), (*cred)->getKeyNames().end());
473
474     X509_NAME* subject=X509_get_subject_name(certEE);
475     if (subject) {
476         // One way is a direct match to the subject DN.
477         // Seems that the way to do the compare is to write the X509_NAME into a BIO.
478         BIO* b = BIO_new(BIO_s_mem());
479         BIO* b2 = BIO_new(BIO_s_mem());
480         // The flags give us LDAP order instead of X.500, with a comma separator.
481         X509_NAME_print_ex(b,subject,0,XN_FLAG_RFC2253);
482         BIO_flush(b);
483         // The flags give us LDAP order instead of X.500, with a comma plus space separator.
484         X509_NAME_print_ex(b2,subject,0,XN_FLAG_RFC2253 + XN_FLAG_SEP_CPLUS_SPC - XN_FLAG_SEP_COMMA_PLUS);
485         BIO_flush(b2);
486
487         BUF_MEM* bptr=nullptr;
488         BUF_MEM* bptr2=nullptr;
489         BIO_get_mem_ptr(b, &bptr);
490         BIO_get_mem_ptr(b2, &bptr2);
491
492         if (bptr && bptr->length > 0 && log.isDebugEnabled()) {
493             string subjectstr(bptr->data, bptr->length);
494             log.debug("certificate subject: %s", subjectstr.c_str());
495         }
496         
497         // Check each keyname.
498         for (set<string>::const_iterator n=trustednames.begin(); bptr && bptr2 && n!=trustednames.end(); n++) {
499 #ifdef HAVE_STRCASECMP
500             if ((n->length() == bptr->length && !strncasecmp(n->c_str(), bptr->data, bptr->length)) ||
501                 (n->length() == bptr2->length && !strncasecmp(n->c_str(), bptr2->data, bptr2->length))) {
502 #else
503             if ((n->length() == bptr->length && !strnicmp(n->c_str(), bptr->data, bptr->length)) ||
504                 (n->length() == bptr2->length && !strnicmp(n->c_str(), bptr2->data, bptr2->length))) {
505 #endif
506                 log.debug("matched full subject DN to a key name (%s)", n->c_str());
507                 BIO_free(b);
508                 BIO_free(b2);
509                 return true;
510             }
511         }
512         BIO_free(b);
513         BIO_free(b2);
514
515         log.debug("unable to match DN, trying TLS subjectAltName match");
516         STACK_OF(GENERAL_NAME)* altnames=(STACK_OF(GENERAL_NAME)*)X509_get_ext_d2i(certEE, NID_subject_alt_name, nullptr, nullptr);
517         if (altnames) {
518             int numalts = sk_GENERAL_NAME_num(altnames);
519             for (int an=0; an<numalts; an++) {
520                 const GENERAL_NAME* check = sk_GENERAL_NAME_value(altnames, an);
521                 if (check->type==GEN_DNS || check->type==GEN_URI) {
522                     const char* altptr = (char*)ASN1_STRING_data(check->d.ia5);
523                     const int altlen = ASN1_STRING_length(check->d.ia5);
524                     for (set<string>::const_iterator n=trustednames.begin(); n!=trustednames.end(); n++) {
525 #ifdef HAVE_STRCASECMP
526                         if ((check->type==GEN_DNS && n->length()==altlen && !strncasecmp(altptr,n->c_str(),altlen))
527 #else
528                         if ((check->type==GEN_DNS && n->length()==altlen && !strnicmp(altptr,n->c_str(),altlen))
529 #endif
530                                 || (check->type==GEN_URI && n->length()==altlen && !strncmp(altptr,n->c_str(),altlen))) {
531                             log.debug("matched DNS/URI subjectAltName to a key name (%s)", n->c_str());
532                             GENERAL_NAMES_free(altnames);
533                             return true;
534                         }
535                     }
536                 }
537             }
538         }
539         GENERAL_NAMES_free(altnames);
540             
541         log.debug("unable to match subjectAltName, trying TLS CN match");
542
543         // Fetch the last CN RDN.
544         char* peer_CN = nullptr;
545         int j,i = -1;
546         while ((j=X509_NAME_get_index_by_NID(subject, NID_commonName, i)) >= 0)
547             i = j;
548         if (i >= 0) {
549             ASN1_STRING* tmp = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(subject, i));
550             // Copied in from libcurl.
551             /* In OpenSSL 0.9.7d and earlier, ASN1_STRING_to_UTF8 fails if the input
552                is already UTF-8 encoded. We check for this case and copy the raw
553                string manually to avoid the problem. */
554             if(tmp && ASN1_STRING_type(tmp) == V_ASN1_UTF8STRING) {
555                 j = ASN1_STRING_length(tmp);
556                 if(j >= 0) {
557                     peer_CN = (char*)OPENSSL_malloc(j + 1);
558                     memcpy(peer_CN, ASN1_STRING_data(tmp), j);
559                     peer_CN[j] = '\0';
560                 }
561             }
562             else /* not a UTF8 name */ {
563                 j = ASN1_STRING_to_UTF8(reinterpret_cast<unsigned char**>(&peer_CN), tmp);
564             }
565
566             for (set<string>::const_iterator n=trustednames.begin(); n!=trustednames.end(); n++) {
567 #ifdef HAVE_STRCASECMP
568                 if (n->length() == j && !strncasecmp(peer_CN, n->c_str(), j)) {
569 #else
570                 if (n->length() == j && !strnicmp(peer_CN, n->c_str(), j)) {
571 #endif
572                     log.debug("matched subject CN to a key name (%s)", n->c_str());
573                     if(peer_CN)
574                         OPENSSL_free(peer_CN);
575                     return true;
576                 }
577             }
578             if(peer_CN)
579                 OPENSSL_free(peer_CN);
580         }
581         else {
582             log.warn("no common name in certificate subject");
583         }
584     }
585     else {
586         log.error("certificate has no subject?!");
587     }
588     
589     return false;
590 }
591
592 bool AbstractPKIXTrustEngine::validateWithCRLs(
593     X509* certEE,
594     STACK_OF(X509)* certChain,
595     const CredentialResolver& credResolver,
596     CredentialCriteria* criteria,
597     const std::vector<XSECCryptoX509CRL*>* inlineCRLs
598     ) const
599 {
600 #ifdef _DEBUG
601     NDC ndc("validateWithCRLs");
602 #endif
603     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX");
604
605     if (!certEE) {
606         log.error("X.509 credential was NULL, unable to perform validation");
607         return false;
608     }
609
610     if (criteria && criteria->getPeerName() && *(criteria->getPeerName())) {
611         log.debug("checking that the certificate name is acceptable");
612         if (criteria->getUsage()==Credential::UNSPECIFIED_CREDENTIAL)
613             criteria->setUsage(Credential::SIGNING_CREDENTIAL);
614         if (!checkEntityNames(certEE,credResolver,*criteria)) {
615             log.error("certificate name was not acceptable");
616             return false;
617         }
618     }
619     
620     log.debug("performing certificate path validation...");
621
622     auto_ptr<PKIXValidationInfoIterator> pkix(getPKIXValidationInfoIterator(credResolver, criteria));
623     while (pkix->next()) {
624         if (::validate(
625                                 certEE,
626                                 certChain,
627                                 pkix.get(),
628                                 (m_checkRevocation=="entityOnly" || m_checkRevocation=="fullChain"),
629                                 (m_checkRevocation=="fullChain"),
630                                 (m_checkRevocation=="entityOnly" || m_checkRevocation=="fullChain") ? inlineCRLs : nullptr
631                                 )) {
632             return true;
633         }
634     }
635
636     log.debug("failed to validate certificate chain using supplied PKIX information");
637     return false;
638 }
639
640 bool AbstractPKIXTrustEngine::validate(
641     X509* certEE,
642     STACK_OF(X509)* certChain,
643     const CredentialResolver& credResolver,
644     CredentialCriteria* criteria
645     ) const
646 {
647     return validateWithCRLs(certEE,certChain,credResolver,criteria);
648 }
649
650 bool AbstractPKIXTrustEngine::validate(
651     XSECCryptoX509* certEE,
652     const vector<XSECCryptoX509*>& certChain,
653     const CredentialResolver& credResolver,
654     CredentialCriteria* criteria
655     ) const
656 {
657 #ifdef _DEBUG
658         NDC ndc("validate");
659 #endif
660     if (!certEE) {
661         Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX").error("X.509 credential was NULL, unable to perform validation");
662         return false;
663     }
664     else if (certEE->getProviderName()!=DSIGConstants::s_unicodeStrPROVOpenSSL) {
665         Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX").error("only the OpenSSL XSEC provider is supported");
666         return false;
667     }
668
669     STACK_OF(X509)* untrusted=sk_X509_new_null();
670     for (vector<XSECCryptoX509*>::const_iterator i=certChain.begin(); i!=certChain.end(); ++i)
671         sk_X509_push(untrusted,static_cast<OpenSSLCryptoX509*>(*i)->getOpenSSLX509());
672
673     bool ret = validate(static_cast<OpenSSLCryptoX509*>(certEE)->getOpenSSLX509(), untrusted, credResolver, criteria);
674     sk_X509_free(untrusted);
675     return ret;
676 }
677
678 bool AbstractPKIXTrustEngine::validate(
679     Signature& sig,
680     const CredentialResolver& credResolver,
681     CredentialCriteria* criteria
682     ) const
683 {
684 #ifdef _DEBUG
685     NDC ndc("validate");
686 #endif
687     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX");
688
689     const KeyInfoResolver* inlineResolver = m_keyInfoResolver;
690     if (!inlineResolver)
691         inlineResolver = XMLToolingConfig::getConfig().getKeyInfoResolver();
692     if (!inlineResolver) {
693         log.error("unable to perform PKIX validation, no KeyInfoResolver available");
694         return false;
695     }
696
697     // Pull the certificate chain out of the signature.
698     X509Credential* x509cred;
699     auto_ptr<Credential> cred(inlineResolver->resolve(&sig,X509Credential::RESOLVE_CERTS|X509Credential::RESOLVE_CRLS));
700     if (!cred.get() || !(x509cred=dynamic_cast<X509Credential*>(cred.get()))) {
701         log.error("unable to perform PKIX validation, signature does not contain any certificates");
702         return false;
703     }
704     const vector<XSECCryptoX509*>& certs = x509cred->getEntityCertificateChain();
705     if (certs.empty()) {
706         log.error("unable to perform PKIX validation, signature does not contain any certificates");
707         return false;
708     }
709
710     log.debug("validating signature using certificate from within the signature");
711
712     // Find and save off a pointer to the certificate that unlocks the object.
713     // Most of the time, this will be the first one anyway.
714     XSECCryptoX509* certEE=nullptr;
715     SignatureValidator keyValidator;
716     for (vector<XSECCryptoX509*>::const_iterator i=certs.begin(); !certEE && i!=certs.end(); ++i) {
717         try {
718             auto_ptr<XSECCryptoKey> key((*i)->clonePublicKey());
719             keyValidator.setKey(key.get());
720             keyValidator.validate(&sig);
721             log.debug("signature verified with key inside signature, attempting certificate validation...");
722             certEE=(*i);
723         }
724         catch (ValidationException& ex) {
725             log.debug(ex.what());
726         }
727     }
728     
729     if (!certEE) {
730         log.debug("failed to verify signature with embedded certificates");
731         return false;
732     }
733     else if (certEE->getProviderName()!=DSIGConstants::s_unicodeStrPROVOpenSSL) {
734         log.error("only the OpenSSL XSEC provider is supported");
735         return false;
736     }
737
738     STACK_OF(X509)* untrusted=sk_X509_new_null();
739     for (vector<XSECCryptoX509*>::const_iterator i=certs.begin(); i!=certs.end(); ++i)
740         sk_X509_push(untrusted,static_cast<OpenSSLCryptoX509*>(*i)->getOpenSSLX509());
741     const vector<XSECCryptoX509CRL*>& crls = x509cred->getCRLs();
742     bool ret = validateWithCRLs(static_cast<OpenSSLCryptoX509*>(certEE)->getOpenSSLX509(), untrusted, credResolver, criteria, &crls);
743     sk_X509_free(untrusted);
744     return ret;
745 }
746
747 bool AbstractPKIXTrustEngine::validate(
748     const XMLCh* sigAlgorithm,
749     const char* sig,
750     KeyInfo* keyInfo,
751     const char* in,
752     unsigned int in_len,
753     const CredentialResolver& credResolver,
754     CredentialCriteria* criteria
755     ) const
756 {
757 #ifdef _DEBUG
758     NDC ndc("validate");
759 #endif
760     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX");
761
762     if (!keyInfo) {
763         log.error("unable to perform PKIX validation, KeyInfo not present");
764         return false;
765     }
766
767     const KeyInfoResolver* inlineResolver = m_keyInfoResolver;
768     if (!inlineResolver)
769         inlineResolver = XMLToolingConfig::getConfig().getKeyInfoResolver();
770     if (!inlineResolver) {
771         log.error("unable to perform PKIX validation, no KeyInfoResolver available");
772         return false;
773     }
774
775     // Pull the certificate chain out of the signature.
776     X509Credential* x509cred;
777     auto_ptr<Credential> cred(inlineResolver->resolve(keyInfo,X509Credential::RESOLVE_CERTS));
778     if (!cred.get() || !(x509cred=dynamic_cast<X509Credential*>(cred.get()))) {
779         log.error("unable to perform PKIX validation, KeyInfo does not contain any certificates");
780         return false;
781     }
782     const vector<XSECCryptoX509*>& certs = x509cred->getEntityCertificateChain();
783     if (certs.empty()) {
784         log.error("unable to perform PKIX validation, KeyInfo does not contain any certificates");
785         return false;
786     }
787
788     log.debug("validating signature using certificate from within KeyInfo");
789
790     // Find and save off a pointer to the certificate that unlocks the object.
791     // Most of the time, this will be the first one anyway.
792     XSECCryptoX509* certEE=nullptr;
793     for (vector<XSECCryptoX509*>::const_iterator i=certs.begin(); !certEE && i!=certs.end(); ++i) {
794         try {
795             auto_ptr<XSECCryptoKey> key((*i)->clonePublicKey());
796             if (Signature::verifyRawSignature(key.get(), sigAlgorithm, sig, in, in_len)) {
797                 log.debug("signature verified with key inside signature, attempting certificate validation...");
798                 certEE=(*i);
799             }
800         }
801         catch (SignatureException& ex) {
802             log.debug(ex.what());
803         }
804     }
805
806     if (!certEE) {
807         log.debug("failed to verify signature with embedded certificates");
808         return false;
809     }
810     else if (certEE->getProviderName()!=DSIGConstants::s_unicodeStrPROVOpenSSL) {
811         log.error("only the OpenSSL XSEC provider is supported");
812         return false;
813     }
814
815     STACK_OF(X509)* untrusted=sk_X509_new_null();
816     for (vector<XSECCryptoX509*>::const_iterator i=certs.begin(); i!=certs.end(); ++i)
817         sk_X509_push(untrusted,static_cast<OpenSSLCryptoX509*>(*i)->getOpenSSLX509());
818     const vector<XSECCryptoX509CRL*>& crls = x509cred->getCRLs();
819     bool ret = validateWithCRLs(static_cast<OpenSSLCryptoX509*>(certEE)->getOpenSSLX509(), untrusted, credResolver, criteria, &crls);
820     sk_X509_free(untrusted);
821     return ret;
822 }