Add authnskew property for ForceAuthn enforcement.
[shibboleth/sp.git] / adfs / adfs.cpp
index 07ca996..8a37559 100644 (file)
 #include <xercesc/util/XMLUniDefs.hpp>
 
 #ifndef SHIBSP_LITE
-# include <shibsp/attribute/Attribute.h>
-# include <shibsp/attribute/filtering/AttributeFilter.h>
-# include <shibsp/attribute/filtering/BasicFilteringContext.h>
-# include <shibsp/attribute/resolver/AttributeExtractor.h>
 # include <shibsp/attribute/resolver/ResolutionContext.h>
 # include <saml/SAMLConfig.h>
 # include <saml/saml1/core/Assertions.h>
@@ -86,6 +82,12 @@ namespace {
         virtual ~ADFSDecoder() {}
         
         XMLObject* decode(string& relayState, const GenericRequest& genericRequest, SecurityPolicy& policy) const;
+
+    protected:
+        void extractMessageDetails(
+            const XMLObject& message, const GenericRequest& req, const XMLCh* protocol, SecurityPolicy& policy
+            ) const {
+        }
     };
 
     MessageDecoder* ADFSDecoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
@@ -151,8 +153,15 @@ namespace {
             {}
         virtual ~ADFSConsumer() {}
 
-    private:
 #ifndef SHIBSP_LITE
+        void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
+            AssertionConsumerService::generateMetadata(role, handlerURL);
+            role.addSupport(m_protocol.get());
+        }
+
+        auto_ptr_XMLCh m_protocol;
+
+    private:
         string implementProtocol(
             const Application& application,
             const HTTPRequest& httpRequest,
@@ -160,7 +169,6 @@ namespace {
             const PropertySet* settings,
             const XMLObject& xmlObject
             ) const;
-        auto_ptr_XMLCh m_protocol;
 #endif
     };
 
