Redesign condition and profile processing based on new policy rules. Fix element...
[shibboleth/cpp-sp.git] / shibsp / attribute / resolver / impl / QueryAttributeResolver.cpp
index 2cf113e..fbecae7 100644 (file)
@@ -1,6 +1,6 @@
 /*
  *  Copyright 2001-2007 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
@@ -16,7 +16,7 @@
 
 /**
  * QueryAttributeResolver.cpp
- * 
+ *
  * AttributeResolver based on SAML queries.
  */
 
@@ -31,6 +31,7 @@
 #include "attribute/resolver/AttributeResolver.h"
 #include "attribute/resolver/ResolutionContext.h"
 #include "binding/SOAPClient.h"
+#include "metadata/MetadataProviderCriteria.h"
 #include "util/SPConstants.h"
 
 #include <saml/exceptions.h>
@@ -69,12 +70,12 @@ namespace shibsp {
             m_class = XMLString::transcode(session.getAuthnContextClassRef());
             m_decl = XMLString::transcode(session.getAuthnContextDeclRef());
         }
-        
+
         QueryContext(
             const Application& application,
             const EntityDescriptor* issuer,
             const XMLCh* protocol,
-            const NameID* nameid,
+            const NameID* nameid=NULL,
             const XMLCh* authncontext_class=NULL,
             const XMLCh* authncontext_decl=NULL,
             const vector<const opensaml::Assertion*>* tokens=NULL,
@@ -97,7 +98,7 @@ namespace shibsp {
                 }
             }
         }
