2 * Copyright 2001-2007 Internet2
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 * AbstractPKIXTrustEngine.cpp
20 * A trust engine that uses X.509 trust anchors and CRLs associated with a KeyInfoSource
21 * to perform PKIX validation of signatures and certificates.
26 #include "security/AbstractPKIXTrustEngine.h"
27 #include "signature/KeyInfo.h"
29 #include <openssl/x509_vfy.h>
30 #include <openssl/x509v3.h>
31 #include <xmltooling/security/CredentialCriteria.h>
32 #include <xmltooling/security/CredentialResolver.h>
33 #include <xmltooling/security/KeyInfoResolver.h>
34 #include <xmltooling/security/OpenSSLCryptoX509CRL.h>
35 #include <xmltooling/security/X509Credential.h>
36 #include <xmltooling/signature/SignatureValidator.h>
37 #include <xmltooling/util/NDC.h>
38 #include <xsec/enc/OpenSSL/OpenSSLCryptoX509.hpp>
40 using namespace xmlsignature;
41 using namespace xmltooling::logging;
42 using namespace xmltooling;
47 static int XMLTOOL_DLLLOCAL error_callback(int ok, X509_STORE_CTX* ctx)
50 Category::getInstance("OpenSSL").error("path validation failure: %s", X509_verify_cert_error_string(ctx->error));
54 static bool XMLTOOL_DLLLOCAL validate(
55 X509* EE, STACK_OF(X509)* untrusted, AbstractPKIXTrustEngine::PKIXValidationInfoIterator* pkixInfo
58 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine");
60 // First we build a stack of CA certs. These objects are all referenced in place.
61 log.debug("building CA list from PKIX Validation information");
63 // We need this for CRL support.
64 X509_STORE* store=X509_STORE_new();
69 #if (OPENSSL_VERSION_NUMBER >= 0x00907000L)
70 X509_STORE_set_flags(store,X509_V_FLAG_CRL_CHECK_ALL);
73 STACK_OF(X509)* CAstack = sk_X509_new_null();
75 // This contains the state of the validate operation.
78 const vector<XSECCryptoX509*>& CAcerts = pkixInfo->getTrustAnchors();
79 for (vector<XSECCryptoX509*>::const_iterator i=CAcerts.begin(); i!=CAcerts.end(); ++i) {
80 if ((*i)->getProviderName()==DSIGConstants::s_unicodeStrPROVOpenSSL) {
81 sk_X509_push(CAstack,static_cast<OpenSSLCryptoX509*>(*i)->getOpenSSLX509());
85 const vector<XSECCryptoX509CRL*>& crls = pkixInfo->getCRLs();
86 for (vector<XSECCryptoX509CRL*>::const_iterator j=crls.begin(); j!=crls.end(); ++j) {
87 if ((*j)->getProviderName()==DSIGConstants::s_unicodeStrPROVOpenSSL) {
89 X509_STORE_add_crl(store, X509_CRL_dup(static_cast<OpenSSLCryptoX509CRL*>(*j)->getOpenSSLX509CRL()));
93 // AFAICT, EE and untrusted are passed in but not owned by the ctx.
94 #if (OPENSSL_VERSION_NUMBER >= 0x00907000L)
95 if (X509_STORE_CTX_init(&ctx,store,EE,untrusted)!=1) {
97 log.error("unable to initialize X509_STORE_CTX");
98 sk_X509_free(CAstack);
99 X509_STORE_free(store);
103 X509_STORE_CTX_init(&ctx,store,EE,untrusted);
106 // Seems to be most efficient to just pass in the CA stack.
107 X509_STORE_CTX_trusted_stack(&ctx,CAstack);
108 X509_STORE_CTX_set_depth(&ctx,100); // we check the depth down below
109 X509_STORE_CTX_set_verify_cb(&ctx,error_callback);
111 int ret=X509_verify_cert(&ctx);
113 // Now see if the depth was acceptable by counting the number of intermediates.
114 int depth=sk_X509_num(ctx.chain)-2;
115 if (pkixInfo->getVerificationDepth() < depth) {
117 "certificate chain was too long (%d intermediates, only %d allowed)",
118 (depth==-1) ? 0 : depth,
119 pkixInfo->getVerificationDepth()
126 X509_STORE_CTX_cleanup(&ctx);
127 X509_STORE_free(store);
128 sk_X509_free(CAstack);
131 log.debug("successfully validated certificate chain");
139 bool AbstractPKIXTrustEngine::checkEntityNames(
140 X509* certEE, const CredentialResolver& credResolver, const CredentialCriteria& criteria
143 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX");
145 // We resolve to a set of trusted credentials.
146 vector<const Credential*> creds;
147 credResolver.resolve(creds,&criteria);
149 // Build a list of acceptable names.
150 set<string> trustednames;
151 trustednames.insert(criteria.getPeerName());
152 for (vector<const Credential*>::const_iterator cred = creds.begin(); cred!=creds.end(); ++cred)
153 trustednames.insert((*cred)->getKeyNames().begin(), (*cred)->getKeyNames().end());
156 X509_NAME* subject=X509_get_subject_name(certEE);
158 // One way is a direct match to the subject DN.
159 // Seems that the way to do the compare is to write the X509_NAME into a BIO.
160 BIO* b = BIO_new(BIO_s_mem());
161 BIO* b2 = BIO_new(BIO_s_mem());
162 BIO_set_mem_eof_return(b, 0);
163 BIO_set_mem_eof_return(b2, 0);
164 // The flags give us LDAP order instead of X.500, with a comma separator.
165 int len=X509_NAME_print_ex(b,subject,0,XN_FLAG_RFC2253);
166 string subjectstr,subjectstr2;
168 while ((len = BIO_read(b, buf, 255)) > 0) {
172 log.debugStream() << "certificate subject: " << subjectstr << logging::eol;
173 // The flags give us LDAP order instead of X.500, with a comma plus space separator.
174 len=X509_NAME_print_ex(b2,subject,0,XN_FLAG_RFC2253 + XN_FLAG_SEP_CPLUS_SPC - XN_FLAG_SEP_COMMA_PLUS);
176 while ((len = BIO_read(b2, buf, 255)) > 0) {
181 // Check each keyname.
182 for (set<string>::const_iterator n=trustednames.begin(); n!=trustednames.end(); n++) {
183 #ifdef HAVE_STRCASECMP
184 if (!strcasecmp(n->c_str(),subjectstr.c_str()) || !strcasecmp(n->c_str(),subjectstr2.c_str())) {
186 if (!stricmp(n->c_str(),subjectstr.c_str()) || !stricmp(n->c_str(),subjectstr2.c_str())) {
188 log.debug("matched full subject DN to a key name (%s)", n->c_str());
197 log.debug("unable to match DN, trying TLS subjectAltName match");
198 STACK_OF(GENERAL_NAME)* altnames=(STACK_OF(GENERAL_NAME)*)X509_get_ext_d2i(certEE, NID_subject_alt_name, NULL, NULL);
200 int numalts = sk_GENERAL_NAME_num(altnames);
201 for (int an=0; an<numalts; an++) {
202 const GENERAL_NAME* check = sk_GENERAL_NAME_value(altnames, an);
203 if (check->type==GEN_DNS || check->type==GEN_URI) {
204 const char* altptr = (char*)ASN1_STRING_data(check->d.ia5);
205 const int altlen = ASN1_STRING_length(check->d.ia5);
206 for (set<string>::const_iterator n=trustednames.begin(); n!=trustednames.end(); n++) {
207 #ifdef HAVE_STRCASECMP
208 if ((check->type==GEN_DNS && !strncasecmp(altptr,n->c_str(),altlen))
210 if ((check->type==GEN_DNS && !strnicmp(altptr,n->c_str(),altlen))
212 || (check->type==GEN_URI && !strncmp(altptr,n->c_str(),altlen))) {
213 log.debug("matched DNS/URI subjectAltName to a key name (%s)", n->c_str());
214 GENERAL_NAMES_free(altnames);
221 GENERAL_NAMES_free(altnames);
223 log.debug("unable to match subjectAltName, trying TLS CN match");
224 memset(buf,0,sizeof(buf));
225 if (X509_NAME_get_text_by_NID(subject,NID_commonName,buf,255)>0) {
226 for (set<string>::const_iterator n=trustednames.begin(); n!=trustednames.end(); n++) {
227 #ifdef HAVE_STRCASECMP
228 if (!strcasecmp(buf,n->c_str())) {
230 if (!stricmp(buf,n->c_str())) {
232 log.debug("matched subject CN to a key name (%s)", n->c_str());
238 log.warn("no common name in certificate subject");
241 log.error("certificate has no subject?!");
246 bool AbstractPKIXTrustEngine::validate(
248 STACK_OF(X509)* certChain,
249 const CredentialResolver& credResolver,
250 CredentialCriteria* criteria
256 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX");
259 log.error("X.509 credential was NULL, unable to perform validation");
263 if (criteria && criteria->getPeerName() && *(criteria->getPeerName())) {
264 log.debug("checking that the certificate name is acceptable");
265 if (criteria->getUsage()==Credential::UNSPECIFIED_CREDENTIAL)
266 criteria->setUsage(Credential::SIGNING_CREDENTIAL);
267 if (!checkEntityNames(certEE,credResolver,*criteria)) {
268 log.error("certificate name was not acceptable");
273 log.debug("performing certificate path validation...");
275 auto_ptr<PKIXValidationInfoIterator> pkix(getPKIXValidationInfoIterator(credResolver, criteria));
276 while (pkix->next()) {
277 if (::validate(certEE,certChain,pkix.get())) {
282 log.debug("failed to validate certificate chain using supplied PKIX information");
286 bool AbstractPKIXTrustEngine::validate(
287 XSECCryptoX509* certEE,
288 const vector<XSECCryptoX509*>& certChain,
289 const CredentialResolver& credResolver,
290 CredentialCriteria* criteria
297 Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX").error("X.509 credential was NULL, unable to perform validation");
300 else if (certEE->getProviderName()!=DSIGConstants::s_unicodeStrPROVOpenSSL) {
301 Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX").error("only the OpenSSL XSEC provider is supported");
305 STACK_OF(X509)* untrusted=sk_X509_new_null();
306 for (vector<XSECCryptoX509*>::const_iterator i=certChain.begin(); i!=certChain.end(); ++i)
307 sk_X509_push(untrusted,static_cast<OpenSSLCryptoX509*>(*i)->getOpenSSLX509());
309 bool ret = validate(static_cast<OpenSSLCryptoX509*>(certEE)->getOpenSSLX509(), untrusted, credResolver, criteria);
310 sk_X509_free(untrusted);
314 bool AbstractPKIXTrustEngine::validate(
316 const CredentialResolver& credResolver,
317 CredentialCriteria* criteria
323 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX");
325 const KeyInfoResolver* inlineResolver = m_keyInfoResolver;
327 inlineResolver = XMLToolingConfig::getConfig().getKeyInfoResolver();
328 if (!inlineResolver) {
329 log.error("unable to perform PKIX validation, no KeyInfoResolver available");
333 // Pull the certificate chain out of the signature.
334 X509Credential* x509cred;
335 auto_ptr<Credential> cred(inlineResolver->resolve(&sig,X509Credential::RESOLVE_CERTS));
336 if (!cred.get() || !(x509cred=dynamic_cast<X509Credential*>(cred.get()))) {
337 log.error("unable to perform PKIX validation, signature does not contain any certificates");
340 const vector<XSECCryptoX509*>& certs = x509cred->getEntityCertificateChain();
342 log.error("unable to perform PKIX validation, signature does not contain any certificates");
346 log.debug("validating signature using certificate from within the signature");
348 // Find and save off a pointer to the certificate that unlocks the object.
349 // Most of the time, this will be the first one anyway.
350 XSECCryptoX509* certEE=NULL;
351 SignatureValidator keyValidator;
352 for (vector<XSECCryptoX509*>::const_iterator i=certs.begin(); !certEE && i!=certs.end(); ++i) {
354 auto_ptr<XSECCryptoKey> key((*i)->clonePublicKey());
355 keyValidator.setKey(key.get());
356 keyValidator.validate(&sig);
357 log.debug("signature verified with key inside signature, attempting certificate validation...");
360 catch (ValidationException& ex) {
361 log.debug(ex.what());
366 return validate(certEE,certs,credResolver,criteria);
368 log.debug("failed to verify signature with embedded certificates");
372 bool AbstractPKIXTrustEngine::validate(
373 const XMLCh* sigAlgorithm,
378 const CredentialResolver& credResolver,
379 CredentialCriteria* criteria
385 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX");
388 log.error("unable to perform PKIX validation, KeyInfo not present");
392 const KeyInfoResolver* inlineResolver = m_keyInfoResolver;
394 inlineResolver = XMLToolingConfig::getConfig().getKeyInfoResolver();
395 if (!inlineResolver) {
396 log.error("unable to perform PKIX validation, no KeyInfoResolver available");
400 // Pull the certificate chain out of the signature.
401 X509Credential* x509cred;
402 auto_ptr<Credential> cred(inlineResolver->resolve(keyInfo,X509Credential::RESOLVE_CERTS));
403 if (!cred.get() || !(x509cred=dynamic_cast<X509Credential*>(cred.get()))) {
404 log.error("unable to perform PKIX validation, KeyInfo does not contain any certificates");
407 const vector<XSECCryptoX509*>& certs = x509cred->getEntityCertificateChain();
409 log.error("unable to perform PKIX validation, KeyInfo does not contain any certificates");
413 log.debug("validating signature using certificate from within KeyInfo");
415 // Find and save off a pointer to the certificate that unlocks the object.
416 // Most of the time, this will be the first one anyway.
417 XSECCryptoX509* certEE=NULL;
418 for (vector<XSECCryptoX509*>::const_iterator i=certs.begin(); !certEE && i!=certs.end(); ++i) {
420 auto_ptr<XSECCryptoKey> key((*i)->clonePublicKey());
421 if (Signature::verifyRawSignature(key.get(), sigAlgorithm, sig, in, in_len)) {
422 log.debug("signature verified with key inside signature, attempting certificate validation...");
426 catch (SignatureException& ex) {
427 log.debug(ex.what());
432 return validate(certEE,certs,credResolver,criteria);
434 log.debug("failed to verify signature with embedded certificates");