Change audience handling and validators to separate out entityID.
[shibboleth/sp.git] / adfs / adfs.cpp
index 6403441..b2be93b 100644 (file)
@@ -162,9 +162,10 @@ namespace {
         auto_ptr_XMLCh m_protocol;
 
     private:
-        string implementProtocol(
+        void implementProtocol(
             const Application& application,
             const HTTPRequest& httpRequest,
+            HTTPResponse& httpResponse,
             SecurityPolicy& policy,
             const PropertySet* settings,
             const XMLObject& xmlObject
@@ -201,10 +202,14 @@ 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
-            ) const;
+        pair<bool,long> doRequest(const Application& application, const char* entityID, HTTPResponse& httpResponse) const;
 
         string m_appId;
         auto_ptr_XMLCh m_binding;
@@ -240,6 +245,10 @@ namespace {
             ep->setBinding(m_login.m_protocol.get());
             role.getSingleLogoutServices().push_back(ep);
         }
+
+        const char* getType() const {
+            return m_login.getType();
+        }
 #endif
 
     private:
@@ -302,7 +311,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;
@@ -316,7 +325,7 @@ pair<bool,long> ADFSSessionInitiator::run(SPRequest& request, const char* entity
 
         // Since we're passing the ACS by value, we need to compute the return URL,
         // so we'll need the target resource for real.
-        recoverRelayState(request.getApplication(), request, target, false);
+        recoverRelayState(request.getApplication(), request, request, target, false);
     }
     else {
         // We're running as a "virtual handler" from within the filter.
@@ -325,29 +334,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.");
 
@@ -427,21 +434,26 @@ 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) {
-        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));
+    MetadataProvider::Criteria mc(entityID, &IDPSSODescriptor::ELEMENT_QNAME, m_binding.get());
+    pair<const EntityDescriptor*,const RoleDescriptor*> entity=m->getEntityDescriptor(mc);
+    if (!entity.first) {
+        m_log.warn("unable to locate metadata for provider (%s)", 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) {
-        m_log.error("unable to locate ADFS-aware identity provider role for provider (%s)", entityID);
-        return make_pair(false,0);
+    else if (!entity.second) {
+        m_log.warn("unable to locate ADFS-aware identity provider role for provider (%s)", entityID);
+        if (getParent())
+            return make_pair(false,0L);
+        throw MetadataException("Unable to locate ADFS-aware identity provider role for provider ($entityID)", namedparams(1, "entityID", entityID));
     }
-    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);
+        m_log.warn("unable to locate compatible SSO service for provider (%s)", entityID);
+        if (getParent())
+            return make_pair(false,0L);
+        throw MetadataException("Unable to locate compatible SSO service for provider ($entityID)", namedparams(1, "entityID", entityID));
     }
 
     preserveRelayState(app, httpResponse, relayState);
@@ -467,7 +479,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
 }
 
@@ -519,9 +531,10 @@ XMLObject* ADFSDecoder::decode(string& relayState, const GenericRequest& generic
     return xmlObject.release();
 }
 
