First set of logout base classes and non-building draft of SP-initiated logout.
[shibboleth/sp.git] / shibsp / handler / impl / AbstractHandler.cpp
index 75c5432..7321f03 100644 (file)
 #include "SPRequest.h"
 #include "handler/AbstractHandler.h"
 #include "remoting/ListenerService.h"
+#include "util/SPConstants.h"
+
+#ifndef SHIBSP_LITE
+# include <saml/SAMLConfig.h>
+# include <saml/binding/SAMLArtifact.h>
+# include <saml/saml1/core/Protocols.h>
+# include <saml/saml2/core/Protocols.h>
+# include <saml/saml2/metadata/Metadata.h>
+# include <saml/saml2/metadata/MetadataCredentialCriteria.h>
+# include <saml/util/SAMLConstants.h>
+# include <xmltooling/util/StorageService.h>
+using namespace opensaml::saml2md;
+#else
+# include "lite/SAMLConstants.h"
+#endif
 
-#include <saml/SAMLConfig.h>
-#include <saml/binding/SAMLArtifact.h>
-#include <saml/saml1/core/Protocols.h>
-#include <saml/saml2/core/Protocols.h>
-#include <saml/util/SAMLConstants.h>
 #include <xmltooling/XMLToolingConfig.h>
-#include <xmltooling/util/StorageService.h>
 #include <xmltooling/util/URLEncoder.h>
 
 using namespace shibsp;
@@ -46,8 +55,13 @@ using namespace xercesc;
 using namespace std;
 
 namespace shibsp {
-    SHIBSP_DLLLOCAL PluginManager<Handler,pair<const DOMElement*,const char*>>::Factory SAML1ConsumerFactory;
-    SHIBSP_DLLLOCAL PluginManager<Handler,pair<const DOMElement*,const char*>>::Factory SAML2ConsumerFactory;
+    SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML1ConsumerFactory;
+    SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2ConsumerFactory;
+    SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2ArtifactResolutionFactory;
+    SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory AssertionLookupFactory;
+    SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory ChainingLogoutInitiatorFactory;
+    SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory LocalLogoutInitiatorFactory;
+    SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2LogoutInitiatorFactory;
 };
 
 void SHIBSP_API shibsp::registerHandlers()
@@ -59,14 +73,24 @@ void SHIBSP_API shibsp::registerHandlers()
     conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_ARTIFACT, SAML2ConsumerFactory);
     conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_POST, SAML2ConsumerFactory);
     conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_POST_SIMPLESIGN, SAML2ConsumerFactory);
+
+    conf.ArtifactResolutionServiceManager.registerFactory(SAML20_BINDING_SOAP, SAML2ArtifactResolutionFactory);
+
+    conf.HandlerManager.registerFactory(SAML20_BINDING_URI, AssertionLookupFactory);
+
+    conf.LogoutInitiatorManager.registerFactory(CHAINING_LOGOUT_INITIATOR, ChainingLogoutInitiatorFactory);
+    conf.LogoutInitiatorManager.registerFactory(LOCAL_LOGOUT_INITIATOR, LocalLogoutInitiatorFactory);
+    conf.LogoutInitiatorManager.registerFactory(SAML2_LOGOUT_INITIATOR, SAML2LogoutInitiatorFactory);
 }
 
 AbstractHandler::AbstractHandler(
     const DOMElement* e, log4cpp::Category& log, DOMNodeFilter* filter, const map<string,string>* remapper
-    ) : m_log(log) {
+    ) : m_log(log), m_configNS(shibspconstants::SHIB2SPCONFIG_NS) {
     load(e,log,filter,remapper);
 }
 
+#ifndef SHIBSP_LITE
+
 void AbstractHandler::checkError(const XMLObject* response) const
 {
     const saml2p::StatusResponseType* r2 = dynamic_cast<const saml2p::StatusResponseType*>(response);
@@ -115,6 +139,88 @@ void AbstractHandler::checkError(const XMLObject* response) const
     }
 }
 
