-/*\r
- * Copyright 2001-2009 Internet2\r
- *\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- */\r
-\r
-/**\r
- * AbstractHandler.cpp\r
- *\r
- * Base class for handlers based on a DOMPropertySet.\r
- */\r
-\r
-#include "internal.h"\r
-#include "exceptions.h"\r
-#include "Application.h"\r
-#include "ServiceProvider.h"\r
-#include "SPRequest.h"\r
-#include "handler/AbstractHandler.h"\r
-#include "handler/LogoutHandler.h"\r
-#include "remoting/ListenerService.h"\r
-#include "util/CGIParser.h"\r
-#include "util/SPConstants.h"\r
-#include "util/TemplateParameters.h"\r
-\r
-#include <vector>\r
-#include <fstream>\r
-#include <xmltooling/XMLToolingConfig.h>\r
-#include <xmltooling/util/PathResolver.h>\r
-#include <xmltooling/util/URLEncoder.h>\r
-\r
-\r
-#ifndef SHIBSP_LITE\r
-# include <saml/exceptions.h>\r
-# include <saml/SAMLConfig.h>\r
-# include <saml/binding/SAMLArtifact.h>\r
-# include <saml/saml1/core/Protocols.h>\r
-# include <saml/saml2/core/Protocols.h>\r
-# include <saml/saml2/metadata/Metadata.h>\r
-# include <saml/saml2/metadata/MetadataCredentialCriteria.h>\r
-# include <saml/util/SAMLConstants.h>\r
-# include <xmltooling/security/Credential.h>\r
-# include <xmltooling/security/CredentialResolver.h>\r
-# include <xmltooling/util/StorageService.h>\r
-using namespace opensaml::saml2md;\r
-using namespace opensaml;\r
-#else\r
-# include "lite/SAMLConstants.h"\r
-#endif\r
-\r
-#include <xmltooling/XMLToolingConfig.h>\r
-#include <xmltooling/util/URLEncoder.h>\r
-\r
-using namespace shibsp;\r
-using namespace samlconstants;\r
-using namespace xmltooling;\r
-using namespace xercesc;\r
-using namespace std;\r
-\r
-namespace shibsp {\r
- SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML1ConsumerFactory;\r
- SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2ConsumerFactory;\r
- SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2ArtifactResolutionFactory;\r
- SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory ChainingLogoutInitiatorFactory;\r
- SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory LocalLogoutInitiatorFactory;\r
- SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2LogoutInitiatorFactory;\r
- SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2LogoutFactory;\r
- SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2NameIDMgmtFactory;\r
- SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory AssertionLookupFactory;\r
- SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory MetadataGeneratorFactory;\r
- SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory StatusHandlerFactory;\r
- SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SessionHandlerFactory;\r
-\r
- void SHIBSP_DLLLOCAL generateRandomHex(std::string& buf, unsigned int len) {\r
- static char DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};\r
- int r;\r
- unsigned char b1,b2;\r
- buf.erase();\r
- for (unsigned int i=0; i<len; i+=4) {\r
- r = rand();\r
- b1 = (0x00FF & r);\r
- b2 = (0xFF00 & r) >> 8;\r
- buf += (DIGITS[(0xF0 & b1) >> 4 ]);\r
- buf += (DIGITS[0x0F & b1]);\r
- buf += (DIGITS[(0xF0 & b2) >> 4 ]);\r
- buf += (DIGITS[0x0F & b2]);\r
- }\r
- }\r
-};\r
-\r
-void SHIBSP_API shibsp::registerHandlers()\r
-{\r
- SPConfig& conf=SPConfig::getConfig();\r
-\r
- conf.AssertionConsumerServiceManager.registerFactory(SAML1_PROFILE_BROWSER_ARTIFACT, SAML1ConsumerFactory);\r
- conf.AssertionConsumerServiceManager.registerFactory(SAML1_PROFILE_BROWSER_POST, SAML1ConsumerFactory);\r
- conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_POST, SAML2ConsumerFactory);\r
- conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_POST_SIMPLESIGN, SAML2ConsumerFactory);\r
- conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_ARTIFACT, SAML2ConsumerFactory);\r
- conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_PAOS, SAML2ConsumerFactory);\r
-\r
- conf.ArtifactResolutionServiceManager.registerFactory(SAML20_BINDING_SOAP, SAML2ArtifactResolutionFactory);\r
-\r
- conf.HandlerManager.registerFactory(SAML20_BINDING_URI, AssertionLookupFactory);\r
- conf.HandlerManager.registerFactory(METADATA_GENERATOR_HANDLER, MetadataGeneratorFactory);\r
- conf.HandlerManager.registerFactory(STATUS_HANDLER, StatusHandlerFactory);\r
- conf.HandlerManager.registerFactory(SESSION_HANDLER, SessionHandlerFactory);\r
-\r
- conf.LogoutInitiatorManager.registerFactory(CHAINING_LOGOUT_INITIATOR, ChainingLogoutInitiatorFactory);\r
- conf.LogoutInitiatorManager.registerFactory(LOCAL_LOGOUT_INITIATOR, LocalLogoutInitiatorFactory);\r
- conf.LogoutInitiatorManager.registerFactory(SAML2_LOGOUT_INITIATOR, SAML2LogoutInitiatorFactory);\r
- conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_SOAP, SAML2LogoutFactory);\r
- conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_HTTP_REDIRECT, SAML2LogoutFactory);\r
- conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_HTTP_POST, SAML2LogoutFactory);\r
- conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_HTTP_POST_SIMPLESIGN, SAML2LogoutFactory);\r
- conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_HTTP_ARTIFACT, SAML2LogoutFactory);\r
-\r
- conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_SOAP, SAML2NameIDMgmtFactory);\r
- conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_HTTP_REDIRECT, SAML2NameIDMgmtFactory);\r
- conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_HTTP_POST, SAML2NameIDMgmtFactory);\r
- conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_HTTP_POST_SIMPLESIGN, SAML2NameIDMgmtFactory);\r
- conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_HTTP_ARTIFACT, SAML2NameIDMgmtFactory);\r
-}\r
-\r
-Handler::Handler()\r
-{\r
-}\r
-\r
-Handler::~Handler()\r
-{\r
-}\r
-\r
-AbstractHandler::AbstractHandler(\r
- const DOMElement* e, Category& log, DOMNodeFilter* filter, const map<string,string>* remapper\r
- ) : m_log(log), m_configNS(shibspconstants::SHIB2SPCONFIG_NS) {\r
- load(e,NULL,filter,remapper);\r
-}\r
-\r
-AbstractHandler::~AbstractHandler()\r
-{\r
-}\r
-\r
-#ifndef SHIBSP_LITE\r
-\r
-const char* Handler::getType() const\r
-{\r
- return getString("type").second;\r
-}\r
-\r
-void AbstractHandler::checkError(const XMLObject* response, const saml2md::RoleDescriptor* role) const\r
-{\r
- const saml2p::StatusResponseType* r2 = dynamic_cast<const saml2p::StatusResponseType*>(response);\r
- if (r2) {\r
- const saml2p::Status* status = r2->getStatus();\r
- if (status) {\r
- const saml2p::StatusCode* sc = status->getStatusCode();\r
- const XMLCh* code = sc ? sc->getValue() : NULL;\r
- if (code && !XMLString::equals(code,saml2p::StatusCode::SUCCESS)) {\r
- FatalProfileException ex("SAML response contained an error.");\r
- annotateException(&ex, role, status); // throws it\r
- }\r
- }\r
- }\r
-\r
- const saml1p::Response* r1 = dynamic_cast<const saml1p::Response*>(response);\r
- if (r1) {\r
- const saml1p::Status* status = r1->getStatus();\r
- if (status) {\r
- const saml1p::StatusCode* sc = status->getStatusCode();\r
- const xmltooling::QName* code = sc ? sc->getValue() : NULL;\r
- if (code && *code != saml1p::StatusCode::SUCCESS) {\r
- FatalProfileException ex("SAML response contained an error.");\r
- ex.addProperty("statusCode", code->toString().c_str());\r
- if (sc->getStatusCode()) {\r
- code = sc->getStatusCode()->getValue();\r
- if (code)\r
- ex.addProperty("statusCode2", code->toString().c_str());\r
- }\r
- if (status->getStatusMessage()) {\r
- auto_ptr_char msg(status->getStatusMessage()->getMessage());\r
- if (msg.get() && *msg.get())\r
- ex.addProperty("statusMessage", msg.get());\r
- }\r
- ex.raise();\r
- }\r
- }\r
- }\r
-}\r
-\r
-void AbstractHandler::fillStatus(saml2p::StatusResponseType& response, const XMLCh* code, const XMLCh* subcode, const char* msg) const\r
-{\r
- saml2p::Status* status = saml2p::StatusBuilder::buildStatus();\r
- saml2p::StatusCode* scode = saml2p::StatusCodeBuilder::buildStatusCode();\r
- status->setStatusCode(scode);\r
- scode->setValue(code);\r
- if (subcode) {\r
- saml2p::StatusCode* ssubcode = saml2p::StatusCodeBuilder::buildStatusCode();\r
- scode->setStatusCode(ssubcode);\r
- ssubcode->setValue(subcode);\r
- }\r
- if (msg) {\r
- pair<bool,bool> flag = getBool("detailedErrors", m_configNS.get());\r
- auto_ptr_XMLCh widemsg((flag.first && flag.second) ? msg : "Error processing request.");\r
- saml2p::StatusMessage* sm = saml2p::StatusMessageBuilder::buildStatusMessage();\r
- status->setStatusMessage(sm);\r
- sm->setMessage(widemsg.get());\r
- }\r
- response.setStatus(status);\r
-}\r
-\r
-long AbstractHandler::sendMessage(\r
- const MessageEncoder& encoder,\r
- XMLObject* msg,\r
- const char* relayState,\r
- const char* destination,\r
- const saml2md::RoleDescriptor* role,\r
- const Application& application,\r
- HTTPResponse& httpResponse,\r
- bool signIfPossible\r
- ) const\r
-{\r
- const EntityDescriptor* entity = role ? dynamic_cast<const EntityDescriptor*>(role->getParent()) : NULL;\r
- const PropertySet* relyingParty = application.getRelyingParty(entity);\r
- pair<bool,const char*> flag = signIfPossible ? make_pair(true,(const char*)"true") : relyingParty->getString("signing");\r
- if (role && flag.first &&\r
- (!strcmp(flag.second, "true") ||\r
- (encoder.isUserAgentPresent() && !strcmp(flag.second, "front")) ||\r
- (!encoder.isUserAgentPresent() && !strcmp(flag.second, "back")))) {\r
- CredentialResolver* credResolver=application.getCredentialResolver();\r
- if (credResolver) {\r
- Locker credLocker(credResolver);\r
- const Credential* cred = NULL;\r
- pair<bool,const char*> keyName = relyingParty->getString("keyName");\r
- pair<bool,const XMLCh*> sigalg = relyingParty->getXMLString("signingAlg");\r
- if (role) {\r
- MetadataCredentialCriteria mcc(*role);\r
- mcc.setUsage(Credential::SIGNING_CREDENTIAL);\r
- if (keyName.first)\r
- mcc.getKeyNames().insert(keyName.second);\r
- if (sigalg.first)\r
- mcc.setXMLAlgorithm(sigalg.second);\r
- cred = credResolver->resolve(&mcc);\r
- }\r
- else {\r
- CredentialCriteria cc;\r
- cc.setUsage(Credential::SIGNING_CREDENTIAL);\r
- if (keyName.first)\r
- cc.getKeyNames().insert(keyName.second);\r
- if (sigalg.first)\r
- cc.setXMLAlgorithm(sigalg.second);\r
- cred = credResolver->resolve(&cc);\r
- }\r
- if (cred) {\r
- // Signed request.\r
- return encoder.encode(\r
- httpResponse,\r
- msg,\r
- destination,\r
- entity,\r
- relayState,\r
- &application,\r
- cred,\r
- sigalg.second,\r
- relyingParty->getXMLString("digestAlg").second\r
- );\r
- }\r
- else {\r
- m_log.warn("no signing credential resolved, leaving message unsigned");\r
- }\r
- }\r
- else {\r
- m_log.warn("no credential resolver installed, leaving message unsigned");\r
- }\r
- }\r
-\r
- // Unsigned request.\r
- return encoder.encode(httpResponse, msg, destination, entity, relayState, &application);\r
-}\r
-\r
-#endif\r
-\r
-void AbstractHandler::preserveRelayState(const Application& application, HTTPResponse& response, string& relayState) const\r
-{\r
- if (relayState.empty())\r
- return;\r
-\r
- // No setting means just pass it by value.\r
- pair<bool,const char*> mech=getString("relayState");\r
- if (!mech.first || !mech.second || !*mech.second)\r
- return;\r
-\r
- if (!strcmp(mech.second, "cookie")) {\r
- // Here we store the state in a cookie and send a fixed\r
- // value so we can recognize it on the way back.\r
- if (relayState.find("cookie:") != 0) {\r
- const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();\r
- pair<string,const char*> shib_cookie=application.getCookieNameProps("_shibstate_");\r
- string stateval = urlenc->encode(relayState.c_str()) + shib_cookie.second;\r
- // Generate a random key for the cookie name instead of the fixed name.\r
- string rsKey;\r
- generateRandomHex(rsKey,5);\r
- shib_cookie.first = "_shibstate_" + rsKey;\r
- response.setCookie(shib_cookie.first.c_str(),stateval.c_str());\r
- relayState = "cookie:" + rsKey;\r
- }\r
- }\r
- else if (strstr(mech.second,"ss:")==mech.second) {\r
- if (relayState.find("ss:") != 0) {\r
- mech.second+=3;\r
- if (*mech.second) {\r
- if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {\r
-#ifndef SHIBSP_LITE\r
- StorageService* storage = application.getServiceProvider().getStorageService(mech.second);\r
- if (storage) {\r
- string rsKey;\r
- generateRandomHex(rsKey,5);\r
- if (!storage->createString("RelayState", rsKey.c_str(), relayState.c_str(), time(NULL) + 600))\r
- throw IOException("Attempted to insert duplicate storage key.");\r
- relayState = string(mech.second-3) + ':' + rsKey;\r
- }\r
- else {\r
- m_log.error("Storage-backed RelayState with invalid StorageService ID (%s)", mech.second);\r
- relayState.erase();\r
- }\r
-#endif\r
- }\r
- else if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {\r
- DDF out,in = DDF("set::RelayState").structure();\r
- in.addmember("id").string(mech.second);\r
- in.addmember("value").unsafe_string(relayState.c_str());\r
- DDFJanitor jin(in),jout(out);\r
- out = application.getServiceProvider().getListenerService()->send(in);\r
- if (!out.isstring())\r
- throw IOException("StorageService-backed RelayState mechanism did not return a state key.");\r
- relayState = string(mech.second-3) + ':' + out.string();\r
- }\r
- }\r
- }\r
- }\r
- else\r
- throw ConfigurationException("Unsupported relayState mechanism ($1).", params(1,mech.second));\r
-}\r
-\r
-void AbstractHandler::recoverRelayState(\r
- const Application& application, const HTTPRequest& request, HTTPResponse& response, string& relayState, bool clear\r
- ) const\r
-{\r
- SPConfig& conf = SPConfig::getConfig();\r
-\r
- // Look for StorageService-backed state of the form "ss:SSID:key".\r
- const char* state = relayState.c_str();\r
- if (strstr(state,"ss:")==state) {\r
- state += 3;\r
- const char* key = strchr(state,':');\r
- if (key) {\r
- string ssid = relayState.substr(3, key - state);\r
- key++;\r
- if (!ssid.empty() && *key) {\r
- if (conf.isEnabled(SPConfig::OutOfProcess)) {\r
-#ifndef SHIBSP_LITE\r
- StorageService* storage = conf.getServiceProvider()->getStorageService(ssid.c_str());\r
- if (storage) {\r
- ssid = key;\r
- if (storage->readString("RelayState",ssid.c_str(),&relayState)>0) {\r
- if (clear)\r
- storage->deleteString("RelayState",ssid.c_str());\r
- return;\r
- }\r
- else\r
- relayState.erase();\r
- }\r
- else {\r
- m_log.error("Storage-backed RelayState with invalid StorageService ID (%s)", ssid.c_str());\r
- relayState.erase();\r
- }\r
-#endif\r
- }\r
- else if (conf.isEnabled(SPConfig::InProcess)) {\r
- DDF out,in = DDF("get::RelayState").structure();\r
- in.addmember("id").string(ssid.c_str());\r
- in.addmember("key").string(key);\r
- in.addmember("clear").integer(clear ? 1 : 0);\r
- DDFJanitor jin(in),jout(out);\r
- out = application.getServiceProvider().getListenerService()->send(in);\r
- if (!out.isstring()) {\r
- m_log.error("StorageService-backed RelayState mechanism did not return a state value.");\r
- relayState.erase();\r
- }\r
- else {\r
- relayState = out.string();\r
- return;\r
- }\r
- }\r
- }\r
- }\r
- }\r
-\r
- // Look for cookie-backed state of the form "cookie:key".\r
- if (strstr(state,"cookie:")==state) {\r
- state += 7;\r
- if (*state) {\r
- // Pull the value from the "relay state" cookie.\r
- pair<string,const char*> relay_cookie = application.getCookieNameProps("_shibstate_");\r
- relay_cookie.first = string("_shibstate_") + state;\r
- state = request.getCookie(relay_cookie.first.c_str());\r
- if (state && *state) {\r
- // URL-decode the value.\r
- char* rscopy=strdup(state);\r
- XMLToolingConfig::getConfig().getURLEncoder()->decode(rscopy);\r
- relayState = rscopy;\r
- free(rscopy);\r
-\r
- if (clear) {\r
- string exp(relay_cookie.second);\r
- exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";\r
- response.setCookie(relay_cookie.first.c_str(), exp.c_str());\r
- }\r
- return;\r
- }\r
- }\r
-\r
- relayState.erase();\r
- }\r
-\r
- // Check for "default" value (or the old "cookie" value that might come from stale bookmarks).\r
- if (relayState.empty() || relayState == "default" || relayState == "cookie") {\r
- pair<bool,const char*> homeURL=application.getString("homeURL");\r
- if (homeURL.first)\r
- relayState=homeURL.second;\r
- else {\r
- // Compute a URL to the root of the site.\r
- int port = request.getPort();\r
- const char* scheme = request.getScheme();\r
- relayState = string(scheme) + "://" + request.getHostname();\r
- if ((!strcmp(scheme,"http") && port!=80) || (!strcmp(scheme,"https") && port!=443)) {\r
- ostringstream portstr;\r
- portstr << port;\r
- relayState += ":" + portstr.str();\r
- }\r
- relayState += '/';\r
- }\r
- }\r
-}\r
-\r
-void AbstractHandler::preservePostData(\r
- const Application& application, const HTTPRequest& request, HTTPResponse& response, const char* relayState\r
- ) const\r
-{\r
-#ifdef HAVE_STRCASECMP\r
- if (strcasecmp(request.getMethod(), "POST")) return;\r
-#else\r
- if (stricmp(request.getMethod(), "POST")) return;\r
-#endif\r
-\r
- // No specs mean no save.\r
- const PropertySet* props=application.getPropertySet("Sessions");\r
- pair<bool,const char*> mech = props->getString("postData");\r
- if (!mech.first) {\r
- m_log.info("postData property not supplied, form data will not be preserved across SSO");\r
- return;\r
- }\r
-\r
- DDF postData = getPostData(application, request);\r
- if (postData.isnull())\r
- return;\r
-\r
- if (strstr(mech.second,"ss:") == mech.second) {\r
- mech.second+=3;\r
- if (!*mech.second) {\r
- postData.destroy();\r
- throw ConfigurationException("Unsupported postData mechanism ($1).", params(1, mech.second - 3));\r
- }\r
-\r
- string postkey;\r
- if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {\r
- DDFJanitor postjan(postData);\r
-#ifndef SHIBSP_LITE\r
- StorageService* storage = application.getServiceProvider().getStorageService(mech.second);\r
- if (storage) {\r
- // Use a random key\r
- string rsKey;\r
- SAMLConfig::getConfig().generateRandomBytes(rsKey,20);\r
- rsKey = SAMLArtifact::toHex(rsKey);\r
- ostringstream out;\r
- out << postData;\r
- if (!storage->createString("PostData", rsKey.c_str(), out.str().c_str(), time(NULL) + 600))\r
- throw IOException("Attempted to insert duplicate storage key.");\r
- postkey = string(mech.second-3) + ':' + rsKey;\r
- }\r
- else {\r
- m_log.error("storage-backed PostData mechanism with invalid StorageService ID (%s)", mech.second);\r
- }\r
-#endif\r
- }\r
- else if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {\r
- DDF out,in = DDF("set::PostData").structure();\r
- DDFJanitor jin(in),jout(out);\r
- in.addmember("id").string(mech.second);\r
- in.add(postData);\r
- out = application.getServiceProvider().getListenerService()->send(in);\r
- if (!out.isstring())\r
- throw IOException("StorageService-backed PostData mechanism did not return a state key.");\r
- postkey = string(mech.second-3) + ':' + out.string();\r
- }\r
-\r
- // Set a cookie with key info.\r
- pair<string,const char*> shib_cookie = getPostCookieNameProps(application, relayState);\r
- postkey += shib_cookie.second;\r
- response.setCookie(shib_cookie.first.c_str(), postkey.c_str());\r
- }\r
- else {\r
- postData.destroy();\r
- throw ConfigurationException("Unsupported postData mechanism ($1).", params(1,mech.second));\r
- }\r
-}\r
-\r
-DDF AbstractHandler::recoverPostData(\r
- const Application& application, const HTTPRequest& request, HTTPResponse& response, const char* relayState\r
- ) const\r
-{\r
- // First we need the post recovery cookie.\r
- pair<string,const char*> shib_cookie = getPostCookieNameProps(application, relayState);\r
- const char* cookie = request.getCookie(shib_cookie.first.c_str());\r
- if (!cookie || !*cookie)\r
- return DDF();\r
-\r
- // Clear the cookie.\r
- string exp(shib_cookie.second);\r
- exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";\r
- response.setCookie(shib_cookie.first.c_str(), exp.c_str());\r
-\r
- // Look for StorageService-backed state of the form "ss:SSID:key".\r
- const char* state = cookie;\r
- if (strstr(state, "ss:") == state) {\r
- state += 3;\r
- const char* key = strchr(state, ':');\r
- if (key) {\r
- string ssid = string(cookie).substr(3, key - state);\r
- key++;\r
- if (!ssid.empty() && *key) {\r
- SPConfig& conf = SPConfig::getConfig();\r
- if (conf.isEnabled(SPConfig::OutOfProcess)) {\r
-#ifndef SHIBSP_LITE\r
- StorageService* storage = conf.getServiceProvider()->getStorageService(ssid.c_str());\r
- if (storage) {\r
- if (storage->readString("PostData", key, &ssid) > 0) {\r
- storage->deleteString("PostData", key);\r
- istringstream inret(ssid);\r
- DDF ret;\r
- inret >> ret;\r
- return ret;\r
- }\r
- else {\r
- m_log.error("failed to recover form post data using key (%s)", key);\r
- }\r
- }\r
- else {\r
- m_log.error("storage-backed PostData with invalid StorageService ID (%s)", ssid.c_str());\r
- }\r
-#endif\r
- }\r
- else if (conf.isEnabled(SPConfig::InProcess)) {\r
- DDF in = DDF("get::PostData").structure();\r
- DDFJanitor jin(in);\r
- in.addmember("id").string(ssid.c_str());\r
- in.addmember("key").string(key);\r
- DDF out = application.getServiceProvider().getListenerService()->send(in);\r
- if (out.islist())\r
- return out;\r
- out.destroy();\r
- m_log.error("storageService-backed PostData mechanism did not return preserved data.");\r
- }\r
- }\r
- }\r
- }\r
- return DDF();\r
-}\r
-\r
-long AbstractHandler::sendPostResponse(\r
- const Application& application, HTTPResponse& httpResponse, const char* url, DDF& postData\r
- ) const\r
-{\r
- HTTPResponse::sanitizeURL(url);\r
-\r
- const PropertySet* props=application.getPropertySet("Sessions");\r
- pair<bool,const char*> postTemplate = props->getString("postTemplate");\r
- if (!postTemplate.first)\r
- throw ConfigurationException("Missing postTemplate property, unable to recreate form post.");\r
-\r
- string fname(postTemplate.second);\r
- ifstream infile(XMLToolingConfig::getConfig().getPathResolver()->resolve(fname, PathResolver::XMLTOOLING_CFG_FILE).c_str());\r
- if (!infile)\r
- throw ConfigurationException("Unable to access HTML template ($1).", params(1, fname.c_str()));\r
- TemplateParameters respParam;\r
- respParam.m_map["action"] = url;\r
-\r
- // Load the parameters into objects for the template.\r
- multimap<string,string>& collection = respParam.m_collectionMap["PostedData"];\r
- DDF param = postData.first();\r
- while (!param.isnull()) {\r
- collection.insert(pair<const string,string>(param.name(), (param.string() ? param.string() : "")));\r
- param = postData.next();\r
- }\r
-\r
- stringstream str;\r
- XMLToolingConfig::getConfig().getTemplateEngine()->run(infile, str, respParam);\r
-\r
- pair<bool,bool> postExpire = props->getBool("postExpire");\r
-\r
- httpResponse.setContentType("text/html");\r
- if (!postExpire.first || postExpire.second) {\r
- httpResponse.setResponseHeader("Expires", "01-Jan-1997 12:00:00 GMT");\r
- httpResponse.setResponseHeader("Cache-Control", "no-cache, no-store, must-revalidate, private");\r
- httpResponse.setResponseHeader("Pragma", "no-cache");\r
- }\r
- return httpResponse.sendResponse(str);\r
-}\r
-\r
-pair<string,const char*> AbstractHandler::getPostCookieNameProps(const Application& app, const char* relayState) const\r
-{\r
- // Decorates the name of the cookie with the relay state key, if any.\r
- // Doing so gives a better assurance that the recovered data really\r
- // belongs to the relayed request.\r
- pair<string,const char*> shib_cookie=app.getCookieNameProps("_shibpost_");\r
- if (strstr(relayState, "cookie:") == relayState) {\r
- shib_cookie.first = string("_shibpost_") + (relayState + 7);\r
- }\r
- else if (strstr(relayState, "ss:") == relayState) {\r
- const char* pch = strchr(relayState + 3, ':');\r
- if (pch)\r
- shib_cookie.first = string("_shibpost_") + (pch + 1);\r
- }\r
- return shib_cookie;\r
-}\r
-\r
-DDF AbstractHandler::getPostData(const Application& application, const HTTPRequest& request) const\r
-{\r
- string contentType = request.getContentType();\r
- if (contentType.compare("application/x-www-form-urlencoded") == 0) {\r
- const PropertySet* props=application.getPropertySet("Sessions");\r
- pair<bool,unsigned int> plimit = props->getUnsignedInt("postLimit");\r
- if (!plimit.first)\r
- plimit.second = 1024 * 1024;\r
- if (plimit.second == 0 || request.getContentLength() <= plimit.second) {\r
- CGIParser cgi(request);\r
- pair<CGIParser::walker,CGIParser::walker> params = cgi.getParameters(NULL);\r
- if (params.first == params.second)\r
- return DDF("parameters").list();\r
- DDF child;\r
- DDF ret = DDF("parameters").list();\r
- for (; params.first != params.second; ++params.first) {\r
- if (!params.first->first.empty()) {\r
- child = DDF(params.first->first.c_str()).unsafe_string(params.first->second);\r
- ret.add(child);\r
- }\r
- }\r
- return ret;\r
- }\r
- else {\r
- m_log.warn("POST limit exceeded, ignoring %d bytes of posted data", request.getContentLength());\r
- }\r
- }\r
- else {\r
- m_log.info("ignoring POST data with non-standard encoding (%s)", contentType.c_str());\r
- }\r
- return DDF();\r
-}\r
+/*
+ * Copyright 2001-2009 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * AbstractHandler.cpp
+ *
+ * Base class for handlers based on a DOMPropertySet.
+ */
+
+#include "internal.h"
+#include "exceptions.h"
+#include "Application.h"
+#include "ServiceProvider.h"
+#include "SPRequest.h"
+#include "handler/AbstractHandler.h"
+#include "handler/LogoutHandler.h"
+#include "remoting/ListenerService.h"
+#include "util/CGIParser.h"
+#include "util/SPConstants.h"
+#include "util/TemplateParameters.h"
+
+#include <vector>
+#include <fstream>
+#include <xmltooling/XMLToolingConfig.h>
+#include <xmltooling/util/PathResolver.h>
+#include <xmltooling/util/URLEncoder.h>
+
+
+#ifndef SHIBSP_LITE
+# include <saml/exceptions.h>
+# 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/security/Credential.h>
+# include <xmltooling/security/CredentialResolver.h>
+# include <xmltooling/util/StorageService.h>
+using namespace opensaml::saml2md;
+using namespace opensaml;
+#else
+# include "lite/SAMLConstants.h"
+#endif
+
+#include <xmltooling/XMLToolingConfig.h>
+#include <xmltooling/util/URLEncoder.h>
+
+using namespace shibsp;
+using namespace samlconstants;
+using namespace xmltooling;
+using namespace xercesc;
+using namespace std;
+
+namespace shibsp {
+ 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 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;
+ SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2LogoutFactory;
+ SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2NameIDMgmtFactory;
+ SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory AssertionLookupFactory;
+ SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory MetadataGeneratorFactory;
+ SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory StatusHandlerFactory;
+ SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SessionHandlerFactory;
+
+ void SHIBSP_DLLLOCAL generateRandomHex(std::string& buf, unsigned int len) {
+ static char DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
+ int r;
+ unsigned char b1,b2;
+ buf.erase();
+ for (unsigned int i=0; i<len; i+=4) {
+ r = rand();
+ b1 = (0x00FF & r);
+ b2 = (0xFF00 & r) >> 8;
+ buf += (DIGITS[(0xF0 & b1) >> 4 ]);
+ buf += (DIGITS[0x0F & b1]);
+ buf += (DIGITS[(0xF0 & b2) >> 4 ]);
+ buf += (DIGITS[0x0F & b2]);
+ }
+ }
+};
+
+void SHIBSP_API shibsp::registerHandlers()
+{
+ SPConfig& conf=SPConfig::getConfig();
+
+ conf.AssertionConsumerServiceManager.registerFactory(SAML1_PROFILE_BROWSER_ARTIFACT, SAML1ConsumerFactory);
+ conf.AssertionConsumerServiceManager.registerFactory(SAML1_PROFILE_BROWSER_POST, SAML1ConsumerFactory);
+ conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_POST, SAML2ConsumerFactory);
+ conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_POST_SIMPLESIGN, SAML2ConsumerFactory);
+ conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_ARTIFACT, SAML2ConsumerFactory);
+ conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_PAOS, SAML2ConsumerFactory);
+
+ conf.ArtifactResolutionServiceManager.registerFactory(SAML20_BINDING_SOAP, SAML2ArtifactResolutionFactory);
+
+ conf.HandlerManager.registerFactory(SAML20_BINDING_URI, AssertionLookupFactory);
+ conf.HandlerManager.registerFactory(METADATA_GENERATOR_HANDLER, MetadataGeneratorFactory);
+ conf.HandlerManager.registerFactory(STATUS_HANDLER, StatusHandlerFactory);
+ conf.HandlerManager.registerFactory(SESSION_HANDLER, SessionHandlerFactory);
+
+ conf.LogoutInitiatorManager.registerFactory(CHAINING_LOGOUT_INITIATOR, ChainingLogoutInitiatorFactory);
+ conf.LogoutInitiatorManager.registerFactory(LOCAL_LOGOUT_INITIATOR, LocalLogoutInitiatorFactory);
+ conf.LogoutInitiatorManager.registerFactory(SAML2_LOGOUT_INITIATOR, SAML2LogoutInitiatorFactory);
+ conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_SOAP, SAML2LogoutFactory);
+ conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_HTTP_REDIRECT, SAML2LogoutFactory);
+ conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_HTTP_POST, SAML2LogoutFactory);
+ conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_HTTP_POST_SIMPLESIGN, SAML2LogoutFactory);
+ conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_HTTP_ARTIFACT, SAML2LogoutFactory);
+
+ conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_SOAP, SAML2NameIDMgmtFactory);
+ conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_HTTP_REDIRECT, SAML2NameIDMgmtFactory);
+ conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_HTTP_POST, SAML2NameIDMgmtFactory);
+ conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_HTTP_POST_SIMPLESIGN, SAML2NameIDMgmtFactory);
+ conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_HTTP_ARTIFACT, SAML2NameIDMgmtFactory);
+}
+
+Handler::Handler()
+{
+}
+
+Handler::~Handler()
+{
+}
+
+AbstractHandler::AbstractHandler(
+ const DOMElement* e, Category& log, DOMNodeFilter* filter, const map<string,string>* remapper
+ ) : m_log(log), m_configNS(shibspconstants::SHIB2SPCONFIG_NS) {
+ load(e,NULL,filter,remapper);
+}
+
+AbstractHandler::~AbstractHandler()
+{
+}
+
+#ifndef SHIBSP_LITE
+
+const char* Handler::getType() const
+{
+ return getString("type").second;
+}
+
+void AbstractHandler::checkError(const XMLObject* response, const saml2md::RoleDescriptor* role) const
+{
+ const saml2p::StatusResponseType* r2 = dynamic_cast<const saml2p::StatusResponseType*>(response);
+ if (r2) {
+ const saml2p::Status* status = r2->getStatus();
+ if (status) {
+ const saml2p::StatusCode* sc = status->getStatusCode();
+ const XMLCh* code = sc ? sc->getValue() : NULL;
+ if (code && !XMLString::equals(code,saml2p::StatusCode::SUCCESS)) {
+ FatalProfileException ex("SAML response contained an error.");
+ annotateException(&ex, role, status); // throws it
+ }
+ }
+ }
+
+ const saml1p::Response* r1 = dynamic_cast<const saml1p::Response*>(response);
+ if (r1) {
+ const saml1p::Status* status = r1->getStatus();
+ if (status) {
+ const saml1p::StatusCode* sc = status->getStatusCode();
+ const xmltooling::QName* code = sc ? sc->getValue() : NULL;
+ if (code && *code != saml1p::StatusCode::SUCCESS) {
+ FatalProfileException ex("SAML response contained an error.");
+ ex.addProperty("statusCode", code->toString().c_str());
+ if (sc->getStatusCode()) {
+ code = sc->getStatusCode()->getValue();
+ if (code)
+ ex.addProperty("statusCode2", code->toString().c_str());
+ }
+ if (status->getStatusMessage()) {
+ auto_ptr_char msg(status->getStatusMessage()->getMessage());
+ if (msg.get() && *msg.get())
+ ex.addProperty("statusMessage", msg.get());
+ }
+ ex.raise();
+ }
+ }
+ }
+}
+
+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,
+ 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,(const char*)"true") : relyingParty->getString("signing");
+ 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);
+ const Credential* cred = NULL;
+ pair<bool,const char*> keyName = relyingParty->getString("keyName");
+ pair<bool,const XMLCh*> sigalg = relyingParty->getXMLString("signingAlg");
+ if (role) {
+ MetadataCredentialCriteria mcc(*role);
+ mcc.setUsage(Credential::SIGNING_CREDENTIAL);
+ if (keyName.first)
+ mcc.getKeyNames().insert(keyName.second);
+ if (sigalg.first)
+ mcc.setXMLAlgorithm(sigalg.second);
+ cred = credResolver->resolve(&mcc);
+ }
+ else {
+ CredentialCriteria cc;
+ cc.setUsage(Credential::SIGNING_CREDENTIAL);
+ if (keyName.first)
+ cc.getKeyNames().insert(keyName.second);
+ if (sigalg.first)
+ cc.setXMLAlgorithm(sigalg.second);
+ cred = credResolver->resolve(&cc);
+ }
+ 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())
+ return;
+
+ // No setting means just pass it by value.
+ pair<bool,const char*> mech=getString("relayState");
+ if (!mech.first || !mech.second || !*mech.second)
+ return;
+
+ if (!strcmp(mech.second, "cookie")) {
+ // Here we store the state in a cookie and send a fixed
+ // value so we can recognize it on the way back.
+ if (relayState.find("cookie:") != 0) {
+ const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
+ pair<string,const char*> shib_cookie=application.getCookieNameProps("_shibstate_");
+ string stateval = urlenc->encode(relayState.c_str()) + shib_cookie.second;
+ // Generate a random key for the cookie name instead of the fixed name.
+ string rsKey;
+ generateRandomHex(rsKey,5);
+ shib_cookie.first = "_shibstate_" + rsKey;
+ response.setCookie(shib_cookie.first.c_str(),stateval.c_str());
+ relayState = "cookie:" + rsKey;
+ }
+ }
+ else if (strstr(mech.second,"ss:")==mech.second) {
+ if (relayState.find("ss:") != 0) {
+ 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;
+ generateRandomHex(rsKey,5);
+ 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();
+ in.addmember("id").string(mech.second);
+ in.addmember("value").unsafe_string(relayState.c_str());
+ DDFJanitor jin(in),jout(out);
+ out = application.getServiceProvider().getListenerService()->send(in);
+ if (!out.isstring())
+ throw IOException("StorageService-backed RelayState mechanism did not return a state key.");
+ relayState = string(mech.second-3) + ':' + out.string();
+ }
+ }
+ }
+ }
+ else
+ throw ConfigurationException("Unsupported relayState mechanism ($1).", params(1,mech.second));
+}
+
+void AbstractHandler::recoverRelayState(
+ const Application& application, const HTTPRequest& request, HTTPResponse& response, string& relayState, bool clear
+ ) const
+{
+ SPConfig& conf = SPConfig::getConfig();
+
+ // Look for StorageService-backed state of the form "ss:SSID:key".
+ const char* state = relayState.c_str();
+ if (strstr(state,"ss:")==state) {
+ state += 3;
+ const char* key = strchr(state,':');
+ if (key) {
+ string ssid = relayState.substr(3, key - state);
+ key++;
+ if (!ssid.empty() && *key) {
+ if (conf.isEnabled(SPConfig::OutOfProcess)) {
+#ifndef SHIBSP_LITE
+ StorageService* storage = conf.getServiceProvider()->getStorageService(ssid.c_str());
+ if (storage) {
+ ssid = key;
+ if (storage->readString("RelayState",ssid.c_str(),&relayState)>0) {
+ if (clear)
+ storage->deleteString("RelayState",ssid.c_str());
+ return;
+ }
+ else
+ relayState.erase();
+ }
+ else {
+ m_log.error("Storage-backed RelayState with invalid StorageService ID (%s)", ssid.c_str());
+ relayState.erase();
+ }
+#endif
+ }
+ else if (conf.isEnabled(SPConfig::InProcess)) {
+ DDF out,in = DDF("get::RelayState").structure();
+ in.addmember("id").string(ssid.c_str());
+ in.addmember("key").string(key);
+ in.addmember("clear").integer(clear ? 1 : 0);
+ DDFJanitor jin(in),jout(out);
+ out = application.getServiceProvider().getListenerService()->send(in);
+ if (!out.isstring()) {
+ m_log.error("StorageService-backed RelayState mechanism did not return a state value.");
+ relayState.erase();
+ }
+ else {
+ relayState = out.string();
+ return;
+ }
+ }
+ }
+ }
+ }
+
+ // Look for cookie-backed state of the form "cookie:key".
+ if (strstr(state,"cookie:")==state) {
+ state += 7;
+ if (*state) {
+ // Pull the value from the "relay state" cookie.
+ pair<string,const char*> relay_cookie = application.getCookieNameProps("_shibstate_");
+ relay_cookie.first = string("_shibstate_") + state;
+ state = request.getCookie(relay_cookie.first.c_str());
+ if (state && *state) {
+ // URL-decode the value.
+ char* rscopy=strdup(state);
+ XMLToolingConfig::getConfig().getURLEncoder()->decode(rscopy);
+ relayState = rscopy;
+ free(rscopy);
+
+ if (clear) {
+ string exp(relay_cookie.second);
+ exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
+ response.setCookie(relay_cookie.first.c_str(), exp.c_str());
+ }
+ return;
+ }
+ }
+
+ relayState.erase();
+ }
+
+ // Check for "default" value (or the old "cookie" value that might come from stale bookmarks).
+ if (relayState.empty() || relayState == "default" || relayState == "cookie") {
+ pair<bool,const char*> homeURL=application.getString("homeURL");
+ if (homeURL.first)
+ relayState=homeURL.second;
+ else {
+ // Compute a URL to the root of the site.
+ int port = request.getPort();
+ const char* scheme = request.getScheme();
+ relayState = string(scheme) + "://" + request.getHostname();
+ if ((!strcmp(scheme,"http") && port!=80) || (!strcmp(scheme,"https") && port!=443)) {
+ ostringstream portstr;
+ portstr << port;
+ relayState += ":" + portstr.str();
+ }
+ relayState += '/';
+ }
+ }
+}
+
+void AbstractHandler::preservePostData(
+ const Application& application, const HTTPRequest& request, HTTPResponse& response, const char* relayState
+ ) const
+{
+#ifdef HAVE_STRCASECMP
+ if (strcasecmp(request.getMethod(), "POST")) return;
+#else
+ if (stricmp(request.getMethod(), "POST")) return;
+#endif
+
+ // No specs mean no save.
+ const PropertySet* props=application.getPropertySet("Sessions");
+ pair<bool,const char*> mech = props->getString("postData");
+ if (!mech.first) {
+ m_log.info("postData property not supplied, form data will not be preserved across SSO");
+ return;
+ }
+
+ DDF postData = getPostData(application, request);
+ if (postData.isnull())
+ return;
+
+ if (strstr(mech.second,"ss:") == mech.second) {
+ mech.second+=3;
+ if (!*mech.second) {
+ postData.destroy();
+ throw ConfigurationException("Unsupported postData mechanism ($1).", params(1, mech.second - 3));
+ }
+
+ string postkey;
+ if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
+ DDFJanitor postjan(postData);
+#ifndef SHIBSP_LITE
+ StorageService* storage = application.getServiceProvider().getStorageService(mech.second);
+ if (storage) {
+ // Use a random key
+ string rsKey;
+ SAMLConfig::getConfig().generateRandomBytes(rsKey,20);
+ rsKey = SAMLArtifact::toHex(rsKey);
+ ostringstream out;
+ out << postData;
+ if (!storage->createString("PostData", rsKey.c_str(), out.str().c_str(), time(NULL) + 600))
+ throw IOException("Attempted to insert duplicate storage key.");
+ postkey = string(mech.second-3) + ':' + rsKey;
+ }
+ else {
+ m_log.error("storage-backed PostData mechanism with invalid StorageService ID (%s)", mech.second);
+ }
+#endif
+ }
+ else if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
+ DDF out,in = DDF("set::PostData").structure();
+ DDFJanitor jin(in),jout(out);
+ in.addmember("id").string(mech.second);
+ in.add(postData);
+ out = application.getServiceProvider().getListenerService()->send(in);
+ if (!out.isstring())
+ throw IOException("StorageService-backed PostData mechanism did not return a state key.");
+ postkey = string(mech.second-3) + ':' + out.string();
+ }
+
+ // Set a cookie with key info.
+ pair<string,const char*> shib_cookie = getPostCookieNameProps(application, relayState);
+ postkey += shib_cookie.second;
+ response.setCookie(shib_cookie.first.c_str(), postkey.c_str());
+ }
+ else {
+ postData.destroy();
+ throw ConfigurationException("Unsupported postData mechanism ($1).", params(1,mech.second));
+ }
+}
+
+DDF AbstractHandler::recoverPostData(
+ const Application& application, const HTTPRequest& request, HTTPResponse& response, const char* relayState
+ ) const
+{
+ // First we need the post recovery cookie.
+ pair<string,const char*> shib_cookie = getPostCookieNameProps(application, relayState);
+ const char* cookie = request.getCookie(shib_cookie.first.c_str());
+ if (!cookie || !*cookie)
+ return DDF();
+
+ // Clear the cookie.
+ string exp(shib_cookie.second);
+ exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
+ response.setCookie(shib_cookie.first.c_str(), exp.c_str());
+
+ // Look for StorageService-backed state of the form "ss:SSID:key".
+ const char* state = cookie;
+ if (strstr(state, "ss:") == state) {
+ state += 3;
+ const char* key = strchr(state, ':');
+ if (key) {
+ string ssid = string(cookie).substr(3, key - state);
+ key++;
+ if (!ssid.empty() && *key) {
+ SPConfig& conf = SPConfig::getConfig();
+ if (conf.isEnabled(SPConfig::OutOfProcess)) {
+#ifndef SHIBSP_LITE
+ StorageService* storage = conf.getServiceProvider()->getStorageService(ssid.c_str());
+ if (storage) {
+ if (storage->readString("PostData", key, &ssid) > 0) {
+ storage->deleteString("PostData", key);
+ istringstream inret(ssid);
+ DDF ret;
+ inret >> ret;
+ return ret;
+ }
+ else {
+ m_log.error("failed to recover form post data using key (%s)", key);
+ }
+ }
+ else {
+ m_log.error("storage-backed PostData with invalid StorageService ID (%s)", ssid.c_str());
+ }
+#endif
+ }
+ else if (conf.isEnabled(SPConfig::InProcess)) {
+ DDF in = DDF("get::PostData").structure();
+ DDFJanitor jin(in);
+ in.addmember("id").string(ssid.c_str());
+ in.addmember("key").string(key);
+ DDF out = application.getServiceProvider().getListenerService()->send(in);
+ if (out.islist())
+ return out;
+ out.destroy();
+ m_log.error("storageService-backed PostData mechanism did not return preserved data.");
+ }
+ }
+ }
+ }
+ return DDF();
+}
+
+long AbstractHandler::sendPostResponse(
+ const Application& application, HTTPResponse& httpResponse, const char* url, DDF& postData
+ ) const
+{
+ HTTPResponse::sanitizeURL(url);
+
+ const PropertySet* props=application.getPropertySet("Sessions");
+ pair<bool,const char*> postTemplate = props->getString("postTemplate");
+ if (!postTemplate.first)
+ throw ConfigurationException("Missing postTemplate property, unable to recreate form post.");
+
+ string fname(postTemplate.second);
+ ifstream infile(XMLToolingConfig::getConfig().getPathResolver()->resolve(fname, PathResolver::XMLTOOLING_CFG_FILE).c_str());
+ if (!infile)
+ throw ConfigurationException("Unable to access HTML template ($1).", params(1, fname.c_str()));
+ TemplateParameters respParam;
+ respParam.m_map["action"] = url;
+
+ // Load the parameters into objects for the template.
+ multimap<string,string>& collection = respParam.m_collectionMap["PostedData"];
+ DDF param = postData.first();
+ while (!param.isnull()) {
+ collection.insert(pair<const string,string>(param.name(), (param.string() ? param.string() : "")));
+ param = postData.next();
+ }
+
+ stringstream str;
+ XMLToolingConfig::getConfig().getTemplateEngine()->run(infile, str, respParam);
+
+ pair<bool,bool> postExpire = props->getBool("postExpire");
+
+ httpResponse.setContentType("text/html");
+ if (!postExpire.first || postExpire.second) {
+ httpResponse.setResponseHeader("Expires", "01-Jan-1997 12:00:00 GMT");
+ httpResponse.setResponseHeader("Cache-Control", "no-cache, no-store, must-revalidate, private");
+ httpResponse.setResponseHeader("Pragma", "no-cache");
+ }
+ return httpResponse.sendResponse(str);
+}
+
+pair<string,const char*> AbstractHandler::getPostCookieNameProps(const Application& app, const char* relayState) const
+{
+ // Decorates the name of the cookie with the relay state key, if any.
+ // Doing so gives a better assurance that the recovered data really
+ // belongs to the relayed request.
+ pair<string,const char*> shib_cookie=app.getCookieNameProps("_shibpost_");
+ if (strstr(relayState, "cookie:") == relayState) {
+ shib_cookie.first = string("_shibpost_") + (relayState + 7);
+ }
+ else if (strstr(relayState, "ss:") == relayState) {
+ const char* pch = strchr(relayState + 3, ':');
+ if (pch)
+ shib_cookie.first = string("_shibpost_") + (pch + 1);
+ }
+ return shib_cookie;
+}
+
+DDF AbstractHandler::getPostData(const Application& application, const HTTPRequest& request) const
+{
+ string contentType = request.getContentType();
+ if (contentType.compare("application/x-www-form-urlencoded") == 0) {
+ const PropertySet* props=application.getPropertySet("Sessions");
+ pair<bool,unsigned int> plimit = props->getUnsignedInt("postLimit");
+ if (!plimit.first)
+ plimit.second = 1024 * 1024;
+ if (plimit.second == 0 || request.getContentLength() <= plimit.second) {
+ CGIParser cgi(request);
+ pair<CGIParser::walker,CGIParser::walker> params = cgi.getParameters(NULL);
+ if (params.first == params.second)
+ return DDF("parameters").list();
+ DDF child;
+ DDF ret = DDF("parameters").list();
+ for (; params.first != params.second; ++params.first) {
+ if (!params.first->first.empty()) {
+ child = DDF(params.first->first.c_str()).unsafe_string(params.first->second);
+ ret.add(child);
+ }
+ }
+ return ret;
+ }
+ else {
+ m_log.warn("POST limit exceeded, ignoring %d bytes of posted data", request.getContentLength());
+ }
+ }
+ else {
+ m_log.info("ignoring POST data with non-standard encoding (%s)", contentType.c_str());
+ }
+ return DDF();
+}