-/*\r
- * Copyright 2006 Internet2\r
- * \r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- */\r
-\r
-/**\r
- * AbstractPKIXTrustEngine.cpp\r
- * \r
- * A trust engine that uses X.509 trust anchors and CRLs associated with a role\r
- * to perform PKIX validation of signatures and certificates.\r
- */\r
-\r
-#include "internal.h"\r
-#include "security/AbstractPKIXTrustEngine.h"\r
-#include "signature/SignatureProfileValidator.h"\r
-\r
-#include <openssl/x509_vfy.h>\r
-#include <openssl/x509v3.h>\r
-#include <xmltooling/security/OpenSSLCryptoX509CRL.h>\r
-#include <xmltooling/signature/SignatureValidator.h>\r
-#include <xmltooling/util/NDC.h>\r
-#include <xsec/enc/OpenSSL/OpenSSLCryptoX509.hpp>\r
-#include <log4cpp/Category.hh>\r
-\r
-using namespace opensaml::saml2md;\r
-using namespace opensaml;\r
-using namespace xmlsignature;\r
-using namespace xmltooling;\r
-using namespace log4cpp;\r
-using namespace std;\r
-\r
-AbstractPKIXTrustEngine::AbstractPKIXTrustEngine(const DOMElement* e) : X509TrustEngine(e), m_inlineResolver(NULL)\r
-{\r
- m_inlineResolver = XMLToolingConfig::getConfig().KeyResolverManager.newPlugin(INLINE_KEY_RESOLVER,NULL);\r
-}\r
-\r
-AbstractPKIXTrustEngine::~AbstractPKIXTrustEngine()\r
-{\r
- delete m_inlineResolver;\r
-}\r
-\r
-namespace {\r
- static int SAML_DLLLOCAL error_callback(int ok, X509_STORE_CTX* ctx)\r
- {\r
- if (!ok)\r
- Category::getInstance("OpenSSL").error("path validation failure: %s", X509_verify_cert_error_string(ctx->error));\r
- return ok;\r
- }\r
-\r
- static bool SAML_DLLLOCAL validate(\r
- X509* EE, STACK_OF(X509)* untrusted, AbstractPKIXTrustEngine::PKIXValidationInfoIterator* pkixInfo\r
- )\r
- {\r
- Category& log=Category::getInstance(SAML_LOGCAT".TrustEngine");\r
- \r
- // First we build a stack of CA certs. These objects are all referenced in place.\r
- log.debug("building CA list from PKIX Validation information");\r
- \r
- // We need this for CRL support.\r
- X509_STORE* store=X509_STORE_new();\r
- if (!store) {\r
- log_openssl();\r
- return false;\r
- }\r
- #if (OPENSSL_VERSION_NUMBER >= 0x00907000L)\r
- X509_STORE_set_flags(store,X509_V_FLAG_CRL_CHECK_ALL);\r
- #endif\r
- \r
- STACK_OF(X509)* CAstack = sk_X509_new_null();\r
- \r
- // This contains the state of the validate operation.\r
- X509_STORE_CTX ctx;\r
- \r
- const vector<XSECCryptoX509*>& CAcerts = pkixInfo->getTrustAnchors();\r
- for (vector<XSECCryptoX509*>::const_iterator i=CAcerts.begin(); i!=CAcerts.end(); ++i) {\r
- if ((*i)->getProviderName()==DSIGConstants::s_unicodeStrPROVOpenSSL) {\r
- sk_X509_push(CAstack,static_cast<OpenSSLCryptoX509*>(*i)->getOpenSSLX509());\r
- }\r
- }\r
-\r
- const vector<XSECCryptoX509CRL*>& crls = pkixInfo->getCRLs();\r
- for (vector<XSECCryptoX509CRL*>::const_iterator j=crls.begin(); j!=crls.end(); ++j) {\r
- if ((*j)->getProviderName()==DSIGConstants::s_unicodeStrPROVOpenSSL) {\r
- // owned by store\r
- X509_STORE_add_crl(\r
- store,\r
- X509_CRL_dup(static_cast<OpenSSLCryptoX509CRL*>(*j)->getOpenSSLX509CRL())\r
- );\r
- }\r
- }\r
- \r
- // AFAICT, EE and untrusted are passed in but not owned by the ctx.\r
- #if (OPENSSL_VERSION_NUMBER >= 0x00907000L)\r
- if (X509_STORE_CTX_init(&ctx,store,EE,untrusted)!=1) {\r
- log_openssl();\r
- log.error("unable to initialize X509_STORE_CTX");\r
- sk_X509_free(CAstack);\r
- X509_STORE_free(store);\r
- return false;\r
- }\r
- #else\r
- X509_STORE_CTX_init(&ctx,store,EE,untrusted);\r
- #endif\r
- \r
- // Seems to be most efficient to just pass in the CA stack.\r
- X509_STORE_CTX_trusted_stack(&ctx,CAstack);\r
- X509_STORE_CTX_set_depth(&ctx,100); // we check the depth down below\r
- X509_STORE_CTX_set_verify_cb(&ctx,error_callback);\r
- \r
- int ret=X509_verify_cert(&ctx);\r
- if (ret==1) {\r
- // Now see if the depth was acceptable by counting the number of intermediates.\r
- int depth=sk_X509_num(ctx.chain)-2;\r
- if (pkixInfo->getVerificationDepth() < depth) {\r
- log.error(\r
- "certificate chain was too long (%d intermediates, only %d allowed)",\r
- (depth==-1) ? 0 : depth,\r
- pkixInfo->getVerificationDepth()\r
- );\r
- ret=0;\r
- }\r
- }\r
- \r
- // Clean up...\r
- X509_STORE_CTX_cleanup(&ctx);\r
- X509_STORE_free(store);\r
- sk_X509_free(CAstack);\r
- \r
- if (ret==1) {\r
- log.info("successfully validated certificate chain");\r
- return true;\r
- }\r
- \r
- return false;\r
- }\r
-};\r
-\r
-bool AbstractPKIXTrustEngine::checkEntityNames(XSECCryptoX509* certEE, const RoleDescriptor& role) const\r
-{\r
- Category& log=Category::getInstance(SAML_LOGCAT".TrustEngine");\r
- \r
- // Build a list of acceptable names. Transcode the possible key "names" to UTF-8.\r
- // For some simple cases, this should handle UTF-8 encoded DNs in certificates.\r
- vector<string> keynames;\r
- const vector<KeyDescriptor*>& keydescs=role.getKeyDescriptors();\r
- for (vector<KeyDescriptor*>::const_iterator kd_i=keydescs.begin(); kd_i!=keydescs.end(); ++kd_i) {\r
- const XMLCh* use=(*kd_i)->getUse();\r
- const KeyInfo* keyInfo = (*kd_i)->getKeyInfo();\r
- if (keyInfo && use && XMLString::equals(use,KeyDescriptor::KEYTYPE_ENCRYPTION))\r
- continue;\r
- const vector<KeyName*>& knames=keyInfo->getKeyNames();\r
- for (vector<KeyName*>::const_iterator kn_i=knames.begin(); kn_i!=knames.end(); ++kn_i) {\r
- const XMLCh* n=(*kn_i)->getName();\r
- if (n && *n) {\r
- char* kn=toUTF8(n);\r
- keynames.push_back(kn);\r
- delete[] kn;\r
- }\r
- }\r
- }\r
- \r
- EntityDescriptor* parent=dynamic_cast<EntityDescriptor*>(role.getParent());\r
- if (parent) {\r
- const XMLCh* eid=parent->getEntityID();\r
- if (eid && *eid) {\r
- char* kn=toUTF8(eid);\r
- keynames.push_back(kn);\r
- delete[] kn;\r
- }\r
- }\r
- \r
- char buf[256];\r
- X509* x=static_cast<OpenSSLCryptoX509*>(certEE)->getOpenSSLX509();\r
- X509_NAME* subject=X509_get_subject_name(x);\r
- if (subject) {\r
- // One way is a direct match to the subject DN.\r
- // Seems that the way to do the compare is to write the X509_NAME into a BIO.\r
- BIO* b = BIO_new(BIO_s_mem());\r
- BIO* b2 = BIO_new(BIO_s_mem());\r
- BIO_set_mem_eof_return(b, 0);\r
- BIO_set_mem_eof_return(b2, 0);\r
- // The flags give us LDAP order instead of X.500, with a comma separator.\r
- int len=X509_NAME_print_ex(b,subject,0,XN_FLAG_RFC2253);\r
- string subjectstr,subjectstr2;\r
- BIO_flush(b);\r
- while ((len = BIO_read(b, buf, 255)) > 0) {\r
- buf[len] = '\0';\r
- subjectstr+=buf;\r
- }\r
- log.infoStream() << "certificate subject: " << subjectstr << CategoryStream::ENDLINE;\r
- // The flags give us LDAP order instead of X.500, with a comma plus space separator.\r
- len=X509_NAME_print_ex(b2,subject,0,XN_FLAG_RFC2253 + XN_FLAG_SEP_CPLUS_SPC - XN_FLAG_SEP_COMMA_PLUS);\r
- BIO_flush(b2);\r
- while ((len = BIO_read(b2, buf, 255)) > 0) {\r
- buf[len] = '\0';\r
- subjectstr2+=buf;\r
- }\r
- \r
- // Check each keyname.\r
- for (vector<string>::const_iterator n=keynames.begin(); n!=keynames.end(); n++) {\r
-#ifdef HAVE_STRCASECMP\r
- if (!strcasecmp(n->c_str(),subjectstr.c_str()) || !strcasecmp(n->c_str(),subjectstr2.c_str())) {\r
-#else\r
- if (!stricmp(n->c_str(),subjectstr.c_str()) || !stricmp(n->c_str(),subjectstr2.c_str())) {\r
-#endif\r
- log.info("matched full subject DN to a key name (%s)", n->c_str());\r
- BIO_free(b);\r
- BIO_free(b2);\r
- return true;\r
- }\r
- }\r
- BIO_free(b);\r
- BIO_free(b2);\r
-\r
- log.debug("unable to match DN, trying TLS subjectAltName match");\r
- STACK_OF(GENERAL_NAME)* altnames=(STACK_OF(GENERAL_NAME)*)X509_get_ext_d2i(x, NID_subject_alt_name, NULL, NULL);\r
- if (altnames) {\r
- int numalts = sk_GENERAL_NAME_num(altnames);\r
- for (int an=0; an<numalts; an++) {\r
- const GENERAL_NAME* check = sk_GENERAL_NAME_value(altnames, an);\r
- if (check->type==GEN_DNS || check->type==GEN_URI) {\r
- const char* altptr = (char*)ASN1_STRING_data(check->d.ia5);\r
- const int altlen = ASN1_STRING_length(check->d.ia5);\r
- \r
- for (vector<string>::const_iterator n=keynames.begin(); n!=keynames.end(); n++) {\r
-#ifdef HAVE_STRCASECMP\r
- if ((check->type==GEN_DNS && !strncasecmp(altptr,n->c_str(),altlen))\r
-#else\r
- if ((check->type==GEN_DNS && !strnicmp(altptr,n->c_str(),altlen))\r
-#endif\r
- || (check->type==GEN_URI && !strncmp(altptr,n->c_str(),altlen))) {\r
- log.info("matched DNS/URI subjectAltName to a key name (%s)", n->c_str());\r
- GENERAL_NAMES_free(altnames);\r
- return true;\r
- }\r
- }\r
- }\r
- }\r
- }\r
- GENERAL_NAMES_free(altnames);\r
- \r
- log.debug("unable to match subjectAltName, trying TLS CN match");\r
- memset(buf,0,sizeof(buf));\r
- if (X509_NAME_get_text_by_NID(subject,NID_commonName,buf,255)>0) {\r
- for (vector<string>::const_iterator n=keynames.begin(); n!=keynames.end(); n++) {\r
-#ifdef HAVE_STRCASECMP\r
- if (!strcasecmp(buf,n->c_str())) {\r
-#else\r
- if (!stricmp(buf,n->c_str())) {\r
-#endif\r
- log.info("matched subject CN to a key name (%s)", n->c_str());\r
- return true;\r
- }\r
- }\r
- }\r
- else\r
- log.warn("no common name in certificate subject");\r
- }\r
- else\r
- log.error("certificate has no subject?!");\r
- \r
- return false;\r
-}\r
-\r
-bool AbstractPKIXTrustEngine::validate(\r
- XSECCryptoX509* certEE,\r
- const vector<XSECCryptoX509*>& certChain,\r
- const RoleDescriptor& role,\r
- bool checkName,\r
- const KeyResolver* keyResolver\r
- ) const\r
-{\r
-#ifdef _DEBUG\r
- NDC ndc("validate");\r
-#endif\r
- Category& log=Category::getInstance(SAML_LOGCAT".TrustEngine");\r
-\r
- if (!certEE) {\r
- log.error("X.509 credential was NULL, unable to perform validation");\r
- return false;\r
- }\r
-\r
- if (checkName) {\r
- log.debug("checking that the entity certificate name is acceptable");\r
- if (!checkEntityNames(certEE,role)) {\r
- log.error("entity certificate name was not acceptable");\r
- return false;\r
- }\r
- }\r
- \r
- log.debug("performing certificate path validation...");\r
-\r
- STACK_OF(X509)* untrusted=sk_X509_new_null();\r
- for (vector<XSECCryptoX509*>::const_iterator i=certChain.begin(); i!=certChain.end(); ++i) {\r
- sk_X509_push(untrusted,static_cast<OpenSSLCryptoX509*>(*i)->getOpenSSLX509());\r
- }\r
- \r
- auto_ptr<PKIXValidationInfoIterator> pkix(getPKIXValidationInfoIterator(role));\r
- while (pkix->next()) {\r
- if (::validate(static_cast<OpenSSLCryptoX509*>(certEE)->getOpenSSLX509(),untrusted,pkix.get())) {\r
- sk_X509_free(untrusted);\r
- return true;\r
- }\r
- }\r
-\r
- sk_X509_free(untrusted);\r
- log.error("failed to validate certificate chain using supplied PKIX information");\r
- return false;\r
-}\r
-\r
-bool AbstractPKIXTrustEngine::validate(Signature& sig, const RoleDescriptor& role, const KeyResolver* keyResolver) const\r
-{\r
-#ifdef _DEBUG\r
- NDC ndc("validate");\r
-#endif\r
- Category& log=Category::getInstance(SAML_LOGCAT".TrustEngine");\r
-\r
- log.debug("attempting to validate signature profile");\r
- SignatureProfileValidator sigValidator;\r
- try {\r
- sigValidator.validate(&sig);\r
- log.debug("signature profile validated");\r
- }\r
- catch (ValidationException& e) {\r
- if (log.isDebugEnabled()) {\r
- log.debug("signature profile failed to validate: %s", e.what());\r
- }\r
- return false;\r
- }\r
-\r
- // Pull the certificate chain out of the signature using an inline KeyResolver.\r
- KeyResolver::ResolvedCertificates certs;\r
- if (0==m_inlineResolver->resolveCertificates(&sig, certs)) {\r
- log.error("unable to perform PKIX validation, signature does not contain any certificates");\r
- return false;\r
- }\r
-\r
- log.debug("validating signature using certificate from within the signature");\r
-\r
- // Find and save off a pointer to the certificate that unlocks the object.\r
- // Most of the time, this will be the first one anyway.\r
- XSECCryptoX509* certEE=NULL;\r
- SignatureValidator keyValidator;\r
- for (vector<XSECCryptoX509*>::const_iterator i=certs.v().begin(); !certEE && i!=certs.v().end(); ++i) {\r
- try {\r
- keyValidator.setKey((*i)->clonePublicKey());\r
- keyValidator.validate(&sig);\r
- log.info("signature verified with key inside signature, attempting certificate validation...");\r
- certEE=(*i);\r
- }\r
- catch (ValidationException&) {\r
- // trap failures\r
- }\r
- }\r
- \r
- if (certEE)\r
- return validate(certEE,certs.v(),role,true,keyResolver);\r
- \r
- log.error("failed to verify signature with embedded certificates");\r
- return false;\r
-}\r
+/*
+ * Copyright 2006 Internet2
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * AbstractPKIXTrustEngine.cpp
+ *
+ * A trust engine that uses X.509 trust anchors and CRLs associated with a role
+ * to perform PKIX validation of signatures and certificates.
+ */
+
+#include "internal.h"
+#include "security/AbstractPKIXTrustEngine.h"
+#include "signature/SignatureProfileValidator.h"
+
+#include <openssl/x509_vfy.h>
+#include <openssl/x509v3.h>
+#include <xmltooling/security/OpenSSLCryptoX509CRL.h>
+#include <xmltooling/signature/SignatureValidator.h>
+#include <xmltooling/util/NDC.h>
+#include <xsec/enc/OpenSSL/OpenSSLCryptoX509.hpp>
+#include <log4cpp/Category.hh>
+
+using namespace opensaml::saml2md;
+using namespace opensaml;
+using namespace xmlsignature;
+using namespace xmltooling;
+using namespace log4cpp;
+using namespace std;
+
+AbstractPKIXTrustEngine::AbstractPKIXTrustEngine(const DOMElement* e) : X509TrustEngine(e), m_inlineResolver(NULL)
+{
+ m_inlineResolver = XMLToolingConfig::getConfig().KeyResolverManager.newPlugin(INLINE_KEY_RESOLVER,NULL);
+}
+
+AbstractPKIXTrustEngine::~AbstractPKIXTrustEngine()
+{
+ delete m_inlineResolver;
+}
+
+namespace {
+ static int SAML_DLLLOCAL error_callback(int ok, X509_STORE_CTX* ctx)
+ {
+ if (!ok)
+ Category::getInstance("OpenSSL").error("path validation failure: %s", X509_verify_cert_error_string(ctx->error));
+ return ok;
+ }
+
+ static bool SAML_DLLLOCAL validate(
+ X509* EE, STACK_OF(X509)* untrusted, AbstractPKIXTrustEngine::PKIXValidationInfoIterator* pkixInfo
+ )
+ {
+ Category& log=Category::getInstance(SAML_LOGCAT".TrustEngine");
+
+ // First we build a stack of CA certs. These objects are all referenced in place.
+ log.debug("building CA list from PKIX Validation information");
+
+ // We need this for CRL support.
+ X509_STORE* store=X509_STORE_new();
+ if (!store) {
+ log_openssl();
+ return false;
+ }
+ #if (OPENSSL_VERSION_NUMBER >= 0x00907000L)
+ X509_STORE_set_flags(store,X509_V_FLAG_CRL_CHECK_ALL);
+ #endif
+
+ STACK_OF(X509)* CAstack = sk_X509_new_null();
+
+ // This contains the state of the validate operation.
+ X509_STORE_CTX ctx;
+
+ const vector<XSECCryptoX509*>& CAcerts = pkixInfo->getTrustAnchors();
+ for (vector<XSECCryptoX509*>::const_iterator i=CAcerts.begin(); i!=CAcerts.end(); ++i) {
+ if ((*i)->getProviderName()==DSIGConstants::s_unicodeStrPROVOpenSSL) {
+ sk_X509_push(CAstack,static_cast<OpenSSLCryptoX509*>(*i)->getOpenSSLX509());
+ }
+ }
+
+ const vector<XSECCryptoX509CRL*>& crls = pkixInfo->getCRLs();
+ for (vector<XSECCryptoX509CRL*>::const_iterator j=crls.begin(); j!=crls.end(); ++j) {
+ if ((*j)->getProviderName()==DSIGConstants::s_unicodeStrPROVOpenSSL) {
+ // owned by store
+ X509_STORE_add_crl(
+ store,
+ X509_CRL_dup(static_cast<OpenSSLCryptoX509CRL*>(*j)->getOpenSSLX509CRL())
+ );
+ }
+ }
+
+ // AFAICT, EE and untrusted are passed in but not owned by the ctx.
+ #if (OPENSSL_VERSION_NUMBER >= 0x00907000L)
+ if (X509_STORE_CTX_init(&ctx,store,EE,untrusted)!=1) {
+ log_openssl();
+ log.error("unable to initialize X509_STORE_CTX");
+ sk_X509_free(CAstack);
+ X509_STORE_free(store);
+ return false;
+ }
+ #else
+ X509_STORE_CTX_init(&ctx,store,EE,untrusted);
+ #endif
+
+ // Seems to be most efficient to just pass in the CA stack.
+ X509_STORE_CTX_trusted_stack(&ctx,CAstack);
+ X509_STORE_CTX_set_depth(&ctx,100); // we check the depth down below
+ X509_STORE_CTX_set_verify_cb(&ctx,error_callback);
+
+ int ret=X509_verify_cert(&ctx);
+ if (ret==1) {
+ // Now see if the depth was acceptable by counting the number of intermediates.
+ int depth=sk_X509_num(ctx.chain)-2;
+ if (pkixInfo->getVerificationDepth() < depth) {
+ log.error(
+ "certificate chain was too long (%d intermediates, only %d allowed)",
+ (depth==-1) ? 0 : depth,
+ pkixInfo->getVerificationDepth()
+ );
+ ret=0;
+ }
+ }
+
+ // Clean up...
+ X509_STORE_CTX_cleanup(&ctx);
+ X509_STORE_free(store);
+ sk_X509_free(CAstack);
+
+ if (ret==1) {
+ log.info("successfully validated certificate chain");
+ return true;
+ }
+
+ return false;
+ }
+};
+
+bool AbstractPKIXTrustEngine::checkEntityNames(XSECCryptoX509* certEE, const RoleDescriptor& role) const
+{
+ Category& log=Category::getInstance(SAML_LOGCAT".TrustEngine");
+
+ // Build a list of acceptable names. Transcode the possible key "names" to UTF-8.
+ // For some simple cases, this should handle UTF-8 encoded DNs in certificates.
+ vector<string> keynames;
+ const vector<KeyDescriptor*>& keydescs=role.getKeyDescriptors();
+ for (vector<KeyDescriptor*>::const_iterator kd_i=keydescs.begin(); kd_i!=keydescs.end(); ++kd_i) {
+ const XMLCh* use=(*kd_i)->getUse();
+ const KeyInfo* keyInfo = (*kd_i)->getKeyInfo();
+ if (keyInfo && use && XMLString::equals(use,KeyDescriptor::KEYTYPE_ENCRYPTION))
+ continue;
+ const vector<KeyName*>& knames=keyInfo->getKeyNames();
+ for (vector<KeyName*>::const_iterator kn_i=knames.begin(); kn_i!=knames.end(); ++kn_i) {
+ const XMLCh* n=(*kn_i)->getName();
+ if (n && *n) {
+ char* kn=toUTF8(n);
+ keynames.push_back(kn);
+ delete[] kn;
+ }
+ }
+ }
+
+ EntityDescriptor* parent=dynamic_cast<EntityDescriptor*>(role.getParent());
+ if (parent) {
+ const XMLCh* eid=parent->getEntityID();
+ if (eid && *eid) {
+ char* kn=toUTF8(eid);
+ keynames.push_back(kn);
+ delete[] kn;
+ }
+ }
+
+ char buf[256];
+ X509* x=static_cast<OpenSSLCryptoX509*>(certEE)->getOpenSSLX509();
+ X509_NAME* subject=X509_get_subject_name(x);
+ if (subject) {
+ // One way is a direct match to the subject DN.
+ // Seems that the way to do the compare is to write the X509_NAME into a BIO.
+ BIO* b = BIO_new(BIO_s_mem());
+ BIO* b2 = BIO_new(BIO_s_mem());
+ BIO_set_mem_eof_return(b, 0);
+ BIO_set_mem_eof_return(b2, 0);
+ // The flags give us LDAP order instead of X.500, with a comma separator.
+ int len=X509_NAME_print_ex(b,subject,0,XN_FLAG_RFC2253);
+ string subjectstr,subjectstr2;
+ BIO_flush(b);
+ while ((len = BIO_read(b, buf, 255)) > 0) {
+ buf[len] = '\0';
+ subjectstr+=buf;
+ }
+ log.infoStream() << "certificate subject: " << subjectstr << CategoryStream::ENDLINE;
+ // The flags give us LDAP order instead of X.500, with a comma plus space separator.
+ len=X509_NAME_print_ex(b2,subject,0,XN_FLAG_RFC2253 + XN_FLAG_SEP_CPLUS_SPC - XN_FLAG_SEP_COMMA_PLUS);
+ BIO_flush(b2);
+ while ((len = BIO_read(b2, buf, 255)) > 0) {
+ buf[len] = '\0';
+ subjectstr2+=buf;
+ }
+
+ // Check each keyname.
+ for (vector<string>::const_iterator n=keynames.begin(); n!=keynames.end(); n++) {
+#ifdef HAVE_STRCASECMP
+ if (!strcasecmp(n->c_str(),subjectstr.c_str()) || !strcasecmp(n->c_str(),subjectstr2.c_str())) {
+#else
+ if (!stricmp(n->c_str(),subjectstr.c_str()) || !stricmp(n->c_str(),subjectstr2.c_str())) {
+#endif
+ log.info("matched full subject DN to a key name (%s)", n->c_str());
+ BIO_free(b);
+ BIO_free(b2);
+ return true;
+ }
+ }
+ BIO_free(b);
+ BIO_free(b2);
+
+ log.debug("unable to match DN, trying TLS subjectAltName match");
+ STACK_OF(GENERAL_NAME)* altnames=(STACK_OF(GENERAL_NAME)*)X509_get_ext_d2i(x, NID_subject_alt_name, NULL, NULL);
+ if (altnames) {
+ int numalts = sk_GENERAL_NAME_num(altnames);
+ for (int an=0; an<numalts; an++) {
+ const GENERAL_NAME* check = sk_GENERAL_NAME_value(altnames, an);
+ if (check->type==GEN_DNS || check->type==GEN_URI) {
+ const char* altptr = (char*)ASN1_STRING_data(check->d.ia5);
+ const int altlen = ASN1_STRING_length(check->d.ia5);
+
+ for (vector<string>::const_iterator n=keynames.begin(); n!=keynames.end(); n++) {
+#ifdef HAVE_STRCASECMP
+ if ((check->type==GEN_DNS && !strncasecmp(altptr,n->c_str(),altlen))
+#else
+ if ((check->type==GEN_DNS && !strnicmp(altptr,n->c_str(),altlen))
+#endif
+ || (check->type==GEN_URI && !strncmp(altptr,n->c_str(),altlen))) {
+ log.info("matched DNS/URI subjectAltName to a key name (%s)", n->c_str());
+ GENERAL_NAMES_free(altnames);
+ return true;
+ }
+ }
+ }
+ }
+ }
+ GENERAL_NAMES_free(altnames);
+
+ log.debug("unable to match subjectAltName, trying TLS CN match");
+ memset(buf,0,sizeof(buf));
+ if (X509_NAME_get_text_by_NID(subject,NID_commonName,buf,255)>0) {
+ for (vector<string>::const_iterator n=keynames.begin(); n!=keynames.end(); n++) {
+#ifdef HAVE_STRCASECMP
+ if (!strcasecmp(buf,n->c_str())) {
+#else
+ if (!stricmp(buf,n->c_str())) {
+#endif
+ log.info("matched subject CN to a key name (%s)", n->c_str());
+ return true;
+ }
+ }
+ }
+ else
+ log.warn("no common name in certificate subject");
+ }
+ else
+ log.error("certificate has no subject?!");
+
+ return false;
+}
+
+bool AbstractPKIXTrustEngine::validate(
+ XSECCryptoX509* certEE,
+ const vector<XSECCryptoX509*>& certChain,
+ const RoleDescriptor& role,
+ bool checkName,
+ const KeyResolver* keyResolver
+ ) const
+{
+#ifdef _DEBUG
+ NDC ndc("validate");
+#endif
+ Category& log=Category::getInstance(SAML_LOGCAT".TrustEngine");
+
+ if (!certEE) {
+ log.error("X.509 credential was NULL, unable to perform validation");
+ return false;
+ }
+
+ if (checkName) {
+ log.debug("checking that the entity certificate name is acceptable");
+ if (!checkEntityNames(certEE,role)) {
+ log.error("entity certificate name was not acceptable");
+ return false;
+ }
+ }
+
+ log.debug("performing certificate path validation...");
+
+ STACK_OF(X509)* untrusted=sk_X509_new_null();
+ for (vector<XSECCryptoX509*>::const_iterator i=certChain.begin(); i!=certChain.end(); ++i) {
+ sk_X509_push(untrusted,static_cast<OpenSSLCryptoX509*>(*i)->getOpenSSLX509());
+ }
+
+ auto_ptr<PKIXValidationInfoIterator> pkix(getPKIXValidationInfoIterator(role));
+ while (pkix->next()) {
+ if (::validate(static_cast<OpenSSLCryptoX509*>(certEE)->getOpenSSLX509(),untrusted,pkix.get())) {
+ sk_X509_free(untrusted);
+ return true;
+ }
+ }
+
+ sk_X509_free(untrusted);
+ log.error("failed to validate certificate chain using supplied PKIX information");
+ return false;
+}
+
+bool AbstractPKIXTrustEngine::validate(Signature& sig, const RoleDescriptor& role, const KeyResolver* keyResolver) const
+{
+#ifdef _DEBUG
+ NDC ndc("validate");
+#endif
+ Category& log=Category::getInstance(SAML_LOGCAT".TrustEngine");
+
+ log.debug("attempting to validate signature profile");
+ SignatureProfileValidator sigValidator;
+ try {
+ sigValidator.validate(&sig);
+ log.debug("signature profile validated");
+ }
+ catch (ValidationException& e) {
+ if (log.isDebugEnabled()) {
+ log.debug("signature profile failed to validate: %s", e.what());
+ }
+ return false;
+ }
+
+ // Pull the certificate chain out of the signature using an inline KeyResolver.
+ KeyResolver::ResolvedCertificates certs;
+ if (0==m_inlineResolver->resolveCertificates(&sig, certs)) {
+ log.error("unable to perform PKIX validation, signature does not contain any certificates");
+ return false;
+ }
+
+ log.debug("validating signature using certificate from within the signature");
+
+ // Find and save off a pointer to the certificate that unlocks the object.
+ // Most of the time, this will be the first one anyway.
+ XSECCryptoX509* certEE=NULL;
+ SignatureValidator keyValidator;
+ for (vector<XSECCryptoX509*>::const_iterator i=certs.v().begin(); !certEE && i!=certs.v().end(); ++i) {
+ try {
+ keyValidator.setKey((*i)->clonePublicKey());
+ keyValidator.validate(&sig);
+ log.info("signature verified with key inside signature, attempting certificate validation...");
+ certEE=(*i);
+ }
+ catch (ValidationException&) {
+ // trap failures
+ }
+ }
+
+ if (certEE)
+ return validate(certEE,certs.v(),role,true,keyResolver);
+
+ log.error("failed to verify signature with embedded certificates");
+ return false;
+}