2 * Copyright 2006 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 role
21 * to perform PKIX validation of signatures and certificates.
25 #include "security/AbstractPKIXTrustEngine.h"
26 #include "signature/SignatureProfileValidator.h"
28 #include <openssl/x509_vfy.h>
29 #include <openssl/x509v3.h>
30 #include <xmltooling/security/OpenSSLCryptoX509CRL.h>
31 #include <xmltooling/signature/SignatureValidator.h>
32 #include <xmltooling/util/NDC.h>
33 #include <xsec/enc/OpenSSL/OpenSSLCryptoX509.hpp>
34 #include <log4cpp/Category.hh>
36 using namespace opensaml::saml2md;
37 using namespace opensaml;
38 using namespace xmlsignature;
39 using namespace xmltooling;
40 using namespace log4cpp;
43 AbstractPKIXTrustEngine::AbstractPKIXTrustEngine(const DOMElement* e) : X509TrustEngine(e), m_inlineResolver(NULL)
45 m_inlineResolver = XMLToolingConfig::getConfig().KeyResolverManager.newPlugin(INLINE_KEY_RESOLVER,NULL);
48 AbstractPKIXTrustEngine::~AbstractPKIXTrustEngine()
50 delete m_inlineResolver;
54 static int SAML_DLLLOCAL error_callback(int ok, X509_STORE_CTX* ctx)
57 Category::getInstance("OpenSSL").error("path validation failure: %s", X509_verify_cert_error_string(ctx->error));
61 static bool SAML_DLLLOCAL validate(
62 X509* EE, STACK_OF(X509)* untrusted, AbstractPKIXTrustEngine::PKIXValidationInfoIterator* pkixInfo
65 Category& log=Category::getInstance(SAML_LOGCAT".TrustEngine");
67 // First we build a stack of CA certs. These objects are all referenced in place.
68 log.debug("building CA list from PKIX Validation information");
70 // We need this for CRL support.
71 X509_STORE* store=X509_STORE_new();
76 #if (OPENSSL_VERSION_NUMBER >= 0x00907000L)
77 X509_STORE_set_flags(store,X509_V_FLAG_CRL_CHECK_ALL);
80 STACK_OF(X509)* CAstack = sk_X509_new_null();
82 // This contains the state of the validate operation.
85 const vector<XSECCryptoX509*>& CAcerts = pkixInfo->getTrustAnchors();
86 for (vector<XSECCryptoX509*>::const_iterator i=CAcerts.begin(); i!=CAcerts.end(); ++i) {
87 if ((*i)->getProviderName()==DSIGConstants::s_unicodeStrPROVOpenSSL) {
88 sk_X509_push(CAstack,static_cast<OpenSSLCryptoX509*>(*i)->getOpenSSLX509());
92 const vector<XSECCryptoX509CRL*>& crls = pkixInfo->getCRLs();
93 for (vector<XSECCryptoX509CRL*>::const_iterator j=crls.begin(); j!=crls.end(); ++j) {
94 if ((*j)->getProviderName()==DSIGConstants::s_unicodeStrPROVOpenSSL) {
98 X509_CRL_dup(static_cast<OpenSSLCryptoX509CRL*>(*j)->getOpenSSLX509CRL())
103 // AFAICT, EE and untrusted are passed in but not owned by the ctx.
104 #if (OPENSSL_VERSION_NUMBER >= 0x00907000L)
105 if (X509_STORE_CTX_init(&ctx,store,EE,untrusted)!=1) {
107 log.error("unable to initialize X509_STORE_CTX");
108 sk_X509_free(CAstack);
109 X509_STORE_free(store);
113 X509_STORE_CTX_init(&ctx,store,EE,untrusted);
116 // Seems to be most efficient to just pass in the CA stack.
117 X509_STORE_CTX_trusted_stack(&ctx,CAstack);
118 X509_STORE_CTX_set_depth(&ctx,100); // we check the depth down below
119 X509_STORE_CTX_set_verify_cb(&ctx,error_callback);
121 int ret=X509_verify_cert(&ctx);
123 // Now see if the depth was acceptable by counting the number of intermediates.
124 int depth=sk_X509_num(ctx.chain)-2;
125 if (pkixInfo->getVerificationDepth() < depth) {
127 "certificate chain was too long (%d intermediates, only %d allowed)",
128 (depth==-1) ? 0 : depth,
129 pkixInfo->getVerificationDepth()
136 X509_STORE_CTX_cleanup(&ctx);
137 X509_STORE_free(store);
138 sk_X509_free(CAstack);
141 log.info("successfully validated certificate chain");
149 bool AbstractPKIXTrustEngine::checkEntityNames(XSECCryptoX509* certEE, const RoleDescriptor& role) const
151 Category& log=Category::getInstance(SAML_LOGCAT".TrustEngine");
153 // Build a list of acceptable names. Transcode the possible key "names" to UTF-8.
154 // For some simple cases, this should handle UTF-8 encoded DNs in certificates.
155 vector<string> keynames;
156 const vector<KeyDescriptor*>& keydescs=role.getKeyDescriptors();
157 for (vector<KeyDescriptor*>::const_iterator kd_i=keydescs.begin(); kd_i!=keydescs.end(); ++kd_i) {
158 const XMLCh* use=(*kd_i)->getUse();
159 const KeyInfo* keyInfo = (*kd_i)->getKeyInfo();
160 if (keyInfo && use && XMLString::equals(use,KeyDescriptor::KEYTYPE_ENCRYPTION))
162 const vector<KeyName*>& knames=keyInfo->getKeyNames();
163 for (vector<KeyName*>::const_iterator kn_i=knames.begin(); kn_i!=knames.end(); ++kn_i) {
164 const XMLCh* n=(*kn_i)->getName();
167 keynames.push_back(kn);
173 EntityDescriptor* parent=dynamic_cast<EntityDescriptor*>(role.getParent());
175 const XMLCh* eid=parent->getEntityID();
177 char* kn=toUTF8(eid);
178 keynames.push_back(kn);
184 X509* x=static_cast<OpenSSLCryptoX509*>(certEE)->getOpenSSLX509();
185 X509_NAME* subject=X509_get_subject_name(x);
187 // One way is a direct match to the subject DN.
188 // Seems that the way to do the compare is to write the X509_NAME into a BIO.
189 BIO* b = BIO_new(BIO_s_mem());
190 BIO* b2 = BIO_new(BIO_s_mem());
191 BIO_set_mem_eof_return(b, 0);
192 BIO_set_mem_eof_return(b2, 0);
193 // The flags give us LDAP order instead of X.500, with a comma separator.
194 int len=X509_NAME_print_ex(b,subject,0,XN_FLAG_RFC2253);
195 string subjectstr,subjectstr2;
197 while ((len = BIO_read(b, buf, 255)) > 0) {
201 log.infoStream() << "certificate subject: " << subjectstr << CategoryStream::ENDLINE;
202 // The flags give us LDAP order instead of X.500, with a comma plus space separator.
203 len=X509_NAME_print_ex(b2,subject,0,XN_FLAG_RFC2253 + XN_FLAG_SEP_CPLUS_SPC - XN_FLAG_SEP_COMMA_PLUS);
205 while ((len = BIO_read(b2, buf, 255)) > 0) {
210 // Check each keyname.
211 for (vector<string>::const_iterator n=keynames.begin(); n!=keynames.end(); n++) {
212 #ifdef HAVE_STRCASECMP
213 if (!strcasecmp(n->c_str(),subjectstr.c_str()) || !strcasecmp(n->c_str(),subjectstr2.c_str())) {
215 if (!stricmp(n->c_str(),subjectstr.c_str()) || !stricmp(n->c_str(),subjectstr2.c_str())) {
217 log.info("matched full subject DN to a key name (%s)", n->c_str());
226 log.debug("unable to match DN, trying TLS subjectAltName match");
227 STACK_OF(GENERAL_NAME)* altnames=(STACK_OF(GENERAL_NAME)*)X509_get_ext_d2i(x, NID_subject_alt_name, NULL, NULL);
229 int numalts = sk_GENERAL_NAME_num(altnames);
230 for (int an=0; an<numalts; an++) {
231 const GENERAL_NAME* check = sk_GENERAL_NAME_value(altnames, an);
232 if (check->type==GEN_DNS || check->type==GEN_URI) {
233 const char* altptr = (char*)ASN1_STRING_data(check->d.ia5);
234 const int altlen = ASN1_STRING_length(check->d.ia5);
236 for (vector<string>::const_iterator n=keynames.begin(); n!=keynames.end(); n++) {
237 #ifdef HAVE_STRCASECMP
238 if ((check->type==GEN_DNS && !strncasecmp(altptr,n->c_str(),altlen))
240 if ((check->type==GEN_DNS && !strnicmp(altptr,n->c_str(),altlen))
242 || (check->type==GEN_URI && !strncmp(altptr,n->c_str(),altlen))) {
243 log.info("matched DNS/URI subjectAltName to a key name (%s)", n->c_str());
244 GENERAL_NAMES_free(altnames);
251 GENERAL_NAMES_free(altnames);
253 log.debug("unable to match subjectAltName, trying TLS CN match");
254 memset(buf,0,sizeof(buf));
255 if (X509_NAME_get_text_by_NID(subject,NID_commonName,buf,255)>0) {
256 for (vector<string>::const_iterator n=keynames.begin(); n!=keynames.end(); n++) {
257 #ifdef HAVE_STRCASECMP
258 if (!strcasecmp(buf,n->c_str())) {
260 if (!stricmp(buf,n->c_str())) {
262 log.info("matched subject CN to a key name (%s)", n->c_str());
268 log.warn("no common name in certificate subject");
271 log.error("certificate has no subject?!");
276 bool AbstractPKIXTrustEngine::validate(
277 XSECCryptoX509* certEE,
278 const vector<XSECCryptoX509*>& certChain,
279 const RoleDescriptor& role,
281 const KeyResolver* keyResolver
287 Category& log=Category::getInstance(SAML_LOGCAT".TrustEngine");
290 log.error("X.509 credential was NULL, unable to perform validation");
295 log.debug("checking that the entity certificate name is acceptable");
296 if (!checkEntityNames(certEE,role)) {
297 log.error("entity certificate name was not acceptable");
302 log.debug("performing certificate path validation...");
304 STACK_OF(X509)* untrusted=sk_X509_new_null();
305 for (vector<XSECCryptoX509*>::const_iterator i=certChain.begin(); i!=certChain.end(); ++i) {
306 sk_X509_push(untrusted,static_cast<OpenSSLCryptoX509*>(*i)->getOpenSSLX509());
309 auto_ptr<PKIXValidationInfoIterator> pkix(getPKIXValidationInfoIterator(role));
310 while (pkix->next()) {
311 if (::validate(static_cast<OpenSSLCryptoX509*>(certEE)->getOpenSSLX509(),untrusted,pkix.get())) {
312 sk_X509_free(untrusted);
317 sk_X509_free(untrusted);
318 log.error("failed to validate certificate chain using supplied PKIX information");
322 bool AbstractPKIXTrustEngine::validate(Signature& sig, const RoleDescriptor& role, const KeyResolver* keyResolver) const
327 Category& log=Category::getInstance(SAML_LOGCAT".TrustEngine");
329 log.debug("attempting to validate signature profile");
330 SignatureProfileValidator sigValidator;
332 sigValidator.validate(&sig);
333 log.debug("signature profile validated");
335 catch (ValidationException& e) {
336 if (log.isDebugEnabled()) {
337 log.debug("signature profile failed to validate: %s", e.what());
342 // Pull the certificate chain out of the signature using an inline KeyResolver.
343 KeyResolver::ResolvedCertificates certs;
344 if (0==m_inlineResolver->resolveCertificates(&sig, certs)) {
345 log.error("unable to perform PKIX validation, signature does not contain any certificates");
349 log.debug("validating signature using certificate from within the signature");
351 // Find and save off a pointer to the certificate that unlocks the object.
352 // Most of the time, this will be the first one anyway.
353 XSECCryptoX509* certEE=NULL;
354 SignatureValidator keyValidator;
355 for (vector<XSECCryptoX509*>::const_iterator i=certs.v().begin(); !certEE && i!=certs.v().end(); ++i) {
357 keyValidator.setKey((*i)->clonePublicKey());
358 keyValidator.validate(&sig);
359 log.info("signature verified with key inside signature, attempting certificate validation...");
362 catch (ValidationException&) {
368 return validate(certEE,certs.v(),role,true,keyResolver);
370 log.error("failed to verify signature with embedded certificates");