PKIX TrustEngine.
authorcantor <cantor@fb386ef7-a10c-0410-8ebf-fd3f8e989ab0>
Fri, 25 Aug 2006 00:48:13 +0000 (00:48 +0000)
committercantor <cantor@fb386ef7-a10c-0410-8ebf-fd3f8e989ab0>
Fri, 25 Aug 2006 00:48:13 +0000 (00:48 +0000)
git-svn-id: https://svn.middleware.georgetown.edu/cpp-opensaml2/trunk@72 fb386ef7-a10c-0410-8ebf-fd3f8e989ab0

15 files changed:
saml/Makefile.am
saml/SAMLConfig.cpp
saml/internal.h
saml/saml.vcproj
saml/security/AbstractPKIXTrustEngine.h [new file with mode: 0644]
saml/security/TrustEngine.h
saml/security/X509TrustEngine.h
saml/security/impl/AbstractPKIXTrustEngine.cpp [new file with mode: 0644]
saml/security/impl/ExplicitKeyTrustEngine.cpp
samltest/Makefile.am
samltest/data/security/FilesystemKeyResolver.xml [new file with mode: 0644]
samltest/data/security/example-metadata.xml
samltest/samltest.vcproj
samltest/security/AbstractPKIXTrustEngineTest.h [new file with mode: 0644]
samltest/security/ExplicitKeyTrustEngineTest.h

index 9ef8991..a7457be 100644 (file)
@@ -29,6 +29,7 @@ encinclude_HEADERS = \
        encryption/EncryptedKeyResolver.h
 
 secinclude_HEADERS = \
+       security/AbstractPKIXTrustEngine.h \
        security/MetadataKeyInfoIterator.h \
        security/TrustEngine.h \
        security/X509TrustEngine.h