-        
+
         ~QueryContext() {
             if (m_session) {
                 XMLString::release((XMLCh**)&m_protocol);
@@ -109,7 +110,7 @@ namespace shibsp {
             for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<shibsp::Attribute>());
             for_each(m_assertions.begin(), m_assertions.end(), xmltooling::cleanup<opensaml::Assertion>());
         }
-    
+
         bool doQuery() const {
             return m_query;
         }
@@ -121,10 +122,10 @@ namespace shibsp {
             if (m_entity)
                 return m_entity;
             if (m_session && m_session->getEntityID()) {
-                m_metadata = m_app.getMetadataProvider();
+                m_metadata = m_app.getMetadataProvider(false);
                 if (m_metadata) {
                     m_metadata->lock();
-                    return m_entity = m_metadata->getEntityDescriptor(m_session->getEntityID());
+                    return m_entity = m_metadata->getEntityDescriptor(MetadataProviderCriteria(m_app, m_session->getEntityID())).first;
                 }
             }
             return NULL;
@@ -164,7 +165,7 @@ namespace shibsp {
         vector<shibsp::Attribute*> m_attributes;
         vector<opensaml::Assertion*> m_assertions;
     };
-    
+
     class SHIBSP_DLLLOCAL QueryResolver : public AttributeResolver
     {
     public:
@@ -176,12 +177,12 @@ namespace shibsp {
 
         Lockable* lock() {return this;}
         void unlock() {}
-        
+
         ResolutionContext* createResolutionContext(
             const Application& application,
             const EntityDescriptor* issuer,
             const XMLCh* protocol,
-            const NameID* nameid,
+            const NameID* nameid=NULL,
             const XMLCh* authncontext_class=NULL,
             const XMLCh* authncontext_decl=NULL,
             const vector<const opensaml::Assertion*>* tokens=NULL,
@@ -205,6 +206,7 @@ namespace shibsp {
         bool SAML2Query(QueryContext& ctx) const;
 
         Category& m_log;
+        string m_policyId;
         vector<AttributeDesignator*> m_SAML1Designators;
         vector<saml2::Attribute*> m_SAML2Designators;
     };
@@ -213,20 +215,22 @@ namespace shibsp {
     {
         return new QueryResolver(e);
     }
-    
-};
 
-void SHIBSP_API shibsp::registerAttributeResolvers()
-{
-    SPConfig::getConfig().AttributeResolverManager.registerFactory(QUERY_ATTRIBUTE_RESOLVER, QueryResolverFactory);
-}
+    static const XMLCh _policyId[] = UNICODE_LITERAL_8(p,o,l,i,c,y,I,d);
+};
 
-QueryResolver::QueryResolver(const DOMElement* e) : m_log(Category::getInstance(SHIBSP_LOGCAT".AttributeResolver"))
+QueryResolver::QueryResolver(const DOMElement* e) : m_log(Category::getInstance(SHIBSP_LOGCAT".AttributeResolver.Query"))
 {
 #ifdef _DEBUG
     xmltooling::NDC ndc("QueryResolver");
 #endif
-    
+
+    const XMLCh* pid = e ? e->getAttributeNS(NULL, _policyId) : NULL;
+    if (pid && *pid) {
+        auto_ptr_char temp(pid);
+        m_policyId = temp.get();
+    }
+
     DOMElement* child = XMLHelper::getFirstChildElement(e);
     while (child) {
         try {
@@ -261,29 +265,36 @@ bool QueryResolver::SAML1Query(QueryContext& ctx) const
 #endif
 
     int version = XMLString::equals(ctx.getProtocol(), samlconstants::SAML11_PROTOCOL_ENUM) ? 1 : 0;
-    const AttributeAuthorityDescriptor* AA = ctx.getEntityDescriptor()->getAttributeAuthorityDescriptor(ctx.getProtocol());
+    const AttributeAuthorityDescriptor* AA =
+        find_if(ctx.getEntityDescriptor()->getAttributeAuthorityDescriptors(), isValidForProtocol(ctx.getProtocol()));
     if (!AA) {
         m_log.warn("no SAML 1.%d AttributeAuthority role found in metadata", version);
         return false;
     }
 
     const Application& application = ctx.getApplication();
-    shibsp::SecurityPolicy policy(application);
+    const PropertySet* relyingParty = application.getRelyingParty(ctx.getEntityDescriptor());
+
+    // Locate policy key.
+    const char* policyId = m_policyId.empty() ? application.getString("policyId").second : m_policyId.c_str();
+
+    // Access policy properties.
+    const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId);
+    pair<bool,bool> validate = settings->getBool("validate");
+
+    shibsp::SecurityPolicy policy(application, NULL, validate.first && validate.second, policyId);
+    policy.getAudiences().push_back(relyingParty->getXMLString("entityID").second);
     MetadataCredentialCriteria mcc(*AA);
     shibsp::SOAPClient soaper(policy);
-    const PropertySet* policySettings =
-        application.getServiceProvider().getPolicySettings(application.getString("policyId").second);
-    pair<bool,bool> signedAssertions = policySettings->getBool("signedAssertions");
 
     auto_ptr_XMLCh binding(samlconstants::SAML1_BINDING_SOAP);
     saml1p::Response* response=NULL;
     const vector<AttributeService*>& endpoints=AA->getAttributeServices();
     for (vector<AttributeService*>::const_iterator ep=endpoints.begin(); !response && ep!=endpoints.end(); ++ep) {
+        if (!XMLString::equals((*ep)->getBinding(),binding.get()) || !(*ep)->getLocation())
+            continue;
+        auto_ptr_char loc((*ep)->getLocation());
         try {
-            if (!XMLString::equals((*ep)->getBinding(),binding.get()))
-                continue;
-            auto_ptr_char loc((*ep)->getLocation());
-            auto_ptr_XMLCh issuer(application.getString("entityID").second);
             NameIdentifier* nameid = NameIdentifierBuilder::buildNameIdentifier();
             nameid->setName(ctx.getNameID()->getName());
             nameid->setFormat(ctx.getNameID()->getFormat());
@@ -292,7 +303,7 @@ bool QueryResolver::SAML1Query(QueryContext& ctx) const
             subject->setNameIdentifier(nameid);
             saml1p::AttributeQuery* query = saml1p::AttributeQueryBuilder::buildAttributeQuery();
             query->setSubject(subject);
-            query->setResource(issuer.get());
+            query->setResource(relyingParty->getXMLString("entityID").second);
             for (vector<AttributeDesignator*>::const_iterator ad = m_SAML1Designators.begin(); ad!=m_SAML1Designators.end(); ++ad)
                 query->getAttributeDesignators().push_back((*ad)->cloneAttributeDesignator());
             Request* request = RequestBuilder::buildRequest();
@@ -304,7 +315,7 @@ bool QueryResolver::SAML1Query(QueryContext& ctx) const
             response = client.receiveSAML();
         }
         catch (exception& ex) {
-            m_log.error("exception making SAML query: %s", ex.what());
+            m_log.error("exception during SAML query to %s: %s", loc.get(), ex.what());
             soaper.reset();
         }
     }
@@ -332,6 +343,7 @@ bool QueryResolver::SAML1Query(QueryContext& ctx) const
     auto_ptr<saml1p::Response> wrapper(response);
     saml1::Assertion* newtoken = assertions.front();
 
+    pair<bool,bool> signedAssertions = relyingParty->getBool("requireSignedAssertions");
     if (!newtoken->getSignature() && signedAssertions.first && signedAssertions.second) {
         m_log.error("assertion unsigned, rejecting it based on signedAssertions policy");
         return true;
@@ -351,7 +363,7 @@ bool QueryResolver::SAML1Query(QueryContext& ctx) const
             throw SecurityPolicyException("Security of SAML 1.x query result not established.");
 
         // Lastly, check it over.
-        saml1::AssertionValidator tokval(application.getAudiences(), time(NULL));
+        saml1::AssertionValidator tokval(relyingParty->getXMLString("entityID").second, application.getAudiences(), time(NULL));
         tokval.validateAssertion(*newtoken);
     }
     catch (exception& ex) {
@@ -393,32 +405,39 @@ bool QueryResolver::SAML2Query(QueryContext& ctx) const
     xmltooling::NDC ndc("query");
 #endif
 
-    const AttributeAuthorityDescriptor* AA = ctx.getEntityDescriptor()->getAttributeAuthorityDescriptor(samlconstants::SAML20P_NS);
+    const AttributeAuthorityDescriptor* AA =
+        find_if(ctx.getEntityDescriptor()->getAttributeAuthorityDescriptors(), isValidForProtocol(samlconstants::SAML20P_NS));
     if (!AA) {
         m_log.warn("no SAML 2 AttributeAuthority role found in metadata");
         return false;
     }
 
     const Application& application = ctx.getApplication();
-    shibsp::SecurityPolicy policy(application);
-    MetadataCredentialCriteria mcc(*AA);
-    shibsp::SOAPClient soaper(policy);
-    const PropertySet* policySettings = application.getServiceProvider().getPolicySettings(application.getString("policyId").second);
-    pair<bool,bool> signedAssertions = policySettings->getBool("signedAssertions");
-
     const PropertySet* relyingParty = application.getRelyingParty(ctx.getEntityDescriptor());
+
+    // Locate policy key.
+    const char* policyId = m_policyId.empty() ? application.getString("policyId").second : m_policyId.c_str();
+
+    // Access policy properties.
+    const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId);
+    pair<bool,bool> validate = settings->getBool("validate");
+
+    pair<bool,bool> signedAssertions = relyingParty->getBool("requireSignedAssertions");
     pair<bool,const char*> encryption = relyingParty->getString("encryption");
 
+    shibsp::SecurityPolicy policy(application, NULL, validate.first && validate.second, policyId);
+    policy.getAudiences().push_back(relyingParty->getXMLString("entityID").second);
+    MetadataCredentialCriteria mcc(*AA);
+    shibsp::SOAPClient soaper(policy);
+
     auto_ptr_XMLCh binding(samlconstants::SAML20_BINDING_SOAP);
     saml2p::StatusResponseType* srt=NULL;
     const vector<AttributeService*>& endpoints=AA->getAttributeServices();
     for (vector<AttributeService*>::const_iterator ep=endpoints.begin(); !srt && ep!=endpoints.end(); ++ep) {
+        if (!XMLString::equals((*ep)->getBinding(),binding.get())  || !(*ep)->getLocation())
+            continue;
+        auto_ptr_char loc((*ep)->getLocation());
         try {
-            if (!XMLString::equals((*ep)->getBinding(),binding.get()))
-                continue;
-            auto_ptr_char loc((*ep)->getLocation());
-            auto_ptr_XMLCh issuer(application.getString("entityID").second);
-
             auto_ptr<saml2::Subject> subject(saml2::SubjectBuilder::buildSubject());
 
             // Encrypt the NameID?
@@ -441,7 +460,7 @@ bool QueryResolver::SAML2Query(QueryContext& ctx) const
             saml2p::AttributeQuery* query = saml2p::AttributeQueryBuilder::buildAttributeQuery();
             query->setSubject(subject.release());
             Issuer* iss = IssuerBuilder::buildIssuer();
-            iss->setName(issuer.get());
+            iss->setName(relyingParty->getXMLString("entityID").second);
             query->setIssuer(iss);
             for (vector<saml2::Attribute*>::const_iterator ad = m_SAML2Designators.begin(); ad!=m_SAML2Designators.end(); ++ad)
                 query->getAttributes().push_back((*ad)->cloneAttribute());
@@ -451,7 +470,7 @@ bool QueryResolver::SAML2Query(QueryContext& ctx) const
             srt = client.receiveSAML();
         }
         catch (exception& ex) {
-            m_log.error("exception making SAML query: %s", ex.what());
+            m_log.error("exception during SAML query to %s: %s", loc.get(), ex.what());
             soaper.reset();
         }
     }
@@ -504,7 +523,7 @@ bool QueryResolver::SAML2Query(QueryContext& ctx) const
             throw SecurityPolicyException("Security of SAML 2.0 query result not established.");
 
         // Lastly, check it over.
-        saml2::AssertionValidator tokval(application.getAudiences(), time(NULL));
+        saml2::AssertionValidator tokval(relyingParty->getXMLString("entityID").second, application.getAudiences(), time(NULL));
         tokval.validateAssertion(*newtoken);
     }
     catch (exception& ex) {