-string ADFSConsumer::implementProtocol(
+void ADFSConsumer::implementProtocol(
     const Application& application,
     const HTTPRequest& httpRequest,
+    HTTPResponse& httpResponse,
     SecurityPolicy& policy,
     const PropertySet* settings,
     const XMLObject& xmlObject
@@ -553,20 +566,31 @@ string ADFSConsumer::implementProtocol(
     if (!policy.isAuthenticated())
         throw SecurityPolicyException("Unable to establish security of incoming assertion.");
 
+    const EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL;
+
     // Now do profile and core semantic validation to ensure we can use it for SSO.
     // Profile validator.
     time_t now = time(NULL);
-    saml1::AssertionValidator ssoValidator(application.getAudiences(), now);
+    saml1::AssertionValidator ssoValidator(application.getRelyingParty(entity)->getXMLString("entityID").second, application.getAudiences(), now);
     ssoValidator.validateAssertion(*token);
     if (!token->getConditions() || !token->getConditions()->getNotBefore() || !token->getConditions()->getNotOnOrAfter())
         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("maxTimeSinceAuthn") : 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()) {
@@ -581,7 +605,6 @@ 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;
@@ -598,7 +621,7 @@ string ADFSConsumer::implementProtocol(
     }
 
     // The context will handle deleting attributes and new tokens.
-        auto_ptr<ResolutionContext> ctx(
+    auto_ptr<ResolutionContext> ctx(
         resolveAttributes(
             application,
             policy.getIssuerMetadata(),
@@ -616,11 +639,12 @@ string ADFSConsumer::implementProtocol(
         tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
     }
 
-    return application.getServiceProvider().getSessionCache()->insert(
-        now + lifetime.second,
+    application.getServiceProvider().getSessionCache()->insert(
         application,
-        httpRequest.getRemoteAddr().c_str(),
-        policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL,
+        httpRequest,
+        httpResponse,
+        now + lifetime.second,
+        entity,
         m_protocol.get(),
         nameid.get(),
         ssoStatement->getAuthenticationInstant() ? ssoStatement->getAuthenticationInstant()->getRawData() : NULL,
@@ -646,17 +670,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());
@@ -664,7 +688,7 @@ pair<bool,long> ADFSLogoutInitiator::run(SPRequest& request, bool isHandler) con
 
     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
         // When out of process, we run natively.
-        return doRequest(request.getApplication(), request.getRequestURL(), entityID.c_str(), request);
+        return doRequest(request.getApplication(), entityID.c_str(), request);
     }
     else {
         // When not out of process, we remote the request.
@@ -672,7 +696,6 @@ pair<bool,long> ADFSLogoutInitiator::run(SPRequest& request, bool isHandler) con
         DDF out,in(m_address.c_str());
         DDFJanitor jin(in), jout(out);
         in.addmember("application_id").string(request.getApplication().getId());
-        in.addmember("url").string(request.getRequestURL());
         in.addmember("entity_id").string(entityID.c_str());
         out=request.getServiceProvider().getListenerService()->send(in);
         return unwrap(request, out);
@@ -699,7 +722,7 @@ void ADFSLogoutInitiator::receive(DDF& in, ostream& out)
     // Since we're remoted, the result should either be a throw, which we pass on,
     // a false/0 return, which we just return as an empty structure, or a response/redirect,
     // which we capture in the facade and send back.
-    doRequest(*app, in["url"].string(), in["entity_id"].string(), *resp.get());
+    doRequest(*app, in["entity_id"].string(), *resp.get());
 
     out << ret;
 #else
@@ -707,9 +730,7 @@ void ADFSLogoutInitiator::receive(DDF& in, ostream& out)
 #endif
 }
 
-pair<bool,long> ADFSLogoutInitiator::doRequest(
-    const Application& application, const char* requestURL, const char* entityID, HTTPResponse& response
-    ) const
+pair<bool,long> ADFSLogoutInitiator::doRequest(const Application& application, const char* entityID, HTTPResponse& response) const
 {
 #ifndef SHIBSP_LITE
     try {
@@ -717,23 +738,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).",
@@ -750,7 +766,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
@@ -781,10 +797,6 @@ pair<bool,long> ADFSLogout::run(SPRequest& request, bool isHandler) const
     param = request.getParameter("wreply");
     const Application& app = request.getApplication();
 
-    // Get the session_id.
-    pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_");
-    const char* session_id = request.getCookie(shib_cookie.first.c_str());
-
     if (!returning) {
         // Pass control to the first front channel notification point, if any.
         map<string,string> parammap;
@@ -796,19 +808,19 @@ pair<bool,long> ADFSLogout::run(SPRequest& request, bool isHandler) const
     }
 
     // Best effort on back channel and to remove the user agent's session.
-    if (session_id) {
+    string session_id = app.getServiceProvider().getSessionCache()->active(app, request);
+    if (!session_id.empty()) {
         vector<string> sessions(1,session_id);
         notifyBackChannel(app, request.getRequestURL(), sessions, false);
         try {
-            app.getServiceProvider().getSessionCache()->remove(session_id, app);
+            app.getServiceProvider().getSessionCache()->remove(app, request, &request);
         }
         catch (exception& ex) {
-            m_log.error("error removing session (%s): %s", session_id, ex.what());
+            m_log.error("error removing session (%s): %s", session_id.c_str(), ex.what());
         }
-        request.setCookie(shib_cookie.first.c_str(), shib_cookie.second);
     }
 
     if (param)
         return make_pair(true, request.sendRedirect(param));
-    return sendLogoutPage(app, request, false, "Logout complete.");
+    return sendLogoutPage(app, request, request, false, "Logout complete.");
 }