Update version resources.
[shibboleth/cpp-sp.git] / adfs / adfs.cpp
index 6570271..6fc91a4 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>
@@ -77,6 +73,23 @@ using namespace std;
 
 namespace {
 
+#ifndef SHIBSP_LITE
+    class SHIBSP_DLLLOCAL ADFSDecoder : public MessageDecoder
+    {
+        auto_ptr_XMLCh m_ns;
+    public:
+        ADFSDecoder() : m_ns(WSTRUST_NS) {}
+        virtual ~ADFSDecoder() {}
+        
+        XMLObject* decode(string& relayState, const GenericRequest& genericRequest, SecurityPolicy& policy) const;
+    };
+
+    MessageDecoder* ADFSDecoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
+    {
+        return new ADFSDecoder();
+    }
+#endif
+
 #if defined (_MSC_VER)
     #pragma warning( push )
     #pragma warning( disable : 4250 )
@@ -86,7 +99,7 @@ namespace {
     {
     public:
         ADFSSessionInitiator(const DOMElement* e, const char* appId)
-                : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator")), m_appId(appId), m_binding(WSFED_NS) {
+                : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator.ADFS")), 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) {
@@ -129,7 +142,7 @@ namespace {
         ADFSConsumer(const DOMElement* e, const char* appId)
             : shibsp::AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SSO.ADFS"))
 #ifndef SHIBSP_LITE
-                ,m_binding(WSFED_NS)
+                ,m_protocol(WSFED_NS)
 #endif
             {}
         virtual ~ADFSConsumer() {}
@@ -143,15 +156,15 @@ namespace {
             const PropertySet* settings,
             const XMLObject& xmlObject
             ) const;
-        auto_ptr_XMLCh m_binding;
+        auto_ptr_XMLCh m_protocol;
 #endif
     };
 
-    class SHIBSP_DLLLOCAL ADFSLogoutInitiator : public AbstractHandler, public LogoutHandler
+    class SHIBSP_DLLLOCAL ADFSLogoutInitiator : public AbstractHandler, public RemotedHandler
     {
     public:
         ADFSLogoutInitiator(const DOMElement* e, const char* appId)
-                : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator")), m_appId(appId), m_binding(WSFED_NS) {
+                : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".LogoutInitiator.ADFS")), 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) {
@@ -178,7 +191,7 @@ namespace {
 
     private:
         pair<bool,long> doRequest(
-            const Application& application, const char* requestURL, Session* session, HTTPResponse& httpResponse
+            const Application& application, const char* requestURL, const char* entityID, HTTPResponse& httpResponse
             ) const;
 
         string m_appId;
@@ -209,23 +222,6 @@ namespace {
     #pragma warning( pop )
 #endif
 
-#ifndef SHIBSP_LITE
-    class ADFSDecoder : public MessageDecoder
-    {
-        auto_ptr_XMLCh m_ns;
-    public:
-        ADFSDecoder() : m_ns(WSTRUST_NS) {}
-        virtual ~ADFSDecoder() {}
-        
-        XMLObject* decode(string& relayState, const GenericRequest& genericRequest, SecurityPolicy& policy) const;
-    };
-
-    MessageDecoder* ADFSDecoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
-    {
-        return new ADFSDecoder();
-    }
-#endif
-
     SessionInitiator* ADFSSessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
     {
         return new ADFSSessionInitiator(p.first, p.second);
@@ -255,7 +251,7 @@ extern "C" int ADFS_EXPORTS xmltooling_extension_init(void*)
 #ifndef SHIBSP_LITE
     SAMLConfig::getConfig().MessageDecoderManager.registerFactory(WSFED_NS, ADFSDecoderFactory);
     XMLObjectBuilder::registerBuilder(QName(WSTRUST_NS,"RequestedSecurityToken"), new AnyElementBuilder());
-    XMLObjectBuilder::registerBuilder(QName(WSTRUST_NS,"RequestedSecurityTokenResponse"), new AnyElementBuilder());
+    XMLObjectBuilder::registerBuilder(QName(WSTRUST_NS,"RequestSecurityTokenResponse"), new AnyElementBuilder());
 #endif
     return 0;
 }
@@ -489,8 +485,8 @@ XMLObject* ADFSDecoder::decode(string& relayState, const GenericRequest& generic
     if (!policy.getValidating())
         SchemaValidators.validate(xmlObject.get());
 
-    // Run through the policy.
-    policy.evaluate(*xmlObject.get(), &genericRequest);
+    // Skip policy step here, there's no security in the wrapper.
+    // policy.evaluate(*xmlObject.get(), &genericRequest);
     
     return xmlObject.release();
 }
@@ -520,7 +516,7 @@ string ADFSConsumer::implementProtocol(
 
     // Run the policy over the assertion. Handles issuer consistency, replay, freshness,
     // and signature verification, assuming the relevant rules are configured.
-    policy.evaluate(*token);
+    policy.evaluate(*token, NULL, m_protocol.get());
     
     // If no security is in place now, we kick it.
     if (!policy.isSecure())
@@ -561,41 +557,6 @@ string ADFSConsumer::implementProtocol(
 
     // We've successfully "accepted" the SSO token.
     // To complete processing, we need to extract and resolve attributes and then create the session.
-    multimap<string,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(), cleanup_pair<string,shibsp::Attribute>());
-                resolvedAttributes.clear();
-            }
-        }
-    }
 
     // Normalize the SAML 1.x NameIdentifier...
     auto_ptr<saml2::NameID> nameid(n ? saml2::NameIDBuilder::buildNameID() : NULL);
@@ -605,65 +566,50 @@ 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,
-            m_binding.get(),
+            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(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_binding.get(),
-            nameid.get(),
-            ssoStatement->getAuthenticationInstant() ? ssoStatement->getAuthenticationInstant()->getRawData() : NULL,
-            NULL,
-            ssoStatement->getAuthenticationMethod(),
-            NULL,
-            &tokens,
-            &resolvedAttributes
-            );
-        for_each(resolvedAttributes.begin(), resolvedAttributes.end(), cleanup_pair<string,Attribute>());
-        return key;
-    }
-    catch (exception&) {
-        for_each(resolvedAttributes.begin(), resolvedAttributes.end(), cleanup_pair<string,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
 
 pair<bool,long> ADFSLogoutInitiator::run(SPRequest& request, bool isHandler) const
 {
-    // Defer to base class for front-channel loop first.
-    pair<bool,long> ret = LogoutHandler::run(request, isHandler);
-    if (ret.first)
-        return ret;
-
-    // At this point we know the front-channel is handled.
-    // We need the session to do any other work.
+    // Normally we'd do notifications and session clearage here, but ADFS logout
+    // is missing the needed request/response features, so we have to rely on
+    // the IdP half to notify us back about the logout and do the work there.
+    // Basically we have no way to tell in the Logout receiving handler whether
+    // we initiated the logout or not.
 
     Session* session = NULL;
     try {
@@ -671,8 +617,8 @@ pair<bool,long> ADFSLogoutInitiator::run(SPRequest& request, bool isHandler) con
         if (!session)
             return make_pair(false,0);
 
-        // We only handle SAML 2.0 sessions.
-        if (!XMLString::equals(session->getProtocol(), WSFED_NS)) {
+        // We only handle ADFS sessions.
+        if (!XMLString::equals(session->getProtocol(), WSFED_NS) || !session->getEntityID()) {
             session->unlock();
             return make_pair(false,0);
         }
@@ -682,18 +628,21 @@ pair<bool,long> ADFSLogoutInitiator::run(SPRequest& request, bool isHandler) con
         return make_pair(false,0);
     }
 
+    string entityID(session->getEntityID());
+    session->unlock();
+
     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
         // When out of process, we run natively.
-        return doRequest(request.getApplication(), request.getRequestURL(), session, request);
+        return doRequest(request.getApplication(), request.getRequestURL(), entityID.c_str(), request);
     }
     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());
-        in.addmember("session_id").string(session->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);
     }
@@ -716,29 +665,11 @@ void ADFSLogoutInitiator::receive(DDF& in, ostream& out)
     DDFJanitor jout(ret);
     auto_ptr<HTTPResponse> resp(getResponse(ret));
     
-    Session* session = NULL;
-    try {
-         session = app->getServiceProvider().getSessionCache()->find(in["session_id"].string(), *app, NULL, NULL);
-    }
-    catch (exception& ex) {
-        m_log.error("error accessing current session: %s", ex.what());
-    }
+    // 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());
 
-    // With no session, we just skip the request and let it fall through to an empty struct return.
-    if (session) {
-        if (session->getEntityID()) {
-            // 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(), session, *resp.get());
-        }
-        else {
-             m_log.error("no issuing entityID found in session");
-             session->unlock();
-             session = NULL;
-             app->getServiceProvider().getSessionCache()->remove(in["session_id"].string(), *app);
-         }
-    }
     out << ret;
 #else
     throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
@@ -746,38 +677,28 @@ void ADFSLogoutInitiator::receive(DDF& in, ostream& out)
 }
 
 pair<bool,long> ADFSLogoutInitiator::doRequest(
-    const Application& application, const char* requestURL, Session* session, HTTPResponse& response
+    const Application& application, const char* requestURL, const char* entityID, HTTPResponse& response
     ) const
 {
-    string entityID(session->getEntityID());
-    vector<string> sessions(1, session->getID());
-
-    // Do back channel notification.
-    if (!notifyBackChannel(application, requestURL, sessions, false)) {
-        session->unlock();
-        application.getServiceProvider().getSessionCache()->remove(sessions.front().c_str(), application);
-        return sendLogoutPage(application, response, true, "Partial logout failure.");
-    }
-
-    session->unlock();
-    application.getServiceProvider().getSessionCache()->remove(sessions.front().c_str(), application);
-
 #ifndef SHIBSP_LITE
     try {
+        if (!entityID)
+            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.c_str());
+        const EntityDescriptor* entity = application.getMetadataProvider()->getEntityDescriptor(entityID);
         if (!entity) {
             throw MetadataException(
                 "Unable to locate metadata for identity provider ($entityID)",
-                namedparams(1, "entityID", entityID.c_str())
+                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.c_str())
+                namedparams(1, "entityID", entityID)
                 );
         }
 
@@ -785,7 +706,7 @@ pair<bool,long> ADFSLogoutInitiator::doRequest(
         if (!ep) {
             throw MetadataException(
                 "Unable to locate ADFS single logout service for identity provider ($entityID).",
-                namedparams(1, "entityID", entityID.c_str())
+                namedparams(1, "entityID", entityID)
                 );
         }
 
@@ -853,6 +774,7 @@ pair<bool,long> ADFSLogout::run(SPRequest& request, bool isHandler) const
         catch (exception& ex) {
             m_log.error("error removing session (%s): %s", session_id, ex.what());
         }
+        request.setCookie(shib_cookie.first.c_str(), shib_cookie.second);
     }
 
     if (param)