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