Move credential usage enum to Credential class.
[shibboleth/xmltooling.git] / xmltooling / security / impl / AbstractPKIXTrustEngine.cpp
index 13a77ba..69e24f3 100644 (file)
  */
 
 #include "internal.h"
+#include "logging.h"
 #include "security/AbstractPKIXTrustEngine.h"
 #include "signature/KeyInfo.h"
 
-#include <log4cpp/Category.hh>
 #include <openssl/x509_vfy.h>
 #include <openssl/x509v3.h>
+#include <xmltooling/security/CredentialCriteria.h>
+#include <xmltooling/security/CredentialResolver.h>
+#include <xmltooling/security/KeyInfoResolver.h>
 #include <xmltooling/security/OpenSSLCryptoX509CRL.h>
+#include <xmltooling/security/X509Credential.h>
 #include <xmltooling/signature/SignatureValidator.h>
 #include <xmltooling/util/NDC.h>
 #include <xsec/enc/OpenSSL/OpenSSLCryptoX509.hpp>
 
 using namespace xmlsignature;
+using namespace xmltooling::logging;
 using namespace xmltooling;
-using namespace log4cpp;
 using namespace std;
 
-AbstractPKIXTrustEngine::AbstractPKIXTrustEngine(const DOMElement* e) : OpenSSLTrustEngine(e), m_inlineResolver(NULL)
-{
-    m_inlineResolver = XMLToolingConfig::getConfig().KeyResolverManager.newPlugin(INLINE_KEY_RESOLVER,NULL);
-}
-
-AbstractPKIXTrustEngine::~AbstractPKIXTrustEngine()
-{
-    delete m_inlineResolver;
-}
 
 namespace {
     static int XMLTOOL_DLLLOCAL error_callback(int ok, X509_STORE_CTX* ctx)
@@ -91,10 +86,7 @@ namespace {
         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())
-                    );
+                X509_STORE_add_crl(store, X509_CRL_dup(static_cast<OpenSSLCryptoX509CRL*>(*j)->getOpenSSLX509CRL()));
             }
         }
      
@@ -136,7 +128,7 @@ namespace {
         sk_X509_free(CAstack);
     
         if (ret==1) {
-            log.info("successfully validated certificate chain");
+            log.debug("successfully validated certificate chain");
             return true;
         }
         
@@ -144,31 +136,22 @@ namespace {
     }
 };
 
-bool AbstractPKIXTrustEngine::checkEntityNames(X509* certEE, const KeyInfoSource& keyInfoSource) const
+bool AbstractPKIXTrustEngine::checkEntityNames(
+    X509* certEE, const CredentialResolver& credResolver, const CredentialCriteria& criteria
+    ) const
 {
-    Category& log=Category::getInstance(XMLTOOLING_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;
-    auto_ptr<KeyInfoIterator> keyInfoIter(keyInfoSource.getKeyInfoIterator());
-    while (keyInfoIter->hasNext()) {
-        const KeyInfo* keyInfo = keyInfoIter->next();
-        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;
-            }
-        }
-    }
+    Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX");
+
+    // We resolve to a set of trusted credentials.
+    vector<const Credential*> creds;
+    credResolver.resolve(creds,&criteria);
+
+    // Build a list of acceptable names.
+    set<string> trustednames;
+    trustednames.insert(criteria.getPeerName());
+    for (vector<const Credential*>::const_iterator cred = creds.begin(); cred!=creds.end(); ++cred)
+        trustednames.insert((*cred)->getKeyNames().begin(), (*cred)->getKeyNames().end());
 
