Factor out LogoutInitiator class, simpler API to get ACS by binding.
[shibboleth/sp.git] / adfs / adfs.cpp
index ecafa3d..c8f4bdd 100644 (file)
@@ -1,6 +1,6 @@
 /*
- *  Copyright 2001-2005 Internet2
- * 
+ *  Copyright 2001-2010 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
@@ -17,7 +17,7 @@
 /**
  * adfs.cpp
  *
- * ADFSv1 extension library
+ * ADFSv1 extension library.
  */
 
 #if defined (_MSC_VER) || defined(__BORLANDC__)
 # define ADFS_EXPORTS
 #endif
 
-#include <memory>
-
 #include <shibsp/base.h>
 #include <shibsp/exceptions.h>
 #include <shibsp/Application.h>
 #include <shibsp/ServiceProvider.h>
 #include <shibsp/SessionCache.h>
 #include <shibsp/SPConfig.h>
+#include <shibsp/SPRequest.h>
 #include <shibsp/handler/AssertionConsumerService.h>
-#include <shibsp/handler/LogoutHandler.h>
+#include <shibsp/handler/LogoutInitiator.h>
 #include <shibsp/handler/SessionInitiator.h>
 #include <xmltooling/logging.h>
+#include <xmltooling/util/DateTime.h>
 #include <xmltooling/util/NDC.h>
 #include <xmltooling/util/URLEncoder.h>
 #include <xmltooling/util/XMLHelper.h>
-#include <xercesc/util/XMLUniDefs.hpp>
+#include <memory>
 
 #ifndef SHIBSP_LITE
 # include <shibsp/attribute/resolver/ResolutionContext.h>
+# include <shibsp/metadata/MetadataProviderCriteria.h>
 # include <saml/SAMLConfig.h>
+# include <saml/exceptions.h>
+# include <saml/binding/SecurityPolicy.h>
 # include <saml/saml1/core/Assertions.h>
-# include <saml/saml1/profile/AssertionValidator.h>
 # include <saml/saml2/core/Assertions.h>
 # include <saml/saml2/metadata/Metadata.h>
 # include <saml/saml2/metadata/EndpointManager.h>
-# include <saml/saml2/profile/AssertionValidator.h>
+# include <xmltooling/XMLToolingConfig.h>
 # include <xmltooling/impl/AnyElement.h>
+# include <xmltooling/util/ParserPool.h>
 # include <xmltooling/validation/ValidatorSuite.h>
 using namespace opensaml::saml2md;
 # ifndef min
