ArtifactMap support.
[shibboleth/sp.git] / shibsp / impl / XMLServiceProvider.cpp
index 54dbde6..33d540c 100644 (file)
 #include "exceptions.h"\r
 #include "AccessControl.h"\r
 #include "Application.h"\r
-#include "Handler.h"\r
 #include "RequestMapper.h"\r
 #include "ServiceProvider.h"\r
 #include "SessionCache.h"\r
 #include "SPConfig.h"\r
 #include "SPRequest.h"\r
 #include "TransactionLog.h"\r
-#include "attribute/Attribute.h"\r
+#include "attribute/resolver/AttributeResolver.h"\r
+#include "handler/Handler.h"\r
 #include "remoting/ListenerService.h"\r
 #include "security/PKIXTrustEngine.h"\r
 #include "util/DOMPropertySet.h"\r
@@ -42,6 +42,7 @@
 #include <log4cpp/Category.hh>\r
 #include <log4cpp/PropertyConfigurator.hh>\r
 #include <saml/SAMLConfig.h>\r
+#include <saml/binding/ArtifactMap.h>\r
 #include <saml/saml1/core/Assertions.h>\r
 #include <saml/saml2/metadata/ChainingMetadataProvider.h>\r
 #include <xmltooling/XMLToolingConfig.h>\r
@@ -57,7 +58,6 @@ using namespace opensaml;
 using namespace xmltooling;\r
 using namespace log4cpp;\r
 using namespace std;\r