index e154646..6f4bf76 100644 (file)
@@ -1,3 +1,4 @@
+
 /*
  *  Copyright 2001-2006 Internet2
  * 
@@ -40,7 +41,7 @@
 #include <xsec/enc/XSECCryptoException.hpp>
 #include <xsec/enc/XSECCryptoProvider.hpp>
 #include <xsec/utils/XSECPlatformUtils.hpp>
-
+#include <openssl/err.h>
 
 using namespace opensaml;
 using namespace xmlsignature;
@@ -173,3 +174,19 @@ string SAMLInternalConfig::hashSHA1(const char* s, bool toHex)
     }
     throw XMLSecurityException("Unable to generate SHA-1 hash.");
 }
+
+void opensaml::log_openssl()
+{
+    const char* file;
+    const char* data;
+    int flags,line;
+
+    unsigned long code=ERR_get_error_line_data(&file,&line,&data,&flags);
+    while (code) {
+        Category& log=Category::getInstance("OpenSSL");
+        log.errorStream() << "error code: " << code << " in " << file << ", line " << line << CategoryStream::ENDLINE;
+        if (data && (flags & ERR_TXT_STRING))
+            log.errorStream() << "error data: " << data << CategoryStream::ENDLINE;
+        code=ERR_get_error_line_data(&file,&line,&data,&flags);
+    }
+}
index 675a5e7..9be5928 100644 (file)
@@ -98,6 +98,8 @@ namespace opensaml {
         std::string hashSHA1(const char* data, bool toHex=false);
     private:
     };
+
+    void log_openssl();
     /// @endcond
 
 };
index 0485e28..e5aa7c0 100644 (file)
@@ -62,7 +62,7 @@
                        />\r
                        <Tool\r
                                Name="VCLinkerTool"\r
-                               AdditionalDependencies="..\..\cpp-xmltooling\Debug\xmltooling_1D.lib xerces-c_2D.lib xsec_1D.lib log4cppD.lib"\r
+                               AdditionalDependencies="..\..\cpp-xmltooling\Debug\xmltooling_1D.lib xerces-c_2D.lib xsec_1D.lib log4cppD.lib libeay32_0_9_8D.lib"\r
                                OutputFile="$(OutDir)\$(ProjectName)_6D.dll"\r
                                LinkIncremental="2"\r
                                GenerateDebugInformation="true"\r
                        />\r
                        <Tool\r
                                Name="VCLinkerTool"\r
-                               AdditionalDependencies="..\..\cpp-xmltooling\Release\xmltooling_1.lib xerces-c_2.lib xsec_1.lib log4cpp.lib"\r
+                               AdditionalDependencies="..\..\cpp-xmltooling\Release\xmltooling_1.lib xerces-c_2.lib xsec_1.lib log4cpp.lib libeay32_0_9_8.lib"\r
                                OutputFile="$(OutDir)\$(ProjectName)_6.dll"\r
                                LinkIncremental="1"\r
                                GenerateDebugInformation="true"\r
                                        Name="impl"\r
                                        >\r
                                        <File\r
+                                               RelativePath=".\security\impl\AbstractPKIXTrustEngine.cpp"\r
+                                               >\r
+                                       </File>\r
+                                       <File\r
                                                RelativePath=".\security\impl\ExplicitKeyTrustEngine.cpp"\r
                                                >\r
                                        </File>\r
                                Name="security"\r
                                >\r
                                <File\r
+                                       RelativePath=".\security\AbstractPKIXTrustEngine.h"\r
+                                       >\r
+                               </File>\r
+                               <File\r
                                        RelativePath=".\security\MetadataKeyInfoIterator.h"\r
                                        >\r
                                </File>\r
diff --git a/saml/security/AbstractPKIXTrustEngine.h b/saml/security/AbstractPKIXTrustEngine.h
new file mode 100644 (file)
index 0000000..0c3ade2
--- /dev/null
@@ -0,0 +1,147 @@
+/*\r
+ *  Copyright 2001-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
+ * @file saml/security/AbstractPKIXTrustEngine.h\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
+#ifndef __saml_pkixtrust_h__\r
+#define __saml_pkixtrust_h__\r
+\r
+#include <saml/security/X509TrustEngine.h>\r
+#include <xmltooling/security/XSECCryptoX509CRL.h>\r
+\r
+namespace opensaml {\r
+\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
+    class SAML_API AbstractPKIXTrustEngine : public X509TrustEngine\r
+    {\r
+    protected:\r
+        /**\r
+         * Constructor.\r
+         * \r
+         * If a DOM is supplied, the following XML content is supported:\r
+         * \r
+         * <ul>\r
+         *  <li>&lt;KeyResolver&gt; elements with a type attribute\r
+         * </ul>\r
+         * \r
+         * XML namespaces are ignored in the processing of this content.\r
+         * \r
+         * @param e DOM to supply configuration for provider\r
+         */\r
+        AbstractPKIXTrustEngine(const DOMElement* e=NULL);\r
+        \r
+        /**\r
+         * Checks that either the ID for the entity with the given role or the key names\r
+         * for the given role match the subject or subject alternate names\r
+         * of the entity's certificate.\r
+         * \r
+         * @param certEE    the credential for the entity to validate\r
+         * @param role      the descriptor of the role the entity is supposed to be acting in\r
+         * \r
+         * @return true the name check succeeds, false if not\r
+         */\r
+        bool checkEntityNames(XSECCryptoX509* certEE, const saml2md::RoleDescriptor& role) const;\r
+        \r
+        /** An inline KeyResolver for extracting certificates out of a signature. */\r
+        xmlsignature::KeyResolver* m_inlineResolver;\r
+        \r
+    public:\r
+        virtual ~AbstractPKIXTrustEngine();\r
+\r
+        virtual bool validate(\r
+            xmlsignature::Signature& sig,\r
+            const saml2md::RoleDescriptor& role,\r
+            const xmlsignature::KeyResolver* keyResolver=NULL\r
+            );\r
+\r
+        virtual bool validate(\r
+            XSECCryptoX509* certEE,\r
+            const std::vector<XSECCryptoX509*>& certChain,\r
+            const saml2md::RoleDescriptor& role,\r
+            bool checkName=true,\r
+            const xmlsignature::KeyResolver* keyResolver=NULL\r
+            );\r
+\r
+        /**\r
+         * Stateful interface that supplies PKIX validation data to the trust engine.\r
+         * Applications can adapt this TrustEngine to their environment by returning\r
+         * implementations of this interface from the getPKIXValidationInfoIterator\r
+         * method.\r
+         */\r
+        class SAML_API PKIXValidationInfoIterator {\r
+            MAKE_NONCOPYABLE(PKIXValidationInfoIterator);\r
+        protected:\r
+            PKIXValidationInfoIterator() {}\r
+        public:\r
+            virtual ~PKIXValidationInfoIterator() {}\r
+            \r
+            /**\r
+             * Advances to the next set of information, if any.\r
+             * \r
+             * @return true iff another set of information is available\r
+             */\r
+            virtual bool next()=0;\r
+            \r
+            /**\r
+             * Returns the allowable trust chain verification depth for the\r
+             * validation data in the current position.\r
+             * \r
+             * @return  allowable trust chain verification depth\r
+             */\r
+            virtual int getVerificationDepth() const=0;\r
+            \r
+            /**\r
+             * Returns the set of trust anchors for the validation data in the\r
+             * current position. Keeping the certificates beyond the lifetime\r
+             * of the iterator or after advancing to the next position requires\r
+             * copying them.\r
+             * \r
+             * @return  set of trust anchors\r
+             */\r
+            virtual const std::vector<XSECCryptoX509*>& getTrustAnchors() const=0;\r
+\r
+            /**\r
+             * Returns the set of CRLs for the validation data in the\r
+             * current position. Keeping the CRLs beyond the lifetime\r
+             * of the iterator or after advancing to the next position requires\r
+             * copying them.\r
+             * \r
+             * @return  set of CRLs\r
+             */\r
+            virtual const std::vector<xmltooling::XSECCryptoX509CRL*>& getCRLs() const=0;\r
+        };\r
+        \r
+        /**\r
+         * Provides access to the information necessary, for the given role, for\r
+         * PKIX validation of credentials. Each set of validation information returned\r
+         * will be tried, in turn, until one succeeds or no more remain.\r
+         * The caller must free the returned interface when finished with it.\r
+         * \r
+         * @return interface for obtaining validation data  \r
+         */\r
+        virtual PKIXValidationInfoIterator* getPKIXValidationInfoIterator(const saml2md::RoleDescriptor& role) const=0;\r
+    };\r
+};\r
+\r
+#endif /* __saml_pkixtrust_h__ */\r
index 996286b..0cc211f 100644 (file)
@@ -68,7 +68,7 @@ namespace opensaml {
          */\r
         virtual bool validate(\r
             xmlsignature::Signature& sig,\r
-            saml2md::RoleDescriptor& role,\r
+            const saml2md::RoleDescriptor& role,\r
             const xmlsignature::KeyResolver* keyResolver=NULL\r
             )=0;\r
     };\r