-    string peername = keyInfoSource.getName();
-    if (!peername.empty())
-        keynames.push_back(peername);
-    
     char buf[256];
     X509_NAME* subject=X509_get_subject_name(certEE);
     if (subject) {
@@ -186,7 +169,7 @@ bool AbstractPKIXTrustEngine::checkEntityNames(X509* certEE, const KeyInfoSource
             buf[len] = '\0';
             subjectstr+=buf;
         }
-        log.infoStream() << "certificate subject: " << subjectstr << CategoryStream::ENDLINE;
+        log.debugStream() << "certificate subject: " << subjectstr << logging::eol;
         // 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);
@@ -196,13 +179,13 @@ bool AbstractPKIXTrustEngine::checkEntityNames(X509* certEE, const KeyInfoSource
         }
         
         // Check each keyname.
-        for (vector<string>::const_iterator n=keynames.begin(); n!=keynames.end(); n++) {
+        for (set<string>::const_iterator n=trustednames.begin(); n!=trustednames.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());
+                log.debug("matched full subject DN to a key name (%s)", n->c_str());
                 BIO_free(b);
                 BIO_free(b2);
                 return true;
@@ -220,15 +203,14 @@ bool AbstractPKIXTrustEngine::checkEntityNames(X509* certEE, const KeyInfoSource
                 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++) {
+                    for (set<string>::const_iterator n=trustednames.begin(); n!=trustednames.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());
+                            log.debug("matched DNS/URI subjectAltName to a key name (%s)", n->c_str());
                             GENERAL_NAMES_free(altnames);
                             return true;
                         }
@@ -241,13 +223,13 @@ bool AbstractPKIXTrustEngine::checkEntityNames(X509* certEE, const KeyInfoSource
         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++) {
+            for (set<string>::const_iterator n=trustednames.begin(); n!=trustednames.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());
+                    log.debug("matched subject CN to a key name (%s)", n->c_str());
                     return true;
                 }
             }
@@ -264,24 +246,25 @@ bool AbstractPKIXTrustEngine::checkEntityNames(X509* certEE, const KeyInfoSource
 bool AbstractPKIXTrustEngine::validate(
     X509* certEE,
     STACK_OF(X509)* certChain,
-    const KeyInfoSource& keyInfoSource,
-    bool checkName,
-    const KeyResolver* keyResolver
+    const CredentialResolver& credResolver,
+    CredentialCriteria* criteria
     ) const
 {
 #ifdef _DEBUG
     NDC ndc("validate");
 #endif
-    Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine");
+    Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX");
 
     if (!certEE) {
         log.error("X.509 credential was NULL, unable to perform validation");
         return false;
     }
 
-    if (checkName) {
+    if (criteria && criteria->getPeerName() && *(criteria->getPeerName())) {
         log.debug("checking that the certificate name is acceptable");
-        if (!checkEntityNames(certEE,keyInfoSource)) {
+        if (criteria->getUsage()==Credential::UNSPECIFIED_CREDENTIAL)
+            criteria->setUsage(Credential::SIGNING_CREDENTIAL);
+        if (!checkEntityNames(certEE,credResolver,*criteria)) {
             log.error("certificate name was not acceptable");
             return false;
         }
@@ -289,66 +272,73 @@ bool AbstractPKIXTrustEngine::validate(
     
     log.debug("performing certificate path validation...");
 
-    auto_ptr<PKIXValidationInfoIterator> pkix(
-        getPKIXValidationInfoIterator(keyInfoSource, *(keyResolver ? keyResolver : m_inlineResolver))
-        );
+    auto_ptr<PKIXValidationInfoIterator> pkix(getPKIXValidationInfoIterator(credResolver, criteria));
     while (pkix->next()) {
         if (::validate(certEE,certChain,pkix.get())) {
             return true;
         }
     }
 
-    log.error("failed to validate certificate chain using supplied PKIX information");
+    log.debug("failed to validate certificate chain using supplied PKIX information");
     return false;
 }
 
 bool AbstractPKIXTrustEngine::validate(
     XSECCryptoX509* certEE,
     const vector<XSECCryptoX509*>& certChain,
-    const KeyInfoSource& keyInfoSource,
-    bool checkName,
-    const KeyResolver* keyResolver
+    const CredentialResolver& credResolver,
+    CredentialCriteria* criteria
     ) const
 {
-    if (!certEE) {
 #ifdef _DEBUG
         NDC ndc("validate");
 #endif
-        Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine").error("X.509 credential was NULL, unable to perform validation");
+    if (!certEE) {
+        Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX").error("X.509 credential was NULL, unable to perform validation");
         return false;
     }
     else if (certEE->getProviderName()!=DSIGConstants::s_unicodeStrPROVOpenSSL) {
-#ifdef _DEBUG
-        NDC ndc("validate");
-#endif
-        Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine").error("only the OpenSSL XSEC provider is supported");
+        Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX").error("only the OpenSSL XSEC provider is supported");
         return false;
     }
 
     STACK_OF(X509)* untrusted=sk_X509_new_null();
-    for (vector<XSECCryptoX509*>::const_iterator i=certChain.begin(); i!=certChain.end(); ++i) {
+    for (vector<XSECCryptoX509*>::const_iterator i=certChain.begin(); i!=certChain.end(); ++i)
         sk_X509_push(untrusted,static_cast<OpenSSLCryptoX509*>(*i)->getOpenSSLX509());
-    }
 
-    bool ret = validate(static_cast<OpenSSLCryptoX509*>(certEE)->getOpenSSLX509(),untrusted,keyInfoSource,checkName,keyResolver);
+    bool ret = validate(static_cast<OpenSSLCryptoX509*>(certEE)->getOpenSSLX509(), untrusted, credResolver, criteria);
     sk_X509_free(untrusted);
     return ret;
 }
 
 bool AbstractPKIXTrustEngine::validate(
     Signature& sig,
-    const KeyInfoSource& keyInfoSource,
-    const KeyResolver* keyResolver
+    const CredentialResolver& credResolver,
+    CredentialCriteria* criteria
     ) const
 {
 #ifdef _DEBUG
     NDC ndc("validate");
 #endif
-    Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine");
+    Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX");
 
-    // Pull the certificate chain out of the signature using an inline KeyResolver.
-    KeyResolver::ResolvedCertificates certs;
-    if (0==m_inlineResolver->resolveCertificates(&sig, certs)) {
+    const KeyInfoResolver* inlineResolver = m_keyInfoResolver;
+    if (!inlineResolver)
+        inlineResolver = XMLToolingConfig::getConfig().getKeyInfoResolver();
+    if (!inlineResolver) {
+        log.error("unable to perform PKIX validation, no KeyInfoResolver available");
+        return false;
+    }
+
+    // Pull the certificate chain out of the signature.
+    X509Credential* x509cred;
+    auto_ptr<Credential> cred(inlineResolver->resolve(&sig,X509Credential::RESOLVE_CERTS));
+    if (!cred.get() || !(x509cred=dynamic_cast<X509Credential*>(cred.get()))) {
+        log.error("unable to perform PKIX validation, signature does not contain any certificates");
+        return false;
+    }
+    const vector<XSECCryptoX509*>& certs = x509cred->getEntityCertificateChain();
+    if (certs.empty()) {
         log.error("unable to perform PKIX validation, signature does not contain any certificates");
         return false;
     }
@@ -359,22 +349,23 @@ bool AbstractPKIXTrustEngine::validate(
     // 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) {
+    for (vector<XSECCryptoX509*>::const_iterator i=certs.begin(); !certEE && i!=certs.end(); ++i) {
         try {
-            keyValidator.setKey((*i)->clonePublicKey());
+            auto_ptr<XSECCryptoKey> key((*i)->clonePublicKey());
+            keyValidator.setKey(key.get());
             keyValidator.validate(&sig);
-            log.info("signature verified with key inside signature, attempting certificate validation...");
+            log.debug("signature verified with key inside signature, attempting certificate validation...");
             certEE=(*i);
         }
-        catch (ValidationException&) {
-            // trap failures
+        catch (ValidationException& ex) {
+            log.debug(ex.what());
         }
     }
     
     if (certEE)
-        return validate(certEE,certs.v(),keyInfoSource,true,keyResolver);
+        return validate(certEE,certs,credResolver,criteria);
         
-    log.error("failed to verify signature with embedded certificates");
+    log.debug("failed to verify signature with embedded certificates");
     return false;
 }
 
@@ -384,18 +375,37 @@ bool AbstractPKIXTrustEngine::validate(
     KeyInfo* keyInfo,
     const char* in,
     unsigned int in_len,
-    const KeyInfoSource& keyInfoSource,
-    const KeyResolver* keyResolver
+    const CredentialResolver& credResolver,
+    CredentialCriteria* criteria
     ) const
 {
 #ifdef _DEBUG
     NDC ndc("validate");
 #endif
-    Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine");
+    Category& log=Category::getInstance(XMLTOOLING_LOGCAT".TrustEngine.PKIX");
+
+    if (!keyInfo) {
+        log.error("unable to perform PKIX validation, KeyInfo not present");
+        return false;
+    }
+
+    const KeyInfoResolver* inlineResolver = m_keyInfoResolver;
+    if (!inlineResolver)
+        inlineResolver = XMLToolingConfig::getConfig().getKeyInfoResolver();
+    if (!inlineResolver) {
+        log.error("unable to perform PKIX validation, no KeyInfoResolver available");
+        return false;
+    }
 
-    // Pull the certificate chain out of the KeyInfo using an inline KeyResolver.
-    KeyResolver::ResolvedCertificates certs;
-    if (!keyInfo || 0==m_inlineResolver->resolveCertificates(keyInfo, certs)) {
+    // Pull the certificate chain out of the signature.
+    X509Credential* x509cred;
+    auto_ptr<Credential> cred(inlineResolver->resolve(keyInfo,X509Credential::RESOLVE_CERTS));
+    if (!cred.get() || !(x509cred=dynamic_cast<X509Credential*>(cred.get()))) {
+        log.error("unable to perform PKIX validation, KeyInfo does not contain any certificates");
+        return false;
+    }
+    const vector<XSECCryptoX509*>& certs = x509cred->getEntityCertificateChain();
+    if (certs.empty()) {
         log.error("unable to perform PKIX validation, KeyInfo does not contain any certificates");
         return false;
     }
@@ -405,23 +415,22 @@ bool AbstractPKIXTrustEngine::validate(
     // 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) {
+    for (vector<XSECCryptoX509*>::const_iterator i=certs.begin(); !certEE && i!=certs.end(); ++i) {
         try {
             auto_ptr<XSECCryptoKey> key((*i)->clonePublicKey());
             if (Signature::verifyRawSignature(key.get(), sigAlgorithm, sig, in, in_len)) {
-                log.info("signature verified with key inside signature, attempting certificate validation...");
+                log.debug("signature verified with key inside signature, attempting certificate validation...");
                 certEE=(*i);
             }
         }
-        catch (SignatureException&) {
-            // trap failures
+        catch (SignatureException& ex) {
+            log.debug(ex.what());
         }
     }
     
     if (certEE)
-        return validate(certEE,certs.v(),keyInfoSource,true,keyResolver);
+        return validate(certEE,certs,credResolver,criteria);
         
-    log.error("failed to verify signature with embedded certificates");
+    log.debug("failed to verify signature with embedded certificates");
     return false;
 }