-using xmlsignature::CredentialResolver;\r
 \r
 namespace {\r
 \r
@@ -66,6 +66,18 @@ namespace {
     #pragma warning( disable : 4250 )\r
 #endif\r
 \r
+    class SHIBSP_DLLLOCAL TokenValidator : public Validator\r
+    {\r
+    public:\r
+        TokenValidator(const Application& app, time_t ts=0, const RoleDescriptor* role=NULL) : m_app(app), m_ts(ts), m_role(role) {}\r
+        void validate(const XMLObject*) const;\r
+\r
+    private:\r
+        const Application& m_app;\r
+        time_t m_ts;\r
+        const RoleDescriptor* m_role;\r
+    };\r
+\r
     static vector<const Handler*> g_noHandlers;\r
 \r
     // Application configuration wrapper\r
@@ -81,14 +93,23 @@ namespace {
         pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;\r
         pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;\r
         pair<bool,int> getInt(const char* name, const char* ns=NULL) const;\r
-        const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;\r
+        const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:sp:config:2.0") const;\r
 \r
         // Application\r
+        const ServiceProvider& getServiceProvider() const {return *m_sp;}\r
         const char* getId() const {return getString("id").second;}\r
         const char* getHash() const {return m_hash.c_str();}\r
-        MetadataProvider* getMetadataProvider() const;\r
-        TrustEngine* getTrustEngine() const;\r
-        const vector<const XMLCh*>& getAudiences() const;\r
+\r
+        MetadataProvider* getMetadataProvider() const {\r
+            return (!m_metadata && m_base) ? m_base->getMetadataProvider() : m_metadata;\r
+        }\r
+        TrustEngine* getTrustEngine() const {\r
+            return (!m_trust && m_base) ? m_base->getTrustEngine() : m_trust;\r
+        }\r
+        AttributeResolver* getAttributeResolver() const {\r
+            return (!m_attrResolver && m_base) ? m_base->getAttributeResolver() : m_attrResolver;\r
+        }\r
+\r
         const PropertySet* getCredentialUse(const EntityDescriptor* provider) const;\r
 \r
         const Handler* getDefaultSessionInitiator() const;\r
@@ -97,7 +118,14 @@ namespace {
         const Handler* getAssertionConsumerServiceByIndex(unsigned short index) const;\r
         const vector<const Handler*>& getAssertionConsumerServicesByBinding(const XMLCh* binding) const;\r
         const Handler* getHandler(const char* path) const;\r
-        \r
+\r
+        const vector<const XMLCh*>& getAudiences() const {\r
+            return (m_audiences.empty() && m_base) ? m_base->getAudiences() : m_audiences;\r
+        }\r
+        Validator* getTokenValidator(time_t ts=0, const opensaml::saml2md::RoleDescriptor* role=NULL) const {\r
+            return new TokenValidator(*this, ts, role);\r
+        }\r
+\r
         // Provides filter to exclude special config elements.\r
         short acceptNode(const DOMNode* node) const;\r
     \r
@@ -108,6 +136,7 @@ namespace {
         string m_hash;\r
         MetadataProvider* m_metadata;\r
         TrustEngine* m_trust;\r
+        AttributeResolver* m_attrResolver;\r
         vector<const XMLCh*> m_audiences;\r
 \r
         // manage handler objects\r
@@ -188,6 +217,7 @@ namespace {
             delete m_listener;\r
             delete m_tranLog;\r
             XMLToolingConfig::getConfig().setReplayCache(NULL);\r
+            SAMLConfig::getConfig().setArtifactMap(NULL);\r
             for_each(m_storage.begin(), m_storage.end(), cleanup_pair<string,StorageService>());\r
         }\r
 \r
@@ -280,6 +310,8 @@ namespace {
 \r
     static const XMLCh _Application[] =         UNICODE_LITERAL_11(A,p,p,l,i,c,a,t,i,o,n);\r
     static const XMLCh Applications[] =         UNICODE_LITERAL_12(A,p,p,l,i,c,a,t,i,o,n,s);\r
+    static const XMLCh _ArtifactMap[] =         UNICODE_LITERAL_11(A,r,t,i,f,a,c,t,M,a,p);\r
+    static const XMLCh _AttributeResolver[] =   UNICODE_LITERAL_17(A,t,t,r,i,b,u,t,e,R,e,s,o,l,v,e,r);\r
     static const XMLCh Credentials[] =          UNICODE_LITERAL_11(C,r,e,d,e,n,t,i,a,l,s);\r
     static const XMLCh CredentialUse[] =        UNICODE_LITERAL_13(C,r,e,d,e,n,t,i,a,l,U,s,e);\r
     static const XMLCh fatal[] =                UNICODE_LITERAL_5(f,a,t,a,l);\r
@@ -291,6 +323,9 @@ namespace {
     static const XMLCh Listener[] =             UNICODE_LITERAL_8(L,i,s,t,e,n,e,r);\r
     static const XMLCh logger[] =               UNICODE_LITERAL_6(l,o,g,g,e,r);\r
     static const XMLCh MemoryListener[] =       UNICODE_LITERAL_14(M,e,m,o,r,y,L,i,s,t,e,n,e,r);\r
+    static const XMLCh _MetadataProvider[] =    UNICODE_LITERAL_16(M,e,t,a,d,a,t,a,P,r,o,v,i,d,e,r);\r
+    static const XMLCh OutOfProcess[] =         UNICODE_LITERAL_12(O,u,t,O,f,P,r,o,c,e,s,s);\r
+    static const XMLCh _path[] =                UNICODE_LITERAL_4(p,a,t,h);\r
     static const XMLCh Policy[] =               UNICODE_LITERAL_6(P,o,l,i,c,y);\r
     static const XMLCh RelyingParty[] =         UNICODE_LITERAL_12(R,e,l,y,i,n,g,P,a,r,t,y);\r
     static const XMLCh _ReplayCache[] =         UNICODE_LITERAL_11(R,e,p,l,a,y,C,a,c,h,e);\r
@@ -300,13 +335,10 @@ namespace {
     static const XMLCh _SessionCache[] =        UNICODE_LITERAL_12(S,e,s,s,i,o,n,C,a,c,h,e);\r
     static const XMLCh SessionInitiator[] =     UNICODE_LITERAL_16(S,e,s,s,i,o,n,I,n,i,t,i,a,t,o,r);\r
     static const XMLCh _StorageService[] =      UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);\r
-    static const XMLCh OutOfProcess[] =         UNICODE_LITERAL_12(O,u,t,O,f,P,r,o,c,e,s,s);\r
     static const XMLCh TCPListener[] =          UNICODE_LITERAL_11(T,C,P,L,i,s,t,e,n,e,r);\r
     static const XMLCh _TrustEngine[] =         UNICODE_LITERAL_11(T,r,u,s,t,E,n,g,i,n,e);\r
-    static const XMLCh UnixListener[] =         UNICODE_LITERAL_12(U,n,i,x,L,i,s,t,e,n,e,r);\r
-    static const XMLCh _MetadataProvider[] =    UNICODE_LITERAL_16(M,e,t,a,d,a,t,a,P,r,o,v,i,d,e,r);\r
-    static const XMLCh _path[] =                UNICODE_LITERAL_4(p,a,t,h);\r
     static const XMLCh _type[] =                UNICODE_LITERAL_4(t,y,p,e);\r
+    static const XMLCh UnixListener[] =         UNICODE_LITERAL_12(U,n,i,x,L,i,s,t,e,n,e,r);\r
 \r
     class SHIBSP_DLLLOCAL PolicyNodeFilter : public DOMNodeFilter\r
     {\r
@@ -326,11 +358,127 @@ namespace shibsp {
     }\r
 };\r
 \r
+void TokenValidator::validate(const XMLObject* xmlObject) const\r
+{\r
+#ifdef _DEBUG\r
+    xmltooling::NDC ndc("validate");\r
+#endif\r
+    Category& log=Category::getInstance(SHIBSP_LOGCAT".Application");\r
+\r
+    const opensaml::RootObject* root = NULL;\r
+    const opensaml::saml2::Assertion* token2 = dynamic_cast<const opensaml::saml2::Assertion*>(xmlObject);\r
+    if (token2) {\r
+        const opensaml::saml2::Conditions* conds = token2->getConditions();\r
+        // First verify the time conditions, using the specified timestamp, if non-zero.\r
+        if (m_ts>0 && conds) {\r
+            unsigned int skew = XMLToolingConfig::getConfig().clock_skew_secs;\r
+            time_t t=conds->getNotBeforeEpoch();\r
+            if (m_ts+skew < t)\r
+                throw ValidationException("Assertion is not yet valid.");\r
+            t=conds->getNotOnOrAfterEpoch();\r
+            if (t <= m_ts-skew)\r
+                throw ValidationException("Assertion is no longer valid.");\r
+        }\r
+\r
+        // Now we process conditions. Only audience restrictions at the moment.\r
+        const vector<opensaml::saml2::Condition*>& convec = conds->getConditions();\r
+        for (vector<opensaml::saml2::Condition*>::const_iterator c = convec.begin(); c!=convec.end(); ++c) {\r
+            const opensaml::saml2::AudienceRestriction* ac=dynamic_cast<const opensaml::saml2::AudienceRestriction*>(*c);\r
+            if (!ac) {\r
+                log.error("unrecognized Condition in assertion (%s)",\r
+                    (*c)->getSchemaType() ? (*c)->getSchemaType()->toString().c_str() : (*c)->getElementQName().toString().c_str());\r
+                throw ValidationException("Assertion contains an unrecognized condition.");\r
+            }\r
+\r
+            bool found = false;\r
+            const vector<opensaml::saml2::Audience*>& auds1 = ac->getAudiences();\r
+            const vector<const XMLCh*>& auds2 = m_app.getAudiences();\r
+            for (vector<opensaml::saml2::Audience*>::const_iterator a = auds1.begin(); !found && a!=auds1.end(); ++a) {\r
+                for (vector<const XMLCh*>::const_iterator a2 = auds2.begin(); !found && a2!=auds2.end(); ++a2) {\r
+                    found = XMLString::equals((*a)->getAudienceURI(), *a2);\r
+                }\r
+            }\r
+\r
+            if (!found) {\r
+                ostringstream os;\r
+                os << *ac;\r
+                log.error("unacceptable AudienceRestriction in assertion (%s)", os.str().c_str());\r
+                throw ValidationException("Assertion contains an unacceptable AudienceRestriction.");\r
+            }\r
+        }\r
+\r
+        root = token2;\r
+    }\r
+    else {\r
+        const opensaml::saml1::Assertion* token1 = dynamic_cast<const opensaml::saml1::Assertion*>(xmlObject);\r
+        if (token1) {\r
+            const opensaml::saml1::Conditions* conds = token1->getConditions();\r
+            // First verify the time conditions, using the specified timestamp, if non-zero.\r
+            if (m_ts>0 && conds) {\r
+                unsigned int skew = XMLToolingConfig::getConfig().clock_skew_secs;\r
+                time_t t=conds->getNotBeforeEpoch();\r
+                if (m_ts+skew < t)\r
+                    throw ValidationException("Assertion is not yet valid.");\r
+                t=conds->getNotOnOrAfterEpoch();\r
+                if (t <= m_ts-skew)\r
+                    throw ValidationException("Assertion is no longer valid.");\r
+            }\r
+\r
+            // Now we process conditions. Only audience restrictions at the moment.\r
+            const vector<opensaml::saml1::Condition*>& convec = conds->getConditions();\r
+            for (vector<opensaml::saml1::Condition*>::const_iterator c = convec.begin(); c!=convec.end(); ++c) {\r
+                const opensaml::saml1::AudienceRestrictionCondition* ac=dynamic_cast<const opensaml::saml1::AudienceRestrictionCondition*>(*c);\r
+                if (!ac) {\r
+                    log.error("unrecognized Condition in assertion (%s)",\r
+                        (*c)->getSchemaType() ? (*c)->getSchemaType()->toString().c_str() : (*c)->getElementQName().toString().c_str());\r
+                    throw ValidationException("Assertion contains an unrecognized condition.");\r
+                }\r
+\r
+                bool found = false;\r
+                const vector<opensaml::saml1::Audience*>& auds1 = ac->getAudiences();\r
+                const vector<const XMLCh*>& auds2 = m_app.getAudiences();\r
+                for (vector<opensaml::saml1::Audience*>::const_iterator a = auds1.begin(); !found && a!=auds1.end(); ++a) {\r
+                    for (vector<const XMLCh*>::const_iterator a2 = auds2.begin(); !found && a2!=auds2.end(); ++a2) {\r
+                        found = XMLString::equals((*a)->getAudienceURI(), *a2);\r
+                    }\r
+                }\r
+\r
+                if (!found) {\r
+                    ostringstream os;\r
+                    os << *ac;\r
+                    log.error("unacceptable AudienceRestrictionCondition in assertion (%s)", os.str().c_str());\r
+                    throw ValidationException("Assertion contains an unacceptable AudienceRestrictionCondition.");\r
+                }\r
+            }\r
+\r
+            root = token1;\r
+        }\r
+        else {\r
+            throw ValidationException("Unknown object type passed to token validator.");\r
+        }\r
+    }\r
+\r
+    if (!m_role || !m_app.getTrustEngine()) {\r
+        log.warn("no issuer role or TrustEngine provided, so no signature validation performed");\r
+        return;\r
+    }\r
+\r
+    const PropertySet* policy=m_app.getServiceProvider().getPolicySettings(m_app.getString("policyId").second);\r
+    pair<bool,bool> signedAssertions=policy ? policy->getBool("signedAssertions") : make_pair(false,false);\r
+\r
+    if (root->getSignature()) {\r
+        if (!m_app.getTrustEngine()->validate(*(root->getSignature()),*m_role))\r
+            throw ValidationException("Assertion signature did not validate.");\r
+    }\r
+    else if (signedAssertions.first && signedAssertions.second)\r
+        throw ValidationException("Assertion was unsigned, violating policy.");\r
+}\r
+\r
 XMLApplication::XMLApplication(\r
     const ServiceProvider* sp,\r
     const DOMElement* e,\r
     const XMLApplication* base\r
-    ) : m_sp(sp), m_base(base), m_metadata(NULL), m_trust(NULL),\r
+    ) : m_sp(sp), m_base(base), m_metadata(NULL), m_trust(NULL), m_attrResolver(NULL),\r
         m_credDefault(NULL), m_sessionInitDefault(NULL), m_acsDefault(NULL)\r
 {\r
 #ifdef _DEBUG\r
@@ -465,10 +613,6 @@ XMLApplication::XMLApplication(
         // Always include our own providerId as an audience.\r
         m_audiences.push_back(getXMLString("providerId").second);\r
 \r
-        if (conf.isEnabled(SPConfig::AttributeResolver)) {\r
-            // TODO\r
-        }\r
-\r
         if (conf.isEnabled(SPConfig::Metadata)) {\r
             child = XMLHelper::getFirstChildElement(e,_MetadataProvider);\r
             if (child) {\r
@@ -494,11 +638,25 @@ XMLApplication::XMLApplication(
                     m_trust = xmlConf.TrustEngineManager.newPlugin(type.get(),child);\r
                 }\r
                 catch (exception& ex) {\r
-                    log.crit("error building TrustEngine: %s",ex.what());\r
+                    log.crit("error building TrustEngine: %s", ex.what());\r
                 }\r
             }\r
         }\r
-        \r
+\r
+        if (conf.isEnabled(SPConfig::AttributeResolution)) {\r
+            child = XMLHelper::getFirstChildElement(e,_AttributeResolver);\r
+            if (child) {\r
+                auto_ptr_char type(child->getAttributeNS(NULL,_type));\r
+                log.info("building AttributeResolver of type %s...",type.get());\r
+                try {\r
+                    m_attrResolver = conf.AttributeResolverManager.newPlugin(type.get(),child);\r
+                }\r
+                catch (exception& ex) {\r
+                    log.crit("error building AttributeResolver: %s", ex.what());\r
+                }\r
+            }\r
+        }\r
+\r
         // Finally, load credential mappings.\r
         child = XMLHelper::getFirstChildElement(e,CredentialUse);\r
         if (child) {\r
@@ -541,6 +699,7 @@ void XMLApplication::cleanup()
     for_each(m_credMap.begin(),m_credMap.end(),cleanup_pair<const XMLCh*,PropertySet>());\r
 #endif\r
 \r
+    delete m_attrResolver;\r
     delete m_trust;\r
     delete m_metadata;\r
 }\r
@@ -560,7 +719,8 @@ short XMLApplication::acceptNode(const DOMNode* node) const
         XMLString::equals(name,CredentialUse) ||\r
         XMLString::equals(name,RelyingParty) ||\r
         XMLString::equals(name,_MetadataProvider) ||\r
-        XMLString::equals(name,_TrustEngine))\r
+        XMLString::equals(name,_TrustEngine) ||\r
+        XMLString::equals(name,_AttributeResolver))\r
         return FILTER_REJECT;\r
 \r
     return FILTER_ACCEPT;\r
@@ -614,21 +774,6 @@ const PropertySet* XMLApplication::getPropertySet(const char* name, const char*
     return m_base->getPropertySet(name,ns);\r
 }\r
 \r
-MetadataProvider* XMLApplication::getMetadataProvider() const\r
-{\r
-    return (!m_metadata && m_base) ? m_base->getMetadataProvider() : m_metadata;\r
-}\r
-\r
-TrustEngine* XMLApplication::getTrustEngine() const\r
-{\r
-    return (!m_trust && m_base) ? m_base->getTrustEngine() : m_trust;\r
-}\r
-\r
-const vector<const XMLCh*>& XMLApplication::getAudiences() const\r
-{\r
-    return (m_audiences.empty() && m_base) ? m_base->getAudiences() : m_audiences;\r
-}\r
-\r
 const PropertySet* XMLApplication::getCredentialUse(const EntityDescriptor* provider) const\r
 {\r
     if (!m_credDefault && m_base)\r
@@ -717,6 +862,7 @@ short XMLConfigImpl::acceptNode(const DOMNode* node) const
         return FILTER_ACCEPT;\r
     const XMLCh* name=node->getLocalName();\r
     if (XMLString::equals(name,Applications) ||\r
+        XMLString::equals(name,_ArtifactMap) ||\r
         XMLString::equals(name,Credentials) ||\r
         XMLString::equals(name,Extensions::LOCAL_NAME) ||\r
         XMLString::equals(name,Implementation) ||\r
@@ -912,6 +1058,20 @@ XMLConfigImpl::XMLConfigImpl(const DOMElement* e, bool first, const XMLConfig* o
                         replaySS = m_outer->m_storage[inmemID];\r
                     }\r
                     xmlConf.setReplayCache(new ReplayCache(replaySS));\r
+                    \r
+                    // ArtifactMap\r
+                    child=XMLHelper::getFirstChildElement(SHAR,_ArtifactMap);\r
+                    if (child) {\r
+                        auto_ptr_char ssid(child->getAttributeNS(NULL,_StorageService));\r
+                        if (ssid.get() && *ssid.get() && m_outer->m_storage.count(ssid.get())) {\r
+                            log.info("building ArtifactMap on top of StorageService (%s)...", ssid.get());\r
+                            samlConf.setArtifactMap(new ArtifactMap(child, m_outer->m_storage[ssid.get()]));\r
+                        }\r
+                    }\r
+                    if (samlConf.getArtifactMap()==NULL) {\r
+                        log.info("building in-memory ArtifactMap...");\r
+                        samlConf.setArtifactMap(new ArtifactMap(child));\r
+                    }\r
                 }\r
                 else {\r
                     log.info("building in-process SessionCache of type %s...",REMOTED_SESSION_CACHE);\r