@@ -86,7 +89,11 @@ namespace {
     public:
         ADFSDecoder() : m_ns(WSTRUST_NS) {}
         virtual ~ADFSDecoder() {}
-        
+
+        const XMLCh* getProtocolFamily() const {
+            return m_ns.get();
+        }
+
         XMLObject* decode(string& relayState, const GenericRequest& genericRequest, SecurityPolicy& policy) const;
 
     protected:
@@ -111,7 +118,7 @@ namespace {
     {
     public:
         ADFSSessionInitiator(const DOMElement* e, const char* appId)
-                : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator.ADFS")), m_appId(appId), m_binding(WSFED_NS) {
+            : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator.ADFS"), nullptr, &m_remapper), m_appId(appId), m_binding(WSFED_NS) {
             // If Location isn't set, defer address registration until the setParent call.
             pair<bool,const char*> loc = getString("Location");
             if (loc.first) {
@@ -120,7 +127,7 @@ namespace {
             }
         }
         virtual ~ADFSSessionInitiator() {}
-        
+
         void setParent(const PropertySet* parent) {
             DOMPropertySet::setParent(parent);
             pair<bool,const char*> loc = getString("Location");
@@ -134,11 +141,17 @@ namespace {
         }
 
         void receive(DDF& in, ostream& out);
+        pair<bool,long> unwrap(SPRequest& request, DDF& out) const;
         pair<bool,long> run(SPRequest& request, string& entityID, bool isHandler=true) const;
 
+        const XMLCh* getProtocolFamily() const {
+            return m_binding.get();
+        }
+
     private:
         pair<bool,long> doRequest(
             const Application& application,
+            const HTTPRequest* httpRequest,
             HTTPResponse& httpResponse,
             const char* entityID,
             const char* acsLocation,
@@ -151,13 +164,10 @@ namespace {
 
     class SHIBSP_DLLLOCAL ADFSConsumer : public shibsp::AssertionConsumerService
     {
+        auto_ptr_XMLCh m_protocol;
     public:
         ADFSConsumer(const DOMElement* e, const char* appId)
-            : shibsp::AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SSO.ADFS"))
-#ifndef SHIBSP_LITE
-                ,m_protocol(WSFED_NS)
-#endif
-            {}
+            : shibsp::AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SSO.ADFS")), m_protocol(WSFED_NS) {}
         virtual ~ADFSConsumer() {}
 
 #ifndef SHIBSP_LITE
@@ -166,21 +176,23 @@ namespace {
             role.addSupport(m_protocol.get());
         }
 
-        auto_ptr_XMLCh m_protocol;
-
     private:
         void implementProtocol(
             const Application& application,
             const HTTPRequest& httpRequest,
             HTTPResponse& httpResponse,
             SecurityPolicy& policy,
-            const PropertySet* settings,
+            const PropertySet*,
             const XMLObject& xmlObject
             ) const;
+#else
+        const XMLCh* getProtocolFamily() const {
+            return m_protocol.get();
+        }
 #endif
     };
 
-    class SHIBSP_DLLLOCAL ADFSLogoutInitiator : public AbstractHandler, public LogoutHandler
+    class SHIBSP_DLLLOCAL ADFSLogoutInitiator : public AbstractHandler, public LogoutInitiator
     {
     public:
         ADFSLogoutInitiator(const DOMElement* e, const char* appId)
@@ -193,7 +205,7 @@ namespace {
             }
         }
         virtual ~ADFSLogoutInitiator() {}
-        
+
         void setParent(const PropertySet* parent) {
             DOMPropertySet::setParent(parent);
             pair<bool,const char*> loc = getString("Location");
@@ -209,11 +221,9 @@ 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";
+        const XMLCh* getProtocolFamily() const {
+            return m_binding.get();
         }
-#endif
 
     private:
         pair<bool,long> doRequest(const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse, Session* session) const;
@@ -227,8 +237,8 @@ namespace {
     public:
         ADFSLogout(const DOMElement* e, const char* appId)
                 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".Logout.ADFS")), m_login(e, appId) {
-#ifndef SHIBSP_LITE
             m_initiator = false;
+#ifndef SHIBSP_LITE
             m_preserve.push_back("wreply");
             string address = string(appId) + getString("Location").second + "::run::ADFSLO";
             setAddress(address.c_str());
@@ -249,7 +259,7 @@ namespace {
             auto_ptr_XMLCh widen(hurl.c_str());
             SingleLogoutService* ep = SingleLogoutServiceBuilder::buildSingleLogoutService();
             ep->setLocation(widen.get());
-            ep->setBinding(m_login.m_protocol.get());
+            ep->setBinding(m_login.getProtocolFamily());
             role.getSingleLogoutServices().push_back(ep);
         }
 
@@ -257,6 +267,9 @@ namespace {
             return m_login.getType();
         }
 #endif
+        const XMLCh* getProtocolFamily() const {
+            return m_login.getProtocolFamily();
+        }
 
     private:
         ADFSConsumer m_login;
@@ -294,8 +307,8 @@ extern "C" int ADFS_EXPORTS xmltooling_extension_init(void*)
     conf.AssertionConsumerServiceManager.registerFactory(WSFED_NS, ADFSLogoutFactory);
 #ifndef SHIBSP_LITE
     SAMLConfig::getConfig().MessageDecoderManager.registerFactory(WSFED_NS, ADFSDecoderFactory);
-    XMLObjectBuilder::registerBuilder(QName(WSTRUST_NS,"RequestedSecurityToken"), new AnyElementBuilder());
-    XMLObjectBuilder::registerBuilder(QName(WSTRUST_NS,"RequestSecurityTokenResponse"), new AnyElementBuilder());
+    XMLObjectBuilder::registerBuilder(xmltooling::QName(WSTRUST_NS,"RequestedSecurityToken"), new AnyElementBuilder());
+    XMLObjectBuilder::registerBuilder(xmltooling::QName(WSTRUST_NS,"RequestSecurityTokenResponse"), new AnyElementBuilder());
 #endif
     return 0;
 }
@@ -317,83 +330,90 @@ extern "C" void ADFS_EXPORTS xmltooling_extension_term()
 pair<bool,long> ADFSSessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
 {
     // We have to know the IdP to function.
-    if (entityID.empty())
+    if (entityID.empty() || !checkCompatibility(request, isHandler))
         return make_pair(false,0L);
 
     string target;
-    const Handler* ACS=NULL;
-    const char* option;
+    pair<bool,const char*> prop;
     pair<bool,const char*> acClass;
+    const Handler* ACS=nullptr;
     const Application& app=request.getApplication();
 
     if (isHandler) {
-        option = request.getParameter("target");
-        if (option)
-            target = option;
+        prop.second = request.getParameter("acsIndex");
+        if (prop.second && *prop.second) {
+            ACS = app.getAssertionConsumerServiceByIndex(atoi(prop.second));
+            if (!ACS)
+                request.log(SPRequest::SPWarn, "invalid acsIndex specified in request, using acsIndex property");
+        }
+
+        prop = getString("target", request);
+        if (prop.first)
+            target = prop.second;
 
         // 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, request, target, false);
+        recoverRelayState(app, request, request, target, false);
 
-        if (acClass.second = request.getParameter("authnContextClassRef"))
-            acClass.first = true;
-        else
-            acClass = getString("authnContextClassRef");
+        acClass = getString("authnContextClassRef", request);
     }
     else {
-        // We're running as a "virtual handler" from within the filter.
-        // The target resource is the current one and everything else is defaulted.
-        target=request.getRequestURL();
+        // Check for a hardwired target value in the map or handler.
+        prop = getString("target", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
+        if (prop.first)
+            target = prop.second;
+        else
+            target = request.getRequestURL();
 
-        const PropertySet* settings = request.getRequestSettings().first;
-        acClass = settings->getString("authnContextClassRef");
-        if (!acClass.first)
-            acClass = getString("authnContextClassRef");
+        acClass = getString("authnContextClassRef", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
     }
 
-    // Since we're not passing by index, we need to fully compute the return URL.
-    // 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;
+    if (!ACS) {
+        pair<bool,unsigned int> index = getUnsignedInt("acsIndex", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
+        if (index.first) {
+            ACS = app.getAssertionConsumerServiceByIndex(index.second);
+            if (!ACS)
+                request.log(SPRequest::SPWarn, "invalid acsIndex property, using default ACS location");
+        }
+        if (!ACS) {
+            ACS = app.getAssertionConsumerServiceByBinding(WSFED_NS);
+            if (!ACS) {
+                m_log.error("unable to locate a compatible ACS");
+                throw ConfigurationException("Unable to locate an ADFS-compatible ACS in the configuration.");
+            }
         }
     }
-    else if (!handlers.empty()) {
-        ACS = handlers.front();
+
+    // Validate the ACS for use with this protocol.
+    if (!XMLString::equals(getProtocolFamily(), ACS->getProtocolFamily())) {
+        m_log.error("configured or requested ACS has non-ADFS binding");
+        throw ConfigurationException("Configured or requested ACS has non-ADFS binding ($1).", params(1, ACS->getString("Binding").second));
     }
-    if (!ACS)
-        throw ConfigurationException("Unable to locate ADFS response endpoint.");
 
+    // Since we're not passing by index, we need to fully compute the return URL.
     // Compute the ACS URL. We add the ACS location to the base handlerURL.
     string ACSloc=request.getHandlerURL(target.c_str());
-    pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
-    if (loc.first) ACSloc+=loc.second;
+    prop = ACS->getString("Location");
+    if (prop.first)
+        ACSloc += prop.second;
 
     if (isHandler) {
         // We may already have RelayState set if we looped back here,
-        // but just in case target is a resource, we reset it back.
-        target.erase();
-        option = request.getParameter("target");
-        if (option)
-            target = option;
+        // but we've turned it back into a resource by this point, so if there's
+        // a target on the URL, reset to that value.
+        prop.second = request.getParameter("target");
+        if (prop.second && *prop.second)
+            target = prop.second;
     }
 
     m_log.debug("attempting to initiate session using ADFS with provider (%s)", entityID.c_str());
 
-    if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess))
-        return doRequest(app, request, entityID.c_str(), ACSloc.c_str(), (acClass.first ? acClass.second : NULL), target);
+    if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
+        // Out of process means the POST data via the request can be exposed directly to the private method.
+        // The method will handle POST preservation if necessary *before* issuing the response, but only if
+        // it dispatches to an IdP.
+        return doRequest(app, &request, request, entityID.c_str(), ACSloc.c_str(), (acClass.first ? acClass.second : nullptr), target);
+    }
 
     // Remote the call.
     DDF out,in = DDF(m_address.c_str()).structure();
@@ -402,7 +422,7 @@ pair<bool,long> ADFSSessionInitiator::run(SPRequest& request, string& entityID,
     in.addmember("entity_id").string(entityID.c_str());
     in.addmember("acsLocation").string(ACSloc.c_str());
     if (!target.empty())
-        in.addmember("RelayState").string(target.c_str());
+        in.addmember("RelayState").unsafe_string(target.c_str());
     if (acClass.first)
         in.addmember("authnContextClassRef").string(acClass.second);
 
@@ -411,11 +431,21 @@ pair<bool,long> ADFSSessionInitiator::run(SPRequest& request, string& entityID,
     return unwrap(request, out);
 }
 
+pair<bool,long> ADFSSessionInitiator::unwrap(SPRequest& request, DDF& out) const
+{
+    // See if there's any response to send back.
+    if (!out["redirect"].isnull() || !out["response"].isnull()) {
+        // If so, we're responsible for handling the POST data, probably by dropping a cookie.
+        preservePostData(request.getApplication(), request, request, out["RelayState"].string());
+    }
+    return RemotedHandler::unwrap(request, out);
+}
+
 void ADFSSessionInitiator::receive(DDF& in, ostream& out)
 {
     // Find application.
     const char* aid=in["application_id"].string();
-    const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
+    const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
     if (!app) {
         // Something's horribly wrong.
         m_log.error("couldn't find application (%s) to generate ADFS request", aid ? aid : "(missing)");
@@ -427,7 +457,7 @@ void ADFSSessionInitiator::receive(DDF& in, ostream& out)
     if (!entityID || !acsLocation)
         throw ConfigurationException("No entityID or acsLocation parameter supplied to remoted SessionInitiator.");
 
-    DDF ret(NULL);
+    DDF ret(nullptr);
     DDFJanitor jout(ret);
 
     // Wrap the outgoing object with a Response facade.
@@ -438,12 +468,16 @@ void ADFSSessionInitiator::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, *http.get(), entityID, acsLocation, in["authnContextClassRef"].string(), relayState);
+    doRequest(*app, nullptr, *http.get(), entityID, acsLocation, in["authnContextClassRef"].string(), relayState);
+    if (!ret.isstruct())
+        ret.structure();
+    ret.addmember("RelayState").unsafe_string(relayState.c_str());
     out << ret;
 }
 
 pair<bool,long> ADFSSessionInitiator::doRequest(
     const Application& app,
+    const HTTPRequest* httpRequest,
     HTTPResponse& httpResponse,
     const char* entityID,
     const char* acsLocation,
@@ -455,14 +489,14 @@ pair<bool,long> ADFSSessionInitiator::doRequest(
     // Use metadata to invoke the SSO service directly.
     MetadataProvider* m=app.getMetadataProvider();
     Locker locker(m);
-    MetadataProvider::Criteria mc(entityID, &IDPSSODescriptor::ELEMENT_QNAME, m_binding.get());
+    MetadataProviderCriteria mc(app, 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));
     }
     else if (!entity.second) {
-        m_log.warn("unable to locate ADFS-aware identity provider role for provider (%s)", entityID);
+        m_log.log(getParent() ? Priority::INFO : Priority::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));
@@ -480,7 +514,7 @@ pair<bool,long> ADFSSessionInitiator::doRequest(
     preserveRelayState(app, httpResponse, relayState);
 
     // UTC timestamp
-    time_t epoch=time(NULL);
+    time_t epoch=time(nullptr);
 #ifndef HAVE_GMTIME_R
     struct tm* ptime=gmtime(&epoch);
 #else
@@ -500,6 +534,11 @@ pair<bool,long> ADFSSessionInitiator::doRequest(
     if (!relayState.empty())
         req += "&wctx=" + urlenc->encode(relayState.c_str());
 
+    if (httpRequest) {
+        // If the request object is available, we're responsible for the POST data.
+        preservePostData(app, *httpRequest, httpResponse, relayState.c_str());
+    }
+
     return make_pair(true, httpResponse.sendRedirect(req.c_str()));
 #else
     return make_pair(false,0L);
@@ -537,7 +576,7 @@ XMLObject* ADFSDecoder::decode(string& relayState, const GenericRequest& generic
     // Parse and bind the document into an XMLObject.
     istringstream is(param);
     DOMDocument* doc = (policy.getValidating() ? XMLToolingConfig::getConfig().getValidatingParser()
-        : XMLToolingConfig::getConfig().getParser()).parse(is); 
+        : XMLToolingConfig::getConfig().getParser()).parse(is);
     XercesJanitor<DOMDocument> janitor(doc);
     auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
     janitor.release();
@@ -547,12 +586,11 @@ XMLObject* ADFSDecoder::decode(string& relayState, const GenericRequest& generic
         throw BindingException("Decoded message was not of the appropriate type.");
     }
 
-    if (!policy.getValidating())
-        SchemaValidators.validate(xmlObject.get());
+    SchemaValidators.validate(xmlObject.get());
 
     // Skip policy step here, there's no security in the wrapper.
     // policy.evaluate(*xmlObject.get(), &genericRequest);
-    
+
     return xmlObject.release();
 }
 
@@ -561,7 +599,7 @@ void ADFSConsumer::implementProtocol(
     const HTTPRequest& httpRequest,
     HTTPResponse& httpResponse,
     SecurityPolicy& policy,
-    const PropertySet* settings,
+    const PropertySet*,
     const XMLObject& xmlObject
     ) const
 {
@@ -573,8 +611,8 @@ void ADFSConsumer::implementProtocol(
     const ElementProxy* response = dynamic_cast<const ElementProxy*>(&xmlObject);
     if (!response || !response->hasChildren())
         throw FatalProfileException("Incoming message was not of the proper type or contains no security token.");
-    
-    const Assertion* token = NULL;
+
+    const Assertion* token = nullptr;
     for (vector<XMLObject*>::const_iterator xo = response->getUnknownXMLObjects().begin(); xo != response->getUnknownXMLObjects().end(); ++xo) {
        // Look for the RequestedSecurityToken element.
        if (XMLString::equals((*xo)->getElementQName().getLocalPart(), RequestedSecurityToken)) {
@@ -587,39 +625,38 @@ void ADFSConsumer::implementProtocol(
            break;
        }
     }
-    
+
     // Extract message and issuer details from assertion.
     extractMessageDetails(*token, m_protocol.get(), policy);
 
+    // Populate recipient as audience.
+    const EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : nullptr;
+    policy.getAudiences().push_back(application.getRelyingParty(entity)->getXMLString("entityID").second);
+
     // Run the policy over the assertion. Handles replay, freshness, and
-    // signature verification, assuming the relevant rules are configured.
-    policy.evaluate(*token);
-    
+    // signature verification, assuming the relevant rules are configured,
+    // along with condition enforcement.
+    policy.evaluate(*token, &httpRequest);
+
     // If no security is in place now, we kick it.
     if (!policy.isAuthenticated())
         throw SecurityPolicyException("Unable to establish security of incoming assertion.");
 
-    time_t now = time(NULL);
-    
+    saml1::NameIdentifier* saml1name=nullptr;
+    saml2::NameID* saml2name=nullptr;
+    const XMLCh* authMethod=nullptr;
+    const XMLCh* authInstant=nullptr;
+    time_t now = time(nullptr), sessionExp = 0;
     const PropertySet* sessionProps = application.getPropertySet("Sessions");
-    const EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL;
-
-    saml1::NameIdentifier* saml1name=NULL;
-    saml2::NameID* saml2name=NULL;
-    const XMLCh* authMethod=NULL;
-    const XMLCh* authInstant=NULL;
-    time_t sessionExp = 0;
-    
+
     const saml1::Assertion* saml1token = dynamic_cast<const saml1::Assertion*>(token);
     if (saml1token) {
-        // Now do profile and core semantic validation to ensure we can use it for SSO.
-        saml1::AssertionValidator ssoValidator(application.getRelyingParty(entity)->getXMLString("entityID").second, application.getAudiences(), now);
-        ssoValidator.validateAssertion(*saml1token);
+        // Now do profile validation to ensure we can use it for SSO.
         if (!saml1token->getConditions() || !saml1token->getConditions()->getNotBefore() || !saml1token->getConditions()->getNotOnOrAfter())
             throw FatalProfileException("Assertion did not contain time conditions.");
         else if (saml1token->getAuthenticationStatements().empty())
             throw FatalProfileException("Assertion did not contain an authentication statement.");
-        
+
         // authnskew allows rejection of SSO if AuthnInstant is too old.
         pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);
 
@@ -651,14 +688,12 @@ void ADFSConsumer::implementProtocol(
         if (!saml2token)
             throw FatalProfileException("Incoming message did not contain a recognized type of SAML assertion.");
 
-        // Now do profile and core semantic validation to ensure we can use it for SSO.
-        saml2::AssertionValidator ssoValidator(application.getRelyingParty(entity)->getXMLString("entityID").second, application.getAudiences(), now);
-        ssoValidator.validateAssertion(*saml2token);
+        // Now do profile validation to ensure we can use it for SSO.
         if (!saml2token->getConditions() || !saml2token->getConditions()->getNotBefore() || !saml2token->getConditions()->getNotOnOrAfter())
             throw FatalProfileException("Assertion did not contain time conditions.");
         else if (saml2token->getAuthnStatements().empty())
             throw FatalProfileException("Assertion did not contain an authentication statement.");
-        
+
         // authnskew allows rejection of SSO if AuthnInstant is too old.
         pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);
 
@@ -674,7 +709,7 @@ void ADFSConsumer::implementProtocol(
             checkAddress(application, httpRequest, ip.get());
         }
 
-        saml2name = saml2token->getSubject() ? saml2token->getSubject()->getNameID() : NULL;
+        saml2name = saml2token->getSubject() ? saml2token->getSubject()->getNameID() : nullptr;
         if (ssoStatement->getAuthnContext() && ssoStatement->getAuthnContext()->getAuthnContextClassRef())
             authMethod = ssoStatement->getAuthnContext()->getAuthnContextClassRef()->getReference();
         if (ssoStatement->getAuthnInstant())
@@ -690,14 +725,14 @@ void ADFSConsumer::implementProtocol(
         else
             sessionExp = min(sessionExp, now + lifetime.second);    // Use the lowest.
     }
-    
+
     m_log.debug("ADFS profile processing completed successfully");
 
     // We've successfully "accepted" the SSO token.
     // To complete processing, we need to extract and resolve attributes and then create the session.
 
     // Normalize a SAML 1.x NameIdentifier...
-    auto_ptr<saml2::NameID> nameid(saml1name ? saml2::NameIDBuilder::buildNameID() : NULL);
+    auto_ptr<saml2::NameID> nameid(saml1name ? saml2::NameIDBuilder::buildNameID() : nullptr);
     if (saml1name) {
         nameid->setName(saml1name->getName());
         nameid->setFormat(saml1name->getFormat());
@@ -714,7 +749,7 @@ void ADFSConsumer::implementProtocol(
             saml1name,
             (saml1name ? nameid.get() : saml2name),
             authMethod,
-            NULL,
+            nullptr,
             &tokens
             )
         );
@@ -733,11 +768,11 @@ void ADFSConsumer::implementProtocol(
         m_protocol.get(),
         (saml1name ? nameid.get() : saml2name),
         authInstant,
-        NULL,
+        nullptr,
         authMethod,
-        NULL,
+        nullptr,
         &tokens,
-        ctx.get() ? &ctx->getResolvedAttributes() : NULL
+        ctx.get() ? &ctx->getResolvedAttributes() : nullptr
         );
 }
 
@@ -751,7 +786,7 @@ pair<bool,long> ADFSLogoutInitiator::run(SPRequest& request, bool isHandler) con
     // Basically we have no way to tell in the Logout receiving handler whether
     // we initiated the logout or not.
 
-    Session* session = NULL;
+    Session* session = nullptr;
     try {
         session = request.getSession(false, true, false);  // don't cache it and ignore all checks
         if (!session)
@@ -795,24 +830,24 @@ void ADFSLogoutInitiator::receive(DDF& in, ostream& out)
 
     // Find application.
     const char* aid=in["application_id"].string();
-    const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
+    const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
     if (!app) {
         // Something's horribly wrong.
         m_log.error("couldn't find application (%s) for logout", aid ? aid : "(missing)");
         throw ConfigurationException("Unable to locate application for logout, deleted?");
     }
-    
+
     // Unpack the request.
     auto_ptr<HTTPRequest> req(getRequest(in));
 
     // Set up a response shim.
-    DDF ret(NULL);
+    DDF ret(nullptr);
     DDFJanitor jout(ret);
     auto_ptr<HTTPResponse> resp(getResponse(ret));
-    
-    Session* session = NULL;
+
+    Session* session = nullptr;
     try {
-         session = app->getServiceProvider().getSessionCache()->find(*app, *req.get(), NULL, NULL);
+         session = app->getServiceProvider().getSessionCache()->find(*app, *req.get(), nullptr, nullptr);
     }
     catch (exception& ex) {
         m_log.error("error accessing current session: %s", ex.what());
@@ -847,7 +882,7 @@ pair<bool,long> ADFSLogoutInitiator::doRequest(
     if (!notifyBackChannel(application, httpRequest.getRequestURL(), sessions, false)) {
         session->unlock();
         application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
-        return sendLogoutPage(application, httpRequest, httpResponse, true, "Partial logout failure.");
+        return sendLogoutPage(application, httpRequest, httpResponse, "partial");
     }
 
 #ifndef SHIBSP_LITE
@@ -857,7 +892,7 @@ pair<bool,long> ADFSLogoutInitiator::doRequest(
         // With a session in hand, we can create a request message, if we can find a compatible endpoint.
         MetadataProvider* m=application.getMetadataProvider();
         Locker metadataLocker(m);
-        MetadataProvider::Criteria mc(session->getEntityID(), &IDPSSODescriptor::ELEMENT_QNAME, m_binding.get());
+        MetadataProviderCriteria mc(application, session->getEntityID(), &IDPSSODescriptor::ELEMENT_QNAME, m_binding.get());
         pair<const EntityDescriptor*,const RoleDescriptor*> entity=m->getEntityDescriptor(mc);
         if (!entity.first) {
             throw MetadataException(
@@ -869,13 +904,14 @@ pair<bool,long> ADFSLogoutInitiator::doRequest(
                 "Unable to locate ADFS IdP role for identity provider ($entityID).", namedparams(1, "entityID", session->getEntityID())
                 );
         }
-        
+
         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).", namedparams(1, "entityID", session->getEntityID())
+                "Unable to locate ADFS single logout service for identity provider ($entityID).",
+                namedparams(1, "entityID", session->getEntityID())
                 );
         }
 
@@ -894,7 +930,7 @@ pair<bool,long> ADFSLogoutInitiator::doRequest(
 
     if (session) {
         session->unlock();
-        session = NULL;
+        session = nullptr;
         application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
     }
 
@@ -954,5 +990,5 @@ pair<bool,long> ADFSLogout::run(SPRequest& request, bool isHandler) const
 
     if (param)
         return make_pair(true, request.sendRedirect(param));
-    return sendLogoutPage(app, request, request, false, "Logout complete.");
+    return sendLogoutPage(app, request, request, "global");
 }