index 1bc8bb6..92b6e82 100644 (file)
@@ -67,7 +67,7 @@ namespace opensaml {
         virtual bool validate(\r
             XSECCryptoX509* certEE,\r
             const std::vector<XSECCryptoX509*>& certChain,\r
-            saml2md::RoleDescriptor& role,\r
+            const saml2md::RoleDescriptor& role,\r
             bool checkName=true,\r
             const xmlsignature::KeyResolver* keyResolver=NULL\r
             )=0;\r
diff --git a/saml/security/impl/AbstractPKIXTrustEngine.cpp b/saml/security/impl/AbstractPKIXTrustEngine.cpp
new file mode 100644 (file)
index 0000000..b06b3c4
--- /dev/null
@@ -0,0 +1,372 @@
+/*\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
+    )\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)\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
index 4219a90..e26f56d 100644 (file)
@@ -56,13 +56,13 @@ namespace opensaml {
 \r
         virtual bool validate(\r
             Signature& sig,\r
-            RoleDescriptor& role,\r
+            const RoleDescriptor& role,\r
             const KeyResolver* keyResolver=NULL\r
             );\r
         virtual bool validate(\r
             XSECCryptoX509* certEE,\r
             const vector<XSECCryptoX509*>& certChain,\r
-            RoleDescriptor& role,\r
+            const RoleDescriptor& role,\r
             bool checkName=true,\r
             const KeyResolver* keyResolver=NULL\r
             );\r
@@ -79,7 +79,7 @@ namespace opensaml {
 \r
 bool ExplicitKeyTrustEngine::validate(\r
     Signature& sig,\r
-    RoleDescriptor& role,\r
+    const RoleDescriptor& role,\r
     const KeyResolver* keyResolver\r
     )\r
 {\r
@@ -108,7 +108,7 @@ bool ExplicitKeyTrustEngine::validate(
 bool ExplicitKeyTrustEngine::validate(\r
     XSECCryptoX509* certEE,\r
     const vector<XSECCryptoX509*>& certChain,\r
-    RoleDescriptor& role,\r
+    const RoleDescriptor& role,\r
     bool checkName,\r
     const KeyResolver* keyResolver\r
     )\r
index 73e4212..8aab1f1 100644 (file)
@@ -17,6 +17,7 @@ samltest_h = \
     signature/SAML1RequestTest.h \
     signature/SAML1ResponseTest.h \
     signature/SAML2AssertionTest.h \
+    security/AbstractPKIXTrustEngineTest.h \
     security/ExplicitKeyTrustEngineTest.h \
     saml1/core/impl/ActionTest.h \
     saml1/core/impl/AdviceTest.h \
diff --git a/samltest/data/security/FilesystemKeyResolver.xml b/samltest/data/security/FilesystemKeyResolver.xml
new file mode 100644 (file)
index 0000000..e37fb88
--- /dev/null
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<FilesystemKeyResolver>
+    <Certificate>
+        <Path>../samltest/data/cert.pem</Path>
+    </Certificate>
+</FilesystemKeyResolver>
index 5c88e41..830a691 100644 (file)
@@ -1,11 +1,14 @@
-<EntityDescriptor 
+<EntitiesDescriptor
        xmlns="urn:oasis:names:tc:SAML:2.0:metadata"
-       xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
+       xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
+
+<EntityDescriptor 
        entityID="https://idp.example.org">
        
        <IDPSSODescriptor protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">
                <KeyDescriptor use="signing">
                    <ds:KeyInfo>
+                       <ds:KeyName>sp.example.org</ds:KeyName>
                        <ds:X509Data>
                                <ds:X509Certificate>
                                        MIICjzCCAfigAwIBAgIJAKk8t1hYcMkhMA0GCSqGSIb3DQEBBAUAMDoxCzAJBgNV
        </IDPSSODescriptor>
 
 </EntityDescriptor>\r
+
+<EntityDescriptor 
+       entityID="https://idp2.example.org">
+       
+       <IDPSSODescriptor protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">
+               <KeyDescriptor use="signing">
+                       <ds:KeyInfo>
+                               <ds:KeyName>sp2.example.org</ds:KeyName>
+                       </ds:KeyInfo>
+               </KeyDescriptor>
+               
+               <SingleSignOnService Binding="foo" Location="foo"/>
+       </IDPSSODescriptor>
+       
+</EntityDescriptor>
+
+</EntitiesDescriptor>
\ No newline at end of file
index ba7d52f..7b160d5 100644 (file)
                                Name="security"\r
                                >\r
                                <File\r
+                                       RelativePath=".\security\AbstractPKIXTrustEngineTest.cpp"\r
+                                       >\r
+                               </File>\r
+                               <File\r
                                        RelativePath=".\security\ExplicitKeyTrustEngineTest.cpp"\r
                                        >\r
                                </File>\r
                                Name="security"\r
                                >\r
                                <File\r
-                                       RelativePath=".\security\ExplicitKeyTrustEngineTest.h"\r
+                                       RelativePath=".\security\AbstractPKIXTrustEngineTest.h"\r
                                        >\r
                                        <FileConfiguration\r
                                                Name="Debug|Win32"\r
                                                />\r
                                        </FileConfiguration>\r
                                </File>\r
+                               <File\r
+                                       RelativePath=".\security\ExplicitKeyTrustEngineTest.h"\r
+                                       >\r
+                                       <FileConfiguration\r
+                                               Name="Debug|Win32"\r
+                                               >\r
+                                               <Tool\r
+                                                       Name="VCCustomBuildTool"\r
+                                                       CommandLine="\perl\bin\perl.exe -w \cxxtest\cxxtestgen.pl --part --have-eh --have-std --abort-on-fail -o &quot;$(InputDir)$(InputName)&quot;.cpp &quot;$(InputPath)&quot;&#x0D;&#x0A;"\r
+                                                       Outputs="&quot;$(InputDir)$(InputName)&quot;.cpp"\r
+                                               />\r
+                                       </FileConfiguration>\r
+                                       <FileConfiguration\r
+                                               Name="Release|Win32"\r
+                                               >\r
+                                               <Tool\r
+                                                       Name="VCCustomBuildTool"\r
+                                                       CommandLine="\perl\bin\perl.exe -w \cxxtest\cxxtestgen.pl --part --have-eh --have-std --abort-on-fail -o &quot;$(InputDir)$(InputName)&quot;.cpp &quot;$(InputPath)&quot;&#x0D;&#x0A;"\r
+                                                       Outputs="&quot;$(InputDir)$(InputName)&quot;.cpp"\r
+                                               />\r
+                                       </FileConfiguration>\r
+                               </File>\r
                        </Filter>\r
                </Filter>\r
                <Filter\r
diff --git a/samltest/security/AbstractPKIXTrustEngineTest.h b/samltest/security/AbstractPKIXTrustEngineTest.h
new file mode 100644 (file)
index 0000000..3db7df2
--- /dev/null
@@ -0,0 +1,141 @@
+/*\r
+ *  Copyright 2001-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
+#include "internal.h"\r
+#include <saml/security/AbstractPKIXTrustEngine.h>\r
+#include <saml/saml2/metadata/MetadataProvider.h>\r
+\r
+using namespace opensaml::saml2;\r
+using namespace opensaml::saml2md;\r
+using namespace xmlsignature;\r
+\r
+namespace {\r
+    class SampleTrustEngine : public AbstractPKIXTrustEngine {\r
+    public:\r
+        SampleTrustEngine() {}\r
+        ~SampleTrustEngine() {}\r
+        \r
+        class SampleIterator : public PKIXValidationInfoIterator {\r
+            vector<XSECCryptoX509CRL*> m_crls;\r
+            KeyResolver::ResolvedCertificates m_certs;\r
+            KeyResolver* m_resolver;\r
+            bool m_done;\r
+        public:\r
+            SampleIterator() : m_resolver(NULL), m_done(false) {\r
+                string config = data_path + "security/FilesystemKeyResolver.xml";\r
+                ifstream in(config.c_str());\r
+                DOMDocument* doc=XMLToolingConfig::getConfig().getParser().parse(in);\r
+                XercesJanitor<DOMDocument> janitor(doc);\r
+                m_resolver = XMLToolingConfig::getConfig().KeyResolverManager.newPlugin(\r
+                    FILESYSTEM_KEY_RESOLVER,doc->getDocumentElement()\r
+                    );\r
+                m_resolver->resolveCertificates((KeyInfo*)NULL,m_certs);\r
+            }\r
+            \r
+            ~SampleIterator() {\r
+                delete m_resolver;\r
+            }\r
+\r
+            bool next() {\r
+                if (m_done)\r
+                    return false;\r
+                m_done = true;\r
+                return true;\r
+            }\r
+            \r
+            int getVerificationDepth() const {\r
+                return 0;\r
+            }\r
+            \r
+            const vector<XSECCryptoX509*>& getTrustAnchors() const {\r
+                return m_certs.v();\r
+            }\r
+            \r
+            const vector<XSECCryptoX509CRL*>& getCRLs() const {\r
+                return m_crls;\r
+            }\r
+        };\r
+    \r
+        PKIXValidationInfoIterator* getPKIXValidationInfoIterator(const RoleDescriptor& role) const {\r
+            return new SampleIterator();\r
+        }\r
+    };\r
+};\r
+\r
+class AbstractPKIXTrustEngineTest : public CxxTest::TestSuite, public SAMLObjectBaseTestCase {\r
+public:\r
+    void setUp() {\r
+        SAMLObjectBaseTestCase::setUp();\r
+    }\r
+    \r
+    void tearDown() {\r
+        SAMLObjectBaseTestCase::tearDown();\r
+    }\r
+\r
+    void testExplicitKeyTrustEngine() {\r
+        string config = data_path + "security/FilesystemMetadataProvider.xml";\r
+        ifstream in(config.c_str());\r
+        DOMDocument* doc=XMLToolingConfig::getConfig().getParser().parse(in);\r
+        XercesJanitor<DOMDocument> janitor(doc);\r
+\r
+        auto_ptr_XMLCh path("path");\r
+        string s = data_path + "security/example-metadata.xml";\r
+        auto_ptr_XMLCh file(s.c_str());\r
+        doc->getDocumentElement()->setAttributeNS(NULL,path.get(),file.get());\r
+\r
+        // Build metadata provider.\r
+        auto_ptr<MetadataProvider> metadataProvider(\r
+            SAMLConfig::getConfig().MetadataProviderManager.newPlugin(FILESYSTEM_METADATA_PROVIDER,doc->getDocumentElement())\r
+            );\r
+        try {\r
+            metadataProvider->init();\r
+        }\r
+        catch (XMLToolingException& ex) {\r
+            TS_TRACE(ex.what());\r
+            throw;\r
+        }\r
+        \r
+        // Build trust engine.\r
+        auto_ptr<opensaml::TrustEngine> trustEngine(new SampleTrustEngine());\r
+        \r
+        // Get signed assertion.\r
+        config = data_path + "signature/SAML2Assertion.xml";\r
+        ifstream in2(config.c_str());\r
+        DOMDocument* doc2=XMLToolingConfig::getConfig().getParser().parse(in2);\r
+        XercesJanitor<DOMDocument> janitor2(doc2);\r
+        auto_ptr<Assertion> assertion(dynamic_cast<Assertion*>(XMLObjectBuilder::getBuilder(doc2->getDocumentElement())->buildFromDocument(doc2)));\r
+        janitor2.release();\r
+\r
+        Locker locker(metadataProvider.get());\r
+        const EntityDescriptor* descriptor = metadataProvider->getEntityDescriptor("https://idp.example.org");\r
+        TSM_ASSERT("Retrieved entity descriptor was null", descriptor!=NULL);\r
+        \r
+        RoleDescriptor* role=descriptor->getIDPSSODescriptors().front();\r
+        TSM_ASSERT("Role not present", role!=NULL);\r
+        \r
+        Signature* sig=assertion->getSignature();\r
+        TSM_ASSERT("Signature not present", sig!=NULL);\r
+        TSM_ASSERT("Signature failed to validate.", trustEngine->validate(*sig, *role, metadataProvider->getKeyResolver()));\r
+\r
+        descriptor = metadataProvider->getEntityDescriptor("https://idp2.example.org");\r
+        TSM_ASSERT("Retrieved entity descriptor was null", descriptor!=NULL);\r
+        \r
+        role=descriptor->getIDPSSODescriptors().front();\r
+        TSM_ASSERT("Role not present", role!=NULL);\r
+\r
+        TSM_ASSERT("Signature validated.", !trustEngine->validate(*sig, *role, metadataProvider->getKeyResolver()));\r
+    }\r
+};\r
index 511de41..53416e9 100644 (file)
@@ -72,12 +72,19 @@ public:
         const EntityDescriptor* descriptor = metadataProvider->getEntityDescriptor("https://idp.example.org");\r
         TSM_ASSERT("Retrieved entity descriptor was null", descriptor!=NULL);\r
         \r
-        Signature* sig=assertion->getSignature();\r
-        TSM_ASSERT("Signature not present", sig!=NULL);\r
-\r
         RoleDescriptor* role=descriptor->getIDPSSODescriptors().front();\r
         TSM_ASSERT("Role not present", role!=NULL);\r
         \r
+        Signature* sig=assertion->getSignature();\r
+        TSM_ASSERT("Signature not present", sig!=NULL);\r
         TSM_ASSERT("Signature failed to validate.", trustEngine->validate(*sig, *role, metadataProvider->getKeyResolver()));\r
+\r
+        descriptor = metadataProvider->getEntityDescriptor("https://idp2.example.org");\r
+        TSM_ASSERT("Retrieved entity descriptor was null", descriptor!=NULL);\r
+        \r
+        role=descriptor->getIDPSSODescriptors().front();\r
+        TSM_ASSERT("Role not present", role!=NULL);\r
+\r
+        TSM_ASSERT("Signature validated.", !trustEngine->validate(*sig, *role, metadataProvider->getKeyResolver()));\r
     }\r
 };\r