+void AbstractHandler::fillStatus(saml2p::StatusResponseType& response, const XMLCh* code, const XMLCh* subcode, const char* msg) const
+{
+    saml2p::Status* status = saml2p::StatusBuilder::buildStatus();
+    saml2p::StatusCode* scode = saml2p::StatusCodeBuilder::buildStatusCode();
+    status->setStatusCode(scode);
+    scode->setValue(code);
+    if (subcode) {
+        saml2p::StatusCode* ssubcode = saml2p::StatusCodeBuilder::buildStatusCode();
+        scode->setStatusCode(ssubcode);
+        ssubcode->setValue(subcode);
+    }
+    if (msg) {
+        pair<bool,bool> flag = getBool("detailedErrors", m_configNS.get());
+        auto_ptr_XMLCh widemsg((flag.first && flag.second) ? msg : "Error processing request.");
+        saml2p::StatusMessage* sm = saml2p::StatusMessageBuilder::buildStatusMessage();
+        status->setStatusMessage(sm);
+        sm->setMessage(widemsg.get());
+    }
+    response.setStatus(status);
+}
+
+long AbstractHandler::sendMessage(
+    const MessageEncoder& encoder,
+    XMLObject* msg,
+    const char* relayState,
+    const char* destination,
+    const saml2md::RoleDescriptor* role,
+    const Application& application,
+    HTTPResponse& httpResponse,
+    const char* signingOption,
+    bool signIfPossible
+    ) const
+{
+    const EntityDescriptor* entity = role ? dynamic_cast<const EntityDescriptor*>(role->getParent()) : NULL;
+    const PropertySet* relyingParty = application.getRelyingParty(entity);
+    pair<bool,const char*> flag = signIfPossible ? make_pair(true,"true") : relyingParty->getString(signingOption);
+    if (role && flag.first &&
+        (!strcmp(flag.second, "true") ||
+            (encoder.isUserAgentPresent() && !strcmp(flag.second, "front")) ||
+            (!encoder.isUserAgentPresent() && !strcmp(flag.second, "back")))) {
+        CredentialResolver* credResolver=application.getCredentialResolver();
+        if (credResolver) {
+            Locker credLocker(credResolver);
+            // Fill in criteria to use.
+            MetadataCredentialCriteria mcc(*role);
+            mcc.setUsage(CredentialCriteria::SIGNING_CREDENTIAL);
+            pair<bool,const char*> keyName = relyingParty->getString("keyName");
+            if (keyName.first)
+                mcc.getKeyNames().insert(keyName.second);
+            pair<bool,const XMLCh*> sigalg = relyingParty->getXMLString("signatureAlg");
+            if (sigalg.first)
+                mcc.setXMLAlgorithm(sigalg.second);
+            const Credential* cred = credResolver->resolve(&mcc);
+            if (cred) {
+                // Signed request.
+                return encoder.encode(
+                    httpResponse,
+                    msg,
+                    destination,
+                    entity,
+                    relayState,
+                    &application,
+                    cred,
+                    sigalg.second,
+                    relyingParty->getXMLString("digestAlg").second
+                    );
+            }
+            else {
+                m_log.warn("no signing credential resolved, leaving message unsigned");
+            }
+        }
+        else {
+            m_log.warn("no credential resolver installed, leaving message unsigned");
+        }
+    }
+
+    // Unsigned request.
+    return encoder.encode(httpResponse, msg, destination, entity, relayState, &application);
+}
+
+#endif
+
 void AbstractHandler::preserveRelayState(const Application& application, HTTPResponse& response, string& relayState) const
 {
     if (relayState.empty())
@@ -141,18 +247,21 @@ void AbstractHandler::preserveRelayState(const Application& application, HTTPRes
             mech.second+=3;
             if (*mech.second) {
                 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
+#ifndef SHIBSP_LITE
                     StorageService* storage = application.getServiceProvider().getStorageService(mech.second);
                     if (storage) {
                         string rsKey;
-                        SAMLConfig::getConfig().generateRandomBytes(rsKey,20);
+                        SAMLConfig::getConfig().generateRandomBytes(rsKey,10);
                         rsKey = SAMLArtifact::toHex(rsKey);
-                        storage->createString("RelayState", rsKey.c_str(), relayState.c_str(), time(NULL) + 600);
+                        if (!storage->createString("RelayState", rsKey.c_str(), relayState.c_str(), time(NULL) + 600))
+                            throw IOException("Attempted to insert duplicate storage key.");
                         relayState = string(mech.second-3) + ':' + rsKey;
                     }
                     else {
                         m_log.error("Storage-backed RelayState with invalid StorageService ID (%s)", mech.second);
                         relayState.erase();
                     }
+#endif
                 }
                 else if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
                     DDF out,in = DDF("set::RelayState").structure();
@@ -185,11 +294,13 @@ void AbstractHandler::recoverRelayState(const Application& application, HTTPRequ
             key++;
             if (!ssid.empty() && *key) {
                 if (conf.isEnabled(SPConfig::OutOfProcess)) {
+#ifndef SHIBSP_LITE
                     StorageService* storage = conf.getServiceProvider()->getStorageService(ssid.c_str());
                     if (storage) {
-                        if (storage->readString("RelayState",key,&relayState)>0) {
+                        ssid = key;
+                        if (storage->readString("RelayState",ssid.c_str(),&relayState)>0) {
                             if (clear)
-                                storage->deleteString("RelayState",key);
+                                storage->deleteString("RelayState",ssid.c_str());
                             return;
                         }
                         else
@@ -201,6 +312,7 @@ void AbstractHandler::recoverRelayState(const Application& application, HTTPRequ
                             );
                         relayState.erase();
                     }
+#endif
                 }
                 else if (conf.isEnabled(SPConfig::InProcess)) {
                     DDF out,in = DDF("get::RelayState").structure();