@@ -193,6 +201,12 @@ namespace {
         void receive(DDF& in, ostream& out);
         pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
 
+#ifndef SHIBSP_LITE
+        const char* getType() const {
+            return "LogoutInitiator";
+        }
+#endif
+
     private:
         pair<bool,long> doRequest(
             const Application& application, const char* requestURL, const char* entityID, HTTPResponse& httpResponse
@@ -218,6 +232,26 @@ namespace {
 
         pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
 
+#ifndef SHIBSP_LITE
+        void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
+            m_login.generateMetadata(role, handlerURL);
+            const char* loc = getString("Location").second;
+            string hurl(handlerURL);
+            if (*loc != '/')
+                hurl += '/';
+            hurl += loc;
+            auto_ptr_XMLCh widen(hurl.c_str());
+            SingleLogoutService* ep = SingleLogoutServiceBuilder::buildSingleLogoutService();
+            ep->setLocation(widen.get());
+            ep->setBinding(m_login.m_protocol.get());
+            role.getSingleLogoutServices().push_back(ep);
+        }
+
+        const char* getType() const {
+            return m_login.getType();
+        }
+#endif
+
     private:
         ADFSConsumer m_login;
     };
@@ -278,7 +312,7 @@ pair<bool,long> ADFSSessionInitiator::run(SPRequest& request, const char* entity
 {
     // We have to know the IdP to function.
     if (!entityID || !*entityID)
-        return make_pair(false,0);
+        return make_pair(false,0L);
 
     string target;
     const Handler* ACS=NULL;
@@ -301,29 +335,27 @@ pair<bool,long> ADFSSessionInitiator::run(SPRequest& request, const char* entity
     }
 
     // Since we're not passing by index, we need to fully compute the return URL.
-    if (!ACS) {
-        // Get all the ADFS endpoints.
-        const vector<const Handler*>& handlers = app.getAssertionConsumerServicesByBinding(m_binding.get());
-
-        // Index comes from request, or default set in the handler, or we just pick the first endpoint.
-        pair<bool,unsigned int> index = make_pair(false,0);
-        if (isHandler) {
-            option = request.getParameter("acsIndex");
-            if (option)
-                index = make_pair(true, atoi(option));
-        }
-        if (!index.first)
-            index = getUnsignedInt("defaultACSIndex");
-        if (index.first) {
-            for (vector<const Handler*>::const_iterator h = handlers.begin(); !ACS && h!=handlers.end(); ++h) {
-                if (index.second == (*h)->getUnsignedInt("index").second)
-                    ACS = *h;
-            }
-        }
-        else if (!handlers.empty()) {
-            ACS = handlers.front();
+    // Get all the ADFS endpoints.
+    const vector<const Handler*>& handlers = app.getAssertionConsumerServicesByBinding(m_binding.get());
+
+    // Index comes from request, or default set in the handler, or we just pick the first endpoint.
+    pair<bool,unsigned int> index(false,0);
+    if (isHandler) {
+        option = request.getParameter("acsIndex");
+        if (option)
+            index = pair<bool,unsigned int>(true, atoi(option));
+    }
+    if (!index.first)
+        index = getUnsignedInt("defaultACSIndex");
+    if (index.first) {
+        for (vector<const Handler*>::const_iterator h = handlers.begin(); !ACS && h!=handlers.end(); ++h) {
+            if (index.second == (*h)->getUnsignedInt("index").second)
+                ACS = *h;
         }
     }
+    else if (!handlers.empty()) {
+        ACS = handlers.front();
+    }
     if (!ACS)
         throw ConfigurationException("Unable to locate ADFS response endpoint.");
 
@@ -403,21 +435,22 @@ pair<bool,long> ADFSSessionInitiator::doRequest(
     // Use metadata to invoke the SSO service directly.
     MetadataProvider* m=app.getMetadataProvider();
     Locker locker(m);
-    const EntityDescriptor* entity=m->getEntityDescriptor(entityID);
-    if (!entity) {
+    MetadataProvider::Criteria mc(entityID, &IDPSSODescriptor::ELEMENT_QNAME, m_binding.get());
+    pair<const EntityDescriptor*,const RoleDescriptor*> entity=m->getEntityDescriptor(mc);
+    if (!entity.first) {
         m_log.error("unable to locate metadata for provider (%s)", entityID);
-        throw MetadataException("Unable to locate metadata for identity provider ($entityID)",
-            namedparams(1, "entityID", entityID));
+        throw MetadataException("Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", entityID));
     }
-    const IDPSSODescriptor* role=entity->getIDPSSODescriptor(m_binding.get());
-    if (!role) {
+    else if (!entity.second) {
         m_log.error("unable to locate ADFS-aware identity provider role for provider (%s)", entityID);
-        return make_pair(false,0);
+        return make_pair(false,0L);
     }
-    const EndpointType* ep=EndpointManager<SingleSignOnService>(role->getSingleSignOnServices()).getByBinding(m_binding.get());
+    const EndpointType* ep = EndpointManager<SingleSignOnService>(
+        dynamic_cast<const IDPSSODescriptor*>(entity.second)->getSingleSignOnServices()
+        ).getByBinding(m_binding.get());
     if (!ep) {
         m_log.error("unable to locate compatible SSO service for provider (%s)", entityID);
-        return make_pair(false,0);
+        return make_pair(false,0L);
     }
 
     preserveRelayState(app, httpResponse, relayState);
@@ -443,7 +476,7 @@ pair<bool,long> ADFSSessionInitiator::doRequest(
 
     return make_pair(true, httpResponse.sendRedirect(req.c_str()));
 #else
-    return make_pair(false,0);
+    return make_pair(false,0L);
 #endif
 }
 
@@ -518,12 +551,15 @@ string ADFSConsumer::implementProtocol(
     if (!token || !token->getSignature())
         throw FatalProfileException("Incoming message did not contain a signed SAML 1.1 assertion.");
 
-    // Run the policy over the assertion. Handles issuer consistency, replay, freshness,
-    // and signature verification, assuming the relevant rules are configured.
-    policy.evaluate(*token, NULL, m_protocol.get());
+    // Extract message and issuer details from assertion.
+    extractMessageDetails(*token, m_protocol.get(), policy);
+
+    // Run the policy over the assertion. Handles replay, freshness, and
+    // signature verification, assuming the relevant rules are configured.
+    policy.evaluate(*token);
     
     // If no security is in place now, we kick it.
-    if (!policy.isSecure())
+    if (!policy.isAuthenticated())
         throw SecurityPolicyException("Unable to establish security of incoming assertion.");
 
     // Now do profile and core semantic validation to ensure we can use it for SSO.
@@ -535,11 +571,20 @@ string ADFSConsumer::implementProtocol(
         throw FatalProfileException("Assertion did not contain time conditions.");
     else if (token->getAuthenticationStatements().empty())
         throw FatalProfileException("Assertion did not contain an authentication statement.");
+    
 
     // With ADFS, we only have one token, but we need to put it in a vector.
     vector<const Assertion*> tokens(1,token);
     const saml1::AuthenticationStatement* ssoStatement=token->getAuthenticationStatements().front();
 
+    // authnskew allows rejection of SSO if AuthnInstant is too old.
+    const PropertySet* sessionProps = application.getPropertySet("Sessions");
+    pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("authnskew") : pair<bool,unsigned int>(false,0);
+
+    if (authnskew.first && authnskew.second &&
+            ssoStatement->getAuthenticationInstant() && (now - ssoStatement->getAuthenticationInstantEpoch() > authnskew.second))
+        throw FatalProfileException("The gap between now and the time you logged into your identity provider exceeds the limit.");
+
     // Address checking.
     saml1::SubjectLocality* locality = ssoStatement->getSubjectLocality();
     if (locality && locality->getIPAddress()) {
@@ -554,48 +599,12 @@ string ADFSConsumer::implementProtocol(
     // Now we have to extract the authentication details for attribute and session setup.
 
     // Session expiration for ADFS is purely SP-driven, and the method is mapped to a ctx class.
-    const PropertySet* sessionProps = application.getPropertySet("Sessions");
     pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
     if (!lifetime.first || lifetime.second == 0)
         lifetime.second = 28800;
 
     // We've successfully "accepted" the SSO token.
     // To complete processing, we need to extract and resolve attributes and then create the session.
-    vector<Attribute*> resolvedAttributes;
-    AttributeExtractor* extractor = application.getAttributeExtractor();
-    if (extractor) {
-        m_log.debug("extracting pushed attributes...");
-        Locker extlocker(extractor);
-        if (n) {
-            try {
-                extractor->extractAttributes(application, policy.getIssuerMetadata(), *n, resolvedAttributes);
-            }
-            catch (exception& ex) {
-                m_log.error("caught exception extracting attributes: %s", ex.what());
-            }
-        }
-        try {
-            extractor->extractAttributes(application, policy.getIssuerMetadata(), *token, resolvedAttributes);
-        }
-        catch (exception& ex) {
-            m_log.error("caught exception extracting attributes: %s", ex.what());
-        }
-
-        AttributeFilter* filter = application.getAttributeFilter();
-        if (filter && !resolvedAttributes.empty()) {
-            BasicFilteringContext fc(application, resolvedAttributes, policy.getIssuerMetadata(), ssoStatement->getAuthenticationMethod());
-            Locker filtlocker(filter);
-            try {
-                filter->filterAttributes(fc, resolvedAttributes);
-            }
-            catch (exception& ex) {
-                m_log.error("caught exception filtering attributes: %s", ex.what());
-                m_log.error("dumping extracted attributes due to filtering exception");
-                for_each(resolvedAttributes.begin(), resolvedAttributes.end(), xmltooling::cleanup<shibsp::Attribute>());
-                resolvedAttributes.clear();
-            }
-        }
-    }
 
     // Normalize the SAML 1.x NameIdentifier...
     auto_ptr<saml2::NameID> nameid(n ? saml2::NameIDBuilder::buildNameID() : NULL);
@@ -605,52 +614,39 @@ string ADFSConsumer::implementProtocol(
         nameid->setNameQualifier(n->getNameQualifier());
     }
 
-    const EntityDescriptor* issuerMetadata =
-        policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL;
-    auto_ptr<ResolutionContext> ctx(
+    // The context will handle deleting attributes and new tokens.
+        auto_ptr<ResolutionContext> ctx(
         resolveAttributes(
             application,
-            issuerMetadata,
+            policy.getIssuerMetadata(),
             m_protocol.get(),
+            n,
             nameid.get(),
             ssoStatement->getAuthenticationMethod(),
             NULL,
-            &tokens,
-            &resolvedAttributes
+            &tokens
             )
         );
 
     if (ctx.get()) {
         // Copy over any new tokens, but leave them in the context for cleanup.
         tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
-
-        // Copy over new attributes, and transfer ownership.
-        resolvedAttributes.insert(resolvedAttributes.end(), ctx->getResolvedAttributes().begin(), ctx->getResolvedAttributes().end());
-        ctx->getResolvedAttributes().clear();
     }
 
-    try {
-        string key = application.getServiceProvider().getSessionCache()->insert(
-            now + lifetime.second,
-            application,
-            httpRequest.getRemoteAddr().c_str(),
-            issuerMetadata,
-            m_protocol.get(),
-            nameid.get(),
-            ssoStatement->getAuthenticationInstant() ? ssoStatement->getAuthenticationInstant()->getRawData() : NULL,
-            NULL,
-            ssoStatement->getAuthenticationMethod(),
-            NULL,
-            &tokens,
-            &resolvedAttributes
-            );
-        for_each(resolvedAttributes.begin(), resolvedAttributes.end(), xmltooling::cleanup<shibsp::Attribute>());
-        return key;
-    }
-    catch (exception&) {
-        for_each(resolvedAttributes.begin(), resolvedAttributes.end(), xmltooling::cleanup<shibsp::Attribute>());
-        throw;
-    }
+    return application.getServiceProvider().getSessionCache()->insert(
+        now + lifetime.second,
+        application,
+        httpRequest.getRemoteAddr().c_str(),
+        policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL,
+        m_protocol.get(),
+        nameid.get(),
+        ssoStatement->getAuthenticationInstant() ? ssoStatement->getAuthenticationInstant()->getRawData() : NULL,
+        NULL,
+        ssoStatement->getAuthenticationMethod(),
+        NULL,
+        &tokens,
+        ctx.get() ? &ctx->getResolvedAttributes() : NULL
+        );
 }
 
 #endif
@@ -667,17 +663,17 @@ pair<bool,long> ADFSLogoutInitiator::run(SPRequest& request, bool isHandler) con
     try {
         session = request.getSession(false, true, false);  // don't cache it and ignore all checks
         if (!session)
-            return make_pair(false,0);
+            return make_pair(false,0L);
 
         // We only handle ADFS sessions.
         if (!XMLString::equals(session->getProtocol(), WSFED_NS) || !session->getEntityID()) {
             session->unlock();
-            return make_pair(false,0);
+            return make_pair(false,0L);
         }
     }
     catch (exception& ex) {
         m_log.error("error accessing current session: %s", ex.what());
-        return make_pair(false,0);
+        return make_pair(false,0L);
     }
 
     string entityID(session->getEntityID());
@@ -689,7 +685,7 @@ pair<bool,long> ADFSLogoutInitiator::run(SPRequest& request, bool isHandler) con
     }
     else {
         // When not out of process, we remote the request.
-        Locker locker(session);
+        Locker locker(session, false);
         DDF out,in(m_address.c_str());
         DDFJanitor jin(in), jout(out);
         in.addmember("application_id").string(request.getApplication().getId());
@@ -738,23 +734,18 @@ pair<bool,long> ADFSLogoutInitiator::doRequest(
             throw ConfigurationException("Missing entityID parameter.");
 
         // With a session in hand, we can create a request message, if we can find a compatible endpoint.
-        Locker metadataLocker(application.getMetadataProvider());
-        const EntityDescriptor* entity = application.getMetadataProvider()->getEntityDescriptor(entityID);
-        if (!entity) {
-            throw MetadataException(
-                "Unable to locate metadata for identity provider ($entityID)",
-                namedparams(1, "entityID", entityID)
-                );
-        }
-        const IDPSSODescriptor* role = entity->getIDPSSODescriptor(m_binding.get());
-        if (!role) {
-            throw MetadataException(
-                "Unable to locate ADFS IdP role for identity provider ($entityID).",
-                namedparams(1, "entityID", entityID)
-                );
-        }
-
-        const EndpointType* ep = EndpointManager<SingleLogoutService>(role->getSingleLogoutServices()).getByBinding(m_binding.get());
+        MetadataProvider* m=application.getMetadataProvider();
+        Locker locker(m);
+        MetadataProvider::Criteria mc(entityID, &IDPSSODescriptor::ELEMENT_QNAME, m_binding.get());
+        pair<const EntityDescriptor*,const RoleDescriptor*> entity=m->getEntityDescriptor(mc);
+        if (!entity.first)
+            throw MetadataException("Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", entityID));
+        else if (!entity.second)
+            throw MetadataException("Unable to locate ADFS IdP role for identity provider ($entityID).", namedparams(1, "entityID", entityID));
+
+        const EndpointType* ep = EndpointManager<SingleLogoutService>(
+            dynamic_cast<const IDPSSODescriptor*>(entity.second)->getSingleLogoutServices()
+            ).getByBinding(m_binding.get());
         if (!ep) {
             throw MetadataException(
                 "Unable to locate ADFS single logout service for identity provider ($entityID).",
@@ -771,7 +762,7 @@ pair<bool,long> ADFSLogoutInitiator::doRequest(
         m_log.error("error issuing ADFS logout request: %s", ex.what());
     }
 
-    return make_pair(false,0);
+    return make_pair(false,0L);
 #else
     throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
 #endif