2 * Licensed to the University Corporation for Advanced Internet
3 * Development, Inc. (UCAID) under one or more contributor license
4 * agreements. See the NOTICE file distributed with this work for
5 * additional information regarding copyright ownership.
7 * UCAID licenses this file to you under the Apache License,
8 * Version 2.0 (the "License"); you may not use this file except
9 * in compliance with the License. You may obtain a copy of the
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17 * either express or implied. See the License for the specific
18 * language governing permissions and limitations under the License.
24 * Base class for handlers based on a DOMPropertySet.
28 #include "exceptions.h"
29 #include "Application.h"
30 #include "ServiceProvider.h"
31 #include "SPRequest.h"
32 #include "handler/AbstractHandler.h"
33 #include "handler/LogoutHandler.h"
34 #include "remoting/ListenerService.h"
35 #include "util/CGIParser.h"
36 #include "util/SPConstants.h"
37 #include "util/TemplateParameters.h"
41 #include <boost/bind.hpp>
42 #include <boost/lexical_cast.hpp>
43 #include <boost/algorithm/string.hpp>
44 #include <xmltooling/XMLToolingConfig.h>
45 #include <xmltooling/util/PathResolver.h>
46 #include <xmltooling/util/URLEncoder.h>
50 # include <saml/exceptions.h>
51 # include <saml/SAMLConfig.h>
52 # include <saml/binding/SAMLArtifact.h>
53 # include <saml/saml1/core/Protocols.h>
54 # include <saml/saml2/core/Protocols.h>
55 # include <saml/saml2/metadata/Metadata.h>
56 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
57 # include <saml/util/SAMLConstants.h>
58 # include <xmltooling/security/Credential.h>
59 # include <xmltooling/security/CredentialResolver.h>
60 # include <xmltooling/util/StorageService.h>
61 using namespace opensaml::saml2md;
62 using namespace opensaml;
64 # include "lite/SAMLConstants.h"
67 #include <xmltooling/XMLToolingConfig.h>
68 #include <xmltooling/util/URLEncoder.h>
70 using namespace shibsp;
71 using namespace samlconstants;
72 using namespace xmltooling;
73 using namespace xercesc;
74 using namespace boost;
78 SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML1ConsumerFactory;
79 SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2ConsumerFactory;
80 SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2ArtifactResolutionFactory;
81 SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2LogoutFactory;
82 SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2NameIDMgmtFactory;
83 SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory AssertionLookupFactory;
84 SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory AttributeCheckerFactory;
85 SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory DiscoveryFeedFactory;
86 SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory ExternalAuthFactory;
87 SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory MetadataGeneratorFactory;
88 SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory StatusHandlerFactory;
89 SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SessionHandlerFactory;
92 void SHIBSP_DLLLOCAL generateRandomHex(std::string& buf, unsigned int len) {
93 static char DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
97 for (unsigned int i=0; i<len; i+=4) {
100 b2 = (0xFF00 & r) >> 8;
101 buf += (DIGITS[(0xF0 & b1) >> 4 ]);
102 buf += (DIGITS[0x0F & b1]);
103 buf += (DIGITS[(0xF0 & b2) >> 4 ]);
104 buf += (DIGITS[0x0F & b2]);
109 void SHIBSP_API shibsp::registerHandlers()
111 SPConfig& conf=SPConfig::getConfig();
113 conf.AssertionConsumerServiceManager.registerFactory(SAML1_ASSERTION_CONSUMER_SERVICE, SAML1ConsumerFactory);
114 conf.AssertionConsumerServiceManager.registerFactory(SAML1_PROFILE_BROWSER_ARTIFACT, SAML1ConsumerFactory);
115 conf.AssertionConsumerServiceManager.registerFactory(SAML1_PROFILE_BROWSER_POST, SAML1ConsumerFactory);
116 conf.AssertionConsumerServiceManager.registerFactory(SAML20_ASSERTION_CONSUMER_SERVICE, SAML2ConsumerFactory);
117 conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_POST, SAML2ConsumerFactory);
118 conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_POST_SIMPLESIGN, SAML2ConsumerFactory);
119 conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_ARTIFACT, SAML2ConsumerFactory);
120 conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_PAOS, SAML2ConsumerFactory);
122 conf.ArtifactResolutionServiceManager.registerFactory(SAML20_ARTIFACT_RESOLUTION_SERVICE, SAML2ArtifactResolutionFactory);
123 conf.ArtifactResolutionServiceManager.registerFactory(SAML20_BINDING_SOAP, SAML2ArtifactResolutionFactory);
125 conf.HandlerManager.registerFactory(SAML20_BINDING_URI, AssertionLookupFactory);
126 conf.HandlerManager.registerFactory(ATTR_CHECKER_HANDLER, AttributeCheckerFactory);
127 conf.HandlerManager.registerFactory(DISCOVERY_FEED_HANDLER, DiscoveryFeedFactory);
128 conf.HandlerManager.registerFactory(EXTERNAL_AUTH_HANDLER, ExternalAuthFactory);
129 conf.HandlerManager.registerFactory(METADATA_GENERATOR_HANDLER, MetadataGeneratorFactory);
130 conf.HandlerManager.registerFactory(STATUS_HANDLER, StatusHandlerFactory);
131 conf.HandlerManager.registerFactory(SESSION_HANDLER, SessionHandlerFactory);
133 conf.SingleLogoutServiceManager.registerFactory(SAML20_LOGOUT_HANDLER, SAML2LogoutFactory);
134 conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_SOAP, SAML2LogoutFactory);
135 conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_HTTP_REDIRECT, SAML2LogoutFactory);
136 conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_HTTP_POST, SAML2LogoutFactory);
137 conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_HTTP_POST_SIMPLESIGN, SAML2LogoutFactory);
138 conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_HTTP_ARTIFACT, SAML2LogoutFactory);
140 conf.ManageNameIDServiceManager.registerFactory(SAML20_NAMEID_MGMT_SERVICE, SAML2NameIDMgmtFactory);
141 conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_SOAP, SAML2NameIDMgmtFactory);
142 conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_HTTP_REDIRECT, SAML2NameIDMgmtFactory);
143 conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_HTTP_POST, SAML2NameIDMgmtFactory);
144 conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_HTTP_POST_SIMPLESIGN, SAML2NameIDMgmtFactory);
145 conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_HTTP_ARTIFACT, SAML2NameIDMgmtFactory);
158 void Handler::generateMetadata(SPSSODescriptor& role, const char* handlerURL) const
164 const XMLCh* Handler::getProtocolFamily() const
169 void Handler::log(SPRequest::SPLogLevel level, const string& msg) const
171 Category::getInstance(SHIBSP_LOGCAT".Handler").log(
172 (level == SPRequest::SPDebug ? Priority::DEBUG :
173 (level == SPRequest::SPInfo ? Priority::INFO :
174 (level == SPRequest::SPWarn ? Priority::WARN :
175 (level == SPRequest::SPError ? Priority::ERROR : Priority::CRIT)))),
180 void Handler::cleanRelayState(
181 const Application& application, const xmltooling::HTTPRequest& request, xmltooling::HTTPResponse& response
184 // Only cookie-based relay state requires cleaning.
185 pair<bool,const char*> mech = getString("relayState");
187 // Check for setting on Sessions element.
188 const PropertySet* sessionprop = application.getPropertySet("Sessions");
190 mech = sessionprop->getString("relayState");
192 if (!mech.first || !mech.second || strncmp(mech.second, "cookie", 6))
195 int maxCookies = 25,purgedCookies = 0;
197 if (*mech.second == ':' && isdigit(*(++mech.second))) {
198 maxCookies = atoi(mech.second);
205 // Walk the list of cookies backwards by name.
206 const map<string,string>& cookies = request.getCookies();
207 for (map<string,string>::const_reverse_iterator i = cookies.rbegin(); i != cookies.rend(); ++i) {
208 // Process relay state cookies only.
209 if (starts_with(i->first, "_shibstate_")) {
210 if (maxCookies > 0) {
211 // Keep it, but count it against the limit.
215 // We're over the limit, so everything here and older gets cleaned up.
217 exp = string(application.getCookieNameProps("_shibstate_").second) + "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
218 response.setCookie(i->first.c_str(), exp.c_str());
224 if (purgedCookies > 0)
225 log(SPRequest::SPDebug, string("purged ") + lexical_cast<string>(purgedCookies) + " stale relay state cookie(s) from client");
228 void Handler::preserveRelayState(const Application& application, HTTPResponse& response, string& relayState) const
230 // The empty string implies no state to deal with.
231 if (relayState.empty())
234 // No setting means just pass state by value.
235 pair<bool,const char*> mech = getString("relayState");
237 // Check for setting on Sessions element.
238 const PropertySet* sessionprop = application.getPropertySet("Sessions");
240 mech = sessionprop->getString("relayState");
242 if (!mech.first || !mech.second || !*mech.second)
245 if (!strncmp(mech.second, "cookie", 6)) {
246 // Here we store the state in a cookie and send a fixed
247 // value so we can recognize it on the way back.
248 if (relayState.find("cookie:") != 0) {
249 pair<string,const char*> shib_cookie = application.getCookieNameProps("_shibstate_");
250 string stateval = XMLToolingConfig::getConfig().getURLEncoder()->encode(relayState.c_str()) + shib_cookie.second;
251 // Generate a random key for the cookie name instead of the fixed name.
253 generateRandomHex(rsKey, 4);
254 rsKey = lexical_cast<string>(time(nullptr)) + '_' + rsKey;
255 shib_cookie.first = "_shibstate_" + rsKey;
256 response.setCookie(shib_cookie.first.c_str(), stateval.c_str());
257 relayState = "cookie:" + rsKey;
260 else if (!strncmp(mech.second, "ss:", 3)) {
261 if (relayState.find("ss:") != 0) {
264 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
266 StorageService* storage = application.getServiceProvider().getStorageService(mech.second);
270 SAMLConfig::getConfig().generateRandomBytes(rsKey,32);
271 rsKey = SAMLArtifact::toHex(rsKey);
272 if (relayState.length() <= storage->getCapabilities().getStringSize()) {
273 if (!storage->createString("RelayState", rsKey.c_str(), relayState.c_str(), time(nullptr) + 600))
274 throw IOException("Collision generating in-memory relay state key.");
277 if (!storage->createText("RelayState", rsKey.c_str(), relayState.c_str(), time(nullptr) + 600))
278 throw IOException("Collision generating in-memory relay state key.");
280 relayState = string(mech.second-3) + ':' + rsKey;
283 string msg("Storage-backed RelayState with invalid StorageService ID (");
284 msg = msg + mech.second+ ')';
285 log(SPRequest::SPError, msg);
289 throw ConfigurationException("Lite version of library cannot be used out of process.");
292 else if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
293 DDF out,in = DDF("set::RelayState").structure();
294 in.addmember("id").string(mech.second);
295 in.addmember("value").unsafe_string(relayState.c_str());
296 DDFJanitor jin(in),jout(out);
297 out = application.getServiceProvider().getListenerService()->send(in);
299 throw IOException("StorageService-backed RelayState mechanism did not return a state key.");
300 relayState = string(mech.second-3) + ':' + out.string();
306 throw ConfigurationException("Unsupported relayState mechanism ($1).", params(1,mech.second));
309 void Handler::recoverRelayState(
310 const Application& application, const HTTPRequest& request, HTTPResponse& response, string& relayState, bool clear
313 SPConfig& conf = SPConfig::getConfig();
315 // Look for StorageService-backed state of the form "ss:SSID:key".
316 const char* state = relayState.c_str();
317 if (strstr(state,"ss:")==state) {
319 const char* key = strchr(state,':');
321 string ssid = relayState.substr(3, key - state);
323 if (!ssid.empty() && *key) {
324 if (conf.isEnabled(SPConfig::OutOfProcess)) {
326 StorageService* storage = conf.getServiceProvider()->getStorageService(ssid.c_str());
329 if (storage->readString("RelayState",ssid.c_str(),&relayState) > 0) {
331 storage->deleteString("RelayState",ssid.c_str());
332 request.absolutize(relayState);
335 else if (storage->readText("RelayState",ssid.c_str(),&relayState) > 0) {
337 storage->deleteText("RelayState",ssid.c_str());
338 request.absolutize(relayState);
346 string msg("Storage-backed RelayState with invalid StorageService ID (");
348 log(SPRequest::SPError, msg);
353 else if (conf.isEnabled(SPConfig::InProcess)) {
354 DDF out,in = DDF("get::RelayState").structure();
355 in.addmember("id").string(ssid.c_str());
356 in.addmember("key").string(key);
357 in.addmember("clear").integer(clear ? 1 : 0);
358 DDFJanitor jin(in),jout(out);
359 out = application.getServiceProvider().getListenerService()->send(in);
360 if (!out.isstring()) {
361 log(SPRequest::SPError, "StorageService-backed RelayState mechanism did not return a state value.");
365 relayState = out.string();
366 request.absolutize(relayState);
374 // Look for cookie-backed state of the form "cookie:timestamp_key".
375 if (strstr(state,"cookie:")==state) {
378 // Pull the value from the "relay state" cookie.
379 pair<string,const char*> relay_cookie = application.getCookieNameProps("_shibstate_");
380 relay_cookie.first = string("_shibstate_") + state;
381 state = request.getCookie(relay_cookie.first.c_str());
382 if (state && *state) {
383 // URL-decode the value.
384 char* rscopy = strdup(state);
385 XMLToolingConfig::getConfig().getURLEncoder()->decode(rscopy);
389 string exp(relay_cookie.second);
390 exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
391 response.setCookie(relay_cookie.first.c_str(), exp.c_str());
393 request.absolutize(relayState);
401 // Check for "default" value (or the old "cookie" value that might come from stale bookmarks).
402 if (relayState.empty() || relayState == "default" || relayState == "cookie") {
403 pair<bool,const char*> homeURL=application.getString("homeURL");
405 relayState = homeURL.second;
410 request.absolutize(relayState);
413 AbstractHandler::AbstractHandler(
414 const DOMElement* e, Category& log, DOMNodeFilter* filter, const map<string,string>* remapper
415 ) : m_log(log), m_configNS(shibspconstants::SHIB2SPCONFIG_NS) {
416 load(e, nullptr, filter, remapper);
419 AbstractHandler::~AbstractHandler()
423 void AbstractHandler::log(SPRequest::SPLogLevel level, const string& msg) const
426 (level == SPRequest::SPDebug ? Priority::DEBUG :
427 (level == SPRequest::SPInfo ? Priority::INFO :
428 (level == SPRequest::SPWarn ? Priority::WARN :
429 (level == SPRequest::SPError ? Priority::ERROR : Priority::CRIT)))),
436 const char* Handler::getType() const
438 return getString("type").second;
441 void AbstractHandler::checkError(const XMLObject* response, const saml2md::RoleDescriptor* role) const
443 const saml2p::StatusResponseType* r2 = dynamic_cast<const saml2p::StatusResponseType*>(response);
445 const saml2p::Status* status = r2->getStatus();
447 const saml2p::StatusCode* sc = status->getStatusCode();
448 const XMLCh* code = sc ? sc->getValue() : nullptr;
449 if (code && !XMLString::equals(code,saml2p::StatusCode::SUCCESS)) {
450 FatalProfileException ex("SAML response contained an error.");
451 annotateException(&ex, role, status); // throws it
456 const saml1p::Response* r1 = dynamic_cast<const saml1p::Response*>(response);
458 const saml1p::Status* status = r1->getStatus();
460 const saml1p::StatusCode* sc = status->getStatusCode();
461 const xmltooling::QName* code = sc ? sc->getValue() : nullptr;
462 if (code && *code != saml1p::StatusCode::SUCCESS) {
463 FatalProfileException ex("SAML response contained an error.");
464 annotateException(&ex, role, status); // throws it
470 void AbstractHandler::fillStatus(saml2p::StatusResponseType& response, const XMLCh* code, const XMLCh* subcode, const char* msg) const
472 saml2p::Status* status = saml2p::StatusBuilder::buildStatus();
473 saml2p::StatusCode* scode = saml2p::StatusCodeBuilder::buildStatusCode();
474 status->setStatusCode(scode);
475 scode->setValue(code);
477 saml2p::StatusCode* ssubcode = saml2p::StatusCodeBuilder::buildStatusCode();
478 scode->setStatusCode(ssubcode);
479 ssubcode->setValue(subcode);
482 pair<bool,bool> flag = getBool("detailedErrors", m_configNS.get());
483 auto_ptr_XMLCh widemsg((flag.first && flag.second) ? msg : "Error processing request.");
484 saml2p::StatusMessage* sm = saml2p::StatusMessageBuilder::buildStatusMessage();
485 status->setStatusMessage(sm);
486 sm->setMessage(widemsg.get());
488 response.setStatus(status);
491 long AbstractHandler::sendMessage(
492 const MessageEncoder& encoder,
494 const char* relayState,
495 const char* destination,
496 const saml2md::RoleDescriptor* role,
497 const Application& application,
498 HTTPResponse& httpResponse,
502 const EntityDescriptor* entity = role ? dynamic_cast<const EntityDescriptor*>(role->getParent()) : nullptr;
503 const PropertySet* relyingParty = application.getRelyingParty(entity);
504 pair<bool,const char*> flag = signIfPossible ? make_pair(true,(const char*)"true") : relyingParty->getString("signing");
505 if (flag.first && (!strcmp(flag.second, "true") ||
506 (encoder.isUserAgentPresent() && !strcmp(flag.second, "front")) ||
507 (!encoder.isUserAgentPresent() && !strcmp(flag.second, "back")))) {
508 CredentialResolver* credResolver = application.getCredentialResolver();
510 Locker credLocker(credResolver);
511 const Credential* cred = nullptr;
512 pair<bool,const char*> keyName = relyingParty->getString("keyName");
513 pair<bool,const XMLCh*> sigalg = relyingParty->getXMLString("signingAlg");
515 MetadataCredentialCriteria mcc(*role);
516 mcc.setUsage(Credential::SIGNING_CREDENTIAL);
518 mcc.getKeyNames().insert(keyName.second);
520 // Using an explicit algorithm, so resolve a credential directly.
521 mcc.setXMLAlgorithm(sigalg.second);
522 cred = credResolver->resolve(&mcc);
525 // Prefer credential based on peer's requirements.
526 pair<const SigningMethod*,const Credential*> p = role->getSigningMethod(*credResolver, mcc);
528 sigalg = make_pair(true, p.first->getAlgorithm());
534 CredentialCriteria cc;
535 cc.setUsage(Credential::SIGNING_CREDENTIAL);
537 cc.getKeyNames().insert(keyName.second);
539 cc.setXMLAlgorithm(sigalg.second);
540 cred = credResolver->resolve(&cc);
544 pair<bool,const XMLCh*> digalg = relyingParty->getXMLString("digestAlg");
545 if (!digalg.first && role) {
546 const DigestMethod* dm = role->getDigestMethod();
548 digalg = make_pair(true, dm->getAlgorithm());
550 return encoder.encode(
559 (digalg.first ? digalg.second : nullptr)
563 m_log.warn("no signing credential resolved, leaving message unsigned");
567 m_log.warn("no credential resolver installed, leaving message unsigned");
572 return encoder.encode(httpResponse, msg, destination, entity, relayState, &application);
577 void AbstractHandler::preservePostData(
578 const Application& application, const HTTPRequest& request, HTTPResponse& response, const char* relayState
581 #ifdef HAVE_STRCASECMP
582 if (strcasecmp(request.getMethod(), "POST")) return;
584 if (stricmp(request.getMethod(), "POST")) return;
587 // No specs mean no save.
588 const PropertySet* props=application.getPropertySet("Sessions");
589 pair<bool,const char*> mech = props ? props->getString("postData") : pair<bool,const char*>(false,nullptr);
591 m_log.info("postData property not supplied, form data will not be preserved across SSO");
595 DDF postData = getPostData(application, request);
596 if (postData.isnull())
599 if (strstr(mech.second,"ss:") == mech.second) {
603 throw ConfigurationException("Unsupported postData mechanism ($1).", params(1, mech.second - 3));
607 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
608 DDFJanitor postjan(postData);
610 StorageService* storage = application.getServiceProvider().getStorageService(mech.second);
614 SAMLConfig::getConfig().generateRandomBytes(rsKey, 32);
615 rsKey = SAMLArtifact::toHex(rsKey);
618 if (!storage->createText("PostData", rsKey.c_str(), out.str().c_str(), time(nullptr) + 600))
619 throw IOException("Attempted to insert duplicate storage key.");
620 postkey = string(mech.second-3) + ':' + rsKey;
623 m_log.error("storage-backed PostData mechanism with invalid StorageService ID (%s)", mech.second);
626 throw ConfigurationException("Lite version of library cannot be used out of process.");
629 else if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
630 DDF out,in = DDF("set::PostData").structure();
631 DDFJanitor jin(in),jout(out);
632 in.addmember("id").string(mech.second);
634 out = application.getServiceProvider().getListenerService()->send(in);
636 throw IOException("StorageService-backed PostData mechanism did not return a state key.");
637 postkey = string(mech.second-3) + ':' + out.string();
640 // Set a cookie with key info.
641 pair<string,const char*> shib_cookie = getPostCookieNameProps(application, relayState);
642 postkey += shib_cookie.second;
643 response.setCookie(shib_cookie.first.c_str(), postkey.c_str());
647 throw ConfigurationException("Unsupported postData mechanism ($1).", params(1,mech.second));
651 DDF AbstractHandler::recoverPostData(
652 const Application& application, const HTTPRequest& request, HTTPResponse& response, const char* relayState
655 // First we need the post recovery cookie.
656 pair<string,const char*> shib_cookie = getPostCookieNameProps(application, relayState);
657 const char* cookie = request.getCookie(shib_cookie.first.c_str());
658 if (!cookie || !*cookie)
662 string exp(shib_cookie.second);
663 exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
664 response.setCookie(shib_cookie.first.c_str(), exp.c_str());
666 // Look for StorageService-backed state of the form "ss:SSID:key".
667 const char* state = cookie;
668 if (strstr(state, "ss:") == state) {
670 const char* key = strchr(state, ':');
672 string ssid = string(cookie).substr(3, key - state);
674 if (!ssid.empty() && *key) {
675 SPConfig& conf = SPConfig::getConfig();
676 if (conf.isEnabled(SPConfig::OutOfProcess)) {
678 StorageService* storage = conf.getServiceProvider()->getStorageService(ssid.c_str());
680 if (storage->readText("PostData", key, &ssid) > 0) {
681 storage->deleteText("PostData", key);
682 istringstream inret(ssid);
688 m_log.error("failed to recover form post data using key (%s)", key);
692 m_log.error("storage-backed PostData with invalid StorageService ID (%s)", ssid.c_str());
696 else if (conf.isEnabled(SPConfig::InProcess)) {
697 DDF in = DDF("get::PostData").structure();
699 in.addmember("id").string(ssid.c_str());
700 in.addmember("key").string(key);
701 DDF out = application.getServiceProvider().getListenerService()->send(in);
705 m_log.error("storageService-backed PostData mechanism did not return preserved data.");
713 long AbstractHandler::sendPostResponse(
714 const Application& application, HTTPResponse& httpResponse, const char* url, DDF& postData
717 HTTPResponse::sanitizeURL(url);
719 const PropertySet* props=application.getPropertySet("Sessions");
720 pair<bool,const char*> postTemplate = props ? props->getString("postTemplate") : pair<bool,const char*>(true,nullptr);
721 if (!postTemplate.first)
722 postTemplate.second = "postTemplate.html";
724 string fname(postTemplate.second);
725 ifstream infile(XMLToolingConfig::getConfig().getPathResolver()->resolve(fname, PathResolver::XMLTOOLING_CFG_FILE).c_str());
727 throw ConfigurationException("Unable to access HTML template ($1).", params(1, fname.c_str()));
728 TemplateParameters respParam;
729 respParam.m_map["action"] = url;
731 // Load the parameters into objects for the template.
732 multimap<string,string>& collection = respParam.m_collectionMap["PostedData"];
733 DDF param = postData.first();
734 while (!param.isnull()) {
735 collection.insert(pair<const string,string>(param.name(), (param.string() ? param.string() : "")));
736 param = postData.next();
740 XMLToolingConfig::getConfig().getTemplateEngine()->run(infile, str, respParam);
742 pair<bool,bool> postExpire = props ? props->getBool("postExpire") : make_pair(false,false);
744 httpResponse.setContentType("text/html");
745 if (!postExpire.first || postExpire.second) {
746 httpResponse.setResponseHeader("Expires", "Wed, 01 Jan 1997 12:00:00 GMT");
747 httpResponse.setResponseHeader("Cache-Control", "no-cache, no-store, must-revalidate, private, max-age=0");
748 httpResponse.setResponseHeader("Pragma", "no-cache");
750 return httpResponse.sendResponse(str);
753 pair<string,const char*> AbstractHandler::getPostCookieNameProps(const Application& app, const char* relayState) const
755 // Decorates the name of the cookie with the relay state key, if any.
756 // Doing so gives a better assurance that the recovered data really
757 // belongs to the relayed request.
758 pair<string,const char*> shib_cookie=app.getCookieNameProps("_shibpost_");
759 if (strstr(relayState, "cookie:") == relayState) {
760 shib_cookie.first = string("_shibpost_") + (relayState + 7);
762 else if (strstr(relayState, "ss:") == relayState) {
763 const char* pch = strchr(relayState + 3, ':');
765 shib_cookie.first = string("_shibpost_") + (pch + 1);
770 DDF AbstractHandler::getPostData(const Application& application, const HTTPRequest& request) const
772 string contentType = request.getContentType();
773 if (contentType.find("application/x-www-form-urlencoded") != string::npos) {
774 const PropertySet* props = application.getPropertySet("Sessions");
775 pair<bool,unsigned int> plimit = props ? props->getUnsignedInt("postLimit") : pair<bool,unsigned int>(false,0);
777 plimit.second = 1024 * 1024;
778 if (plimit.second == 0 || request.getContentLength() <= plimit.second) {
779 CGIParser cgi(request);
780 pair<CGIParser::walker,CGIParser::walker> params = cgi.getParameters(nullptr);
781 if (params.first == params.second)
782 return DDF("parameters").list();
784 DDF ret = DDF("parameters").list();
785 for (; params.first != params.second; ++params.first) {
786 if (!params.first->first.empty()) {
787 child = DDF(params.first->first.c_str()).unsafe_string(params.first->second);
794 m_log.warn("POST limit exceeded, ignoring %d bytes of posted data", request.getContentLength());
798 m_log.info("ignoring POST data with non-standard encoding (%s)", contentType.c_str());
803 pair<bool,bool> AbstractHandler::getBool(const char* name, const SPRequest& request, unsigned int type) const
805 if (type & HANDLER_PROPERTY_REQUEST) {
806 const char* param = request.getParameter(name);
808 return make_pair(true, (*param=='t' || *param=='1'));
811 if (type & HANDLER_PROPERTY_MAP) {
812 pair<bool,bool> ret = request.getRequestSettings().first->getBool(name);
817 if (type & HANDLER_PROPERTY_FIXED) {
818 return getBool(name);
821 return make_pair(false,false);
824 pair<bool,const char*> AbstractHandler::getString(const char* name, const SPRequest& request, unsigned int type) const
826 if (type & HANDLER_PROPERTY_REQUEST) {
827 const char* param = request.getParameter(name);
829 return make_pair(true, param);
832 if (type & HANDLER_PROPERTY_MAP) {
833 pair<bool,const char*> ret = request.getRequestSettings().first->getString(name);
838 if (type & HANDLER_PROPERTY_FIXED) {
839 return getString(name);
842 return pair<bool,const char*>(false,nullptr);
845 pair<bool,unsigned int> AbstractHandler::getUnsignedInt(const char* name, const SPRequest& request, unsigned int type) const
847 if (type & HANDLER_PROPERTY_REQUEST) {
848 const char* param = request.getParameter(name);
849 if (param && *param) {
851 return pair<bool,unsigned int>(true, lexical_cast<unsigned int>(param));
853 catch (bad_lexical_cast&) {
854 return pair<bool,unsigned int>(false,0);
859 if (type & HANDLER_PROPERTY_MAP) {
860 pair<bool,unsigned int> ret = request.getRequestSettings().first->getUnsignedInt(name);
865 if (type & HANDLER_PROPERTY_FIXED) {
866 return getUnsignedInt(name);
869 return pair<bool,unsigned int>(false,0);
872 pair<bool,int> AbstractHandler::getInt(const char* name, const SPRequest& request, unsigned int type) const
874 if (type & HANDLER_PROPERTY_REQUEST) {
875 const char* param = request.getParameter(name);
877 return pair<bool,int>(true, atoi(param));
880 if (type & HANDLER_PROPERTY_MAP) {
881 pair<bool,int> ret = request.getRequestSettings().first->getInt(name);
886 if (type & HANDLER_PROPERTY_FIXED) {
890 return pair<bool,int>(false,0);