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 <xmltooling/XMLToolingConfig.h>
42 #include <xmltooling/util/PathResolver.h>
43 #include <xmltooling/util/URLEncoder.h>
47 # include <saml/exceptions.h>
48 # include <saml/SAMLConfig.h>
49 # include <saml/binding/SAMLArtifact.h>
50 # include <saml/saml1/core/Protocols.h>
51 # include <saml/saml2/core/Protocols.h>
52 # include <saml/saml2/metadata/Metadata.h>
53 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
54 # include <saml/util/SAMLConstants.h>
55 # include <xmltooling/security/Credential.h>
56 # include <xmltooling/security/CredentialResolver.h>
57 # include <xmltooling/util/StorageService.h>
58 using namespace opensaml::saml2md;
59 using namespace opensaml;
61 # include "lite/SAMLConstants.h"
64 #include <xmltooling/XMLToolingConfig.h>
65 #include <xmltooling/util/URLEncoder.h>
67 using namespace shibsp;
68 using namespace samlconstants;
69 using namespace xmltooling;
70 using namespace xercesc;
75 SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML1ConsumerFactory;
76 SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2ConsumerFactory;
77 SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2ArtifactResolutionFactory;
78 SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2LogoutFactory;
79 SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2NameIDMgmtFactory;
80 SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory AssertionLookupFactory;
81 SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory DiscoveryFeedFactory;
82 SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory MetadataGeneratorFactory;
83 SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory StatusHandlerFactory;
84 SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SessionHandlerFactory;
86 void SHIBSP_DLLLOCAL absolutize(const HTTPRequest& request, string& url) {
90 // Compute a URL to the root of the site.
91 int port = request.getPort();
92 const char* scheme = request.getScheme();
93 string root = string(scheme) + "://" + request.getHostname();
94 if ((!strcmp(scheme,"http") && port!=80) || (!strcmp(scheme,"https") && port!=443)) {
95 ostringstream portstr;
97 root += ":" + portstr.str();
103 void SHIBSP_DLLLOCAL generateRandomHex(std::string& buf, unsigned int len) {
104 static char DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
108 for (unsigned int i=0; i<len; i+=4) {
111 b2 = (0xFF00 & r) >> 8;
112 buf += (DIGITS[(0xF0 & b1) >> 4 ]);
113 buf += (DIGITS[0x0F & b1]);
114 buf += (DIGITS[(0xF0 & b2) >> 4 ]);
115 buf += (DIGITS[0x0F & b2]);
119 void SHIBSP_DLLLOCAL limitRelayState(
120 Category& log, const Application& application, const HTTPRequest& httpRequest, const char* relayState
122 const PropertySet* sessionProps = application.getPropertySet("Sessions");
124 pair<bool,const char*> relayStateLimit = sessionProps->getString("relayStateLimit");
125 if (relayStateLimit.first && strcmp(relayStateLimit.second, "none")) {
126 vector<string> whitelist;
127 if (!strcmp(relayStateLimit.second, "exact")) {
128 // Scheme and hostname have to match.
129 if (!strcmp(httpRequest.getScheme(), "https") && httpRequest.getPort() == 443) {
130 whitelist.push_back(string("https://") + httpRequest.getHostname() + '/');
132 else if (!strcmp(httpRequest.getScheme(), "http") && httpRequest.getPort() == 80) {
133 whitelist.push_back(string("http://") + httpRequest.getHostname() + '/');
135 ostringstream portstr;
136 portstr << httpRequest.getPort();
137 whitelist.push_back(string(httpRequest.getScheme()) + "://" + httpRequest.getHostname() + ':' + portstr.str() + '/');
139 else if (!strcmp(relayStateLimit.second, "host")) {
140 // Allow any scheme or port.
141 whitelist.push_back(string("https://") + httpRequest.getHostname() + '/');
142 whitelist.push_back(string("http://") + httpRequest.getHostname() + '/');
143 whitelist.push_back(string("https://") + httpRequest.getHostname() + ':');
144 whitelist.push_back(string("http://") + httpRequest.getHostname() + ':');
146 else if (!strcmp(relayStateLimit.second, "whitelist")) {
147 // Literal set of comparisons to use.
148 pair<bool,const char*> whitelistval = sessionProps->getString("relayStateWhitelist");
149 if (whitelistval.first) {
152 const char* token = strtok_r(const_cast<char*>(whitelistval.second), " ", &pos);
154 const char* token = strtok(const_cast<char*>(whitelistval.second), " ");
157 whitelist.push_back(token);
159 token = strtok_r(nullptr, " ", &pos);
161 token = strtok(nullptr, " ");
167 log.warn("unrecognized relayStateLimit policy (%s), blocked redirect to (%s)", relayStateLimit.second, relayState);
168 throw opensaml::SecurityPolicyException("Unrecognized relayStateLimit setting.");
171 for (vector<string>::const_iterator w = whitelist.begin(); w != whitelist.end(); ++w) {
172 if (XMLString::startsWithI(relayState, w->c_str())) {
177 log.warn("relayStateLimit policy (%s), blocked redirect to (%s)", relayStateLimit.second, relayState);
178 throw opensaml::SecurityPolicyException("Blocked unacceptable redirect location.");
184 void SHIBSP_API shibsp::registerHandlers()
186 SPConfig& conf=SPConfig::getConfig();
188 conf.AssertionConsumerServiceManager.registerFactory(SAML1_ASSERTION_CONSUMER_SERVICE, SAML1ConsumerFactory);
189 conf.AssertionConsumerServiceManager.registerFactory(SAML1_PROFILE_BROWSER_ARTIFACT, SAML1ConsumerFactory);
190 conf.AssertionConsumerServiceManager.registerFactory(SAML1_PROFILE_BROWSER_POST, SAML1ConsumerFactory);
191 conf.AssertionConsumerServiceManager.registerFactory(SAML20_ASSERTION_CONSUMER_SERVICE, SAML2ConsumerFactory);
192 conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_POST, SAML2ConsumerFactory);
193 conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_POST_SIMPLESIGN, SAML2ConsumerFactory);
194 conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_ARTIFACT, SAML2ConsumerFactory);
195 conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_PAOS, SAML2ConsumerFactory);
197 conf.ArtifactResolutionServiceManager.registerFactory(SAML20_ARTIFACT_RESOLUTION_SERVICE, SAML2ArtifactResolutionFactory);
198 conf.ArtifactResolutionServiceManager.registerFactory(SAML20_BINDING_SOAP, SAML2ArtifactResolutionFactory);
200 conf.HandlerManager.registerFactory(SAML20_BINDING_URI, AssertionLookupFactory);
201 conf.HandlerManager.registerFactory(DISCOVERY_FEED_HANDLER, DiscoveryFeedFactory);
202 conf.HandlerManager.registerFactory(METADATA_GENERATOR_HANDLER, MetadataGeneratorFactory);
203 conf.HandlerManager.registerFactory(STATUS_HANDLER, StatusHandlerFactory);
204 conf.HandlerManager.registerFactory(SESSION_HANDLER, SessionHandlerFactory);
206 conf.SingleLogoutServiceManager.registerFactory(SAML20_LOGOUT_HANDLER, SAML2LogoutFactory);
207 conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_SOAP, SAML2LogoutFactory);
208 conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_HTTP_REDIRECT, SAML2LogoutFactory);
209 conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_HTTP_POST, SAML2LogoutFactory);
210 conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_HTTP_POST_SIMPLESIGN, SAML2LogoutFactory);
211 conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_HTTP_ARTIFACT, SAML2LogoutFactory);
213 conf.ManageNameIDServiceManager.registerFactory(SAML20_NAMEID_MGMT_SERVICE, SAML2NameIDMgmtFactory);
214 conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_SOAP, SAML2NameIDMgmtFactory);
215 conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_HTTP_REDIRECT, SAML2NameIDMgmtFactory);
216 conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_HTTP_POST, SAML2NameIDMgmtFactory);
217 conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_HTTP_POST_SIMPLESIGN, SAML2NameIDMgmtFactory);
218 conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_HTTP_ARTIFACT, SAML2NameIDMgmtFactory);
231 void Handler::generateMetadata(SPSSODescriptor& role, const char* handlerURL) const
237 const XMLCh* Handler::getProtocolFamily() const
242 void Handler::log(SPRequest::SPLogLevel level, const string& msg) const
244 Category::getInstance(SHIBSP_LOGCAT".Handler").log(
245 (level == SPRequest::SPDebug ? Priority::DEBUG :
246 (level == SPRequest::SPInfo ? Priority::INFO :
247 (level == SPRequest::SPWarn ? Priority::WARN :
248 (level == SPRequest::SPError ? Priority::ERROR : Priority::CRIT)))),
253 void Handler::preserveRelayState(const Application& application, HTTPResponse& response, string& relayState) const
255 // The empty string implies no state to deal with.
256 if (relayState.empty())
259 // No setting means just pass state by value.
260 pair<bool,const char*> mech = getString("relayState");
262 // Check for setting on Sessions element.
263 const PropertySet* sessionprop = application.getPropertySet("Sessions");
265 mech = sessionprop->getString("relayState");
267 if (!mech.first || !mech.second || !*mech.second)
270 if (!strcmp(mech.second, "cookie")) {
271 // Here we store the state in a cookie and send a fixed
272 // value so we can recognize it on the way back.
273 if (relayState.find("cookie:") != 0) {
274 const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
275 pair<string,const char*> shib_cookie=application.getCookieNameProps("_shibstate_");
276 string stateval = urlenc->encode(relayState.c_str()) + shib_cookie.second;
277 // Generate a random key for the cookie name instead of the fixed name.
279 generateRandomHex(rsKey,5);
280 shib_cookie.first = "_shibstate_" + rsKey;
281 response.setCookie(shib_cookie.first.c_str(),stateval.c_str());
282 relayState = "cookie:" + rsKey;
285 else if (strstr(mech.second,"ss:")==mech.second) {
286 if (relayState.find("ss:") != 0) {
289 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
291 StorageService* storage = application.getServiceProvider().getStorageService(mech.second);
295 SAMLConfig::getConfig().generateRandomBytes(rsKey,32);
296 rsKey = SAMLArtifact::toHex(rsKey);
297 if (!storage->createString("RelayState", rsKey.c_str(), relayState.c_str(), time(nullptr) + 600))
298 throw IOException("Collision generating in-memory relay state key.");
299 relayState = string(mech.second-3) + ':' + rsKey;
302 string msg("Storage-backed RelayState with invalid StorageService ID (");
303 msg = msg + mech.second+ ')';
304 log(SPRequest::SPError, msg);
308 throw ConfigurationException("Lite version of library cannot be used out of process.");
311 else if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
312 DDF out,in = DDF("set::RelayState").structure();
313 in.addmember("id").string(mech.second);
314 in.addmember("value").unsafe_string(relayState.c_str());
315 DDFJanitor jin(in),jout(out);
316 out = application.getServiceProvider().getListenerService()->send(in);
318 throw IOException("StorageService-backed RelayState mechanism did not return a state key.");
319 relayState = string(mech.second-3) + ':' + out.string();
325 throw ConfigurationException("Unsupported relayState mechanism ($1).", params(1,mech.second));
328 void Handler::recoverRelayState(
329 const Application& application, const HTTPRequest& request, HTTPResponse& response, string& relayState, bool clear
332 SPConfig& conf = SPConfig::getConfig();
334 // Look for StorageService-backed state of the form "ss:SSID:key".
335 const char* state = relayState.c_str();
336 if (strstr(state,"ss:")==state) {
338 const char* key = strchr(state,':');
340 string ssid = relayState.substr(3, key - state);
342 if (!ssid.empty() && *key) {
343 if (conf.isEnabled(SPConfig::OutOfProcess)) {
345 StorageService* storage = conf.getServiceProvider()->getStorageService(ssid.c_str());
348 if (storage->readString("RelayState",ssid.c_str(),&relayState) > 0) {
350 storage->deleteString("RelayState",ssid.c_str());
351 absolutize(request, relayState);
358 string msg("Storage-backed RelayState with invalid StorageService ID (");
360 log(SPRequest::SPError, msg);
365 else if (conf.isEnabled(SPConfig::InProcess)) {
366 DDF out,in = DDF("get::RelayState").structure();
367 in.addmember("id").string(ssid.c_str());
368 in.addmember("key").string(key);
369 in.addmember("clear").integer(clear ? 1 : 0);
370 DDFJanitor jin(in),jout(out);
371 out = application.getServiceProvider().getListenerService()->send(in);
372 if (!out.isstring()) {
373 log(SPRequest::SPError, "StorageService-backed RelayState mechanism did not return a state value.");
377 relayState = out.string();
378 absolutize(request, relayState);
386 // Look for cookie-backed state of the form "cookie:key".
387 if (strstr(state,"cookie:")==state) {
390 // Pull the value from the "relay state" cookie.
391 pair<string,const char*> relay_cookie = application.getCookieNameProps("_shibstate_");
392 relay_cookie.first = string("_shibstate_") + state;
393 state = request.getCookie(relay_cookie.first.c_str());
394 if (state && *state) {
395 // URL-decode the value.
396 char* rscopy=strdup(state);
397 XMLToolingConfig::getConfig().getURLEncoder()->decode(rscopy);
402 string exp(relay_cookie.second);
403 exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
404 response.setCookie(relay_cookie.first.c_str(), exp.c_str());
406 absolutize(request, relayState);
414 // Check for "default" value (or the old "cookie" value that might come from stale bookmarks).
415 if (relayState.empty() || relayState == "default" || relayState == "cookie") {
416 pair<bool,const char*> homeURL=application.getString("homeURL");
418 relayState = homeURL.second;
423 absolutize(request, relayState);
426 AbstractHandler::AbstractHandler(
427 const DOMElement* e, Category& log, DOMNodeFilter* filter, const map<string,string>* remapper
428 ) : m_log(log), m_configNS(shibspconstants::SHIB2SPCONFIG_NS) {
429 load(e,nullptr,filter,remapper);
432 AbstractHandler::~AbstractHandler()
436 void AbstractHandler::log(SPRequest::SPLogLevel level, const string& msg) const
439 (level == SPRequest::SPDebug ? Priority::DEBUG :
440 (level == SPRequest::SPInfo ? Priority::INFO :
441 (level == SPRequest::SPWarn ? Priority::WARN :
442 (level == SPRequest::SPError ? Priority::ERROR : Priority::CRIT)))),
449 const char* Handler::getType() const
451 return getString("type").second;
454 void AbstractHandler::checkError(const XMLObject* response, const saml2md::RoleDescriptor* role) const
456 const saml2p::StatusResponseType* r2 = dynamic_cast<const saml2p::StatusResponseType*>(response);
458 const saml2p::Status* status = r2->getStatus();
460 const saml2p::StatusCode* sc = status->getStatusCode();
461 const XMLCh* code = sc ? sc->getValue() : nullptr;
462 if (code && !XMLString::equals(code,saml2p::StatusCode::SUCCESS)) {
463 FatalProfileException ex("SAML response contained an error.");
464 annotateException(&ex, role, status); // throws it
469 const saml1p::Response* r1 = dynamic_cast<const saml1p::Response*>(response);
471 const saml1p::Status* status = r1->getStatus();
473 const saml1p::StatusCode* sc = status->getStatusCode();
474 const xmltooling::QName* code = sc ? sc->getValue() : nullptr;
475 if (code && *code != saml1p::StatusCode::SUCCESS) {
476 FatalProfileException ex("SAML response contained an error.");
477 ex.addProperty("statusCode", code->toString().c_str());
478 if (sc->getStatusCode()) {
479 code = sc->getStatusCode()->getValue();
481 ex.addProperty("statusCode2", code->toString().c_str());
483 if (status->getStatusMessage()) {
484 auto_ptr_char msg(status->getStatusMessage()->getMessage());
485 if (msg.get() && *msg.get())
486 ex.addProperty("statusMessage", msg.get());
494 void AbstractHandler::fillStatus(saml2p::StatusResponseType& response, const XMLCh* code, const XMLCh* subcode, const char* msg) const
496 saml2p::Status* status = saml2p::StatusBuilder::buildStatus();
497 saml2p::StatusCode* scode = saml2p::StatusCodeBuilder::buildStatusCode();
498 status->setStatusCode(scode);
499 scode->setValue(code);
501 saml2p::StatusCode* ssubcode = saml2p::StatusCodeBuilder::buildStatusCode();
502 scode->setStatusCode(ssubcode);
503 ssubcode->setValue(subcode);
506 pair<bool,bool> flag = getBool("detailedErrors", m_configNS.get());
507 auto_ptr_XMLCh widemsg((flag.first && flag.second) ? msg : "Error processing request.");
508 saml2p::StatusMessage* sm = saml2p::StatusMessageBuilder::buildStatusMessage();
509 status->setStatusMessage(sm);
510 sm->setMessage(widemsg.get());
512 response.setStatus(status);
515 long AbstractHandler::sendMessage(
516 const MessageEncoder& encoder,
518 const char* relayState,
519 const char* destination,
520 const saml2md::RoleDescriptor* role,
521 const Application& application,
522 HTTPResponse& httpResponse,
526 const EntityDescriptor* entity = role ? dynamic_cast<const EntityDescriptor*>(role->getParent()) : nullptr;
527 const PropertySet* relyingParty = application.getRelyingParty(entity);
528 pair<bool,const char*> flag = signIfPossible ? make_pair(true,(const char*)"true") : relyingParty->getString("signing");
529 if (role && flag.first &&
530 (!strcmp(flag.second, "true") ||
531 (encoder.isUserAgentPresent() && !strcmp(flag.second, "front")) ||
532 (!encoder.isUserAgentPresent() && !strcmp(flag.second, "back")))) {
533 CredentialResolver* credResolver=application.getCredentialResolver();
535 Locker credLocker(credResolver);
536 const Credential* cred = nullptr;
537 pair<bool,const char*> keyName = relyingParty->getString("keyName");
538 pair<bool,const XMLCh*> sigalg = relyingParty->getXMLString("signingAlg");
540 MetadataCredentialCriteria mcc(*role);
541 mcc.setUsage(Credential::SIGNING_CREDENTIAL);
543 mcc.getKeyNames().insert(keyName.second);
545 // Using an explicit algorithm, so resolve a credential directly.
546 mcc.setXMLAlgorithm(sigalg.second);
547 cred = credResolver->resolve(&mcc);
550 // Prefer credential based on peer's requirements.
551 pair<const SigningMethod*,const Credential*> p = role->getSigningMethod(*credResolver, mcc);
553 sigalg = make_pair(true, p.first->getAlgorithm());
559 CredentialCriteria cc;
560 cc.setUsage(Credential::SIGNING_CREDENTIAL);
562 cc.getKeyNames().insert(keyName.second);
564 cc.setXMLAlgorithm(sigalg.second);
565 cred = credResolver->resolve(&cc);
569 pair<bool,const XMLCh*> digalg = relyingParty->getXMLString("digestAlg");
570 if (!digalg.first && role) {
571 const DigestMethod* dm = role->getDigestMethod();
573 digalg = make_pair(true, dm->getAlgorithm());
575 return encoder.encode(
584 (digalg.first ? digalg.second : nullptr)
588 m_log.warn("no signing credential resolved, leaving message unsigned");
592 m_log.warn("no credential resolver installed, leaving message unsigned");
597 return encoder.encode(httpResponse, msg, destination, entity, relayState, &application);
602 void AbstractHandler::preservePostData(
603 const Application& application, const HTTPRequest& request, HTTPResponse& response, const char* relayState
606 #ifdef HAVE_STRCASECMP
607 if (strcasecmp(request.getMethod(), "POST")) return;
609 if (stricmp(request.getMethod(), "POST")) return;
612 // No specs mean no save.
613 const PropertySet* props=application.getPropertySet("Sessions");
614 pair<bool,const char*> mech = props ? props->getString("postData") : pair<bool,const char*>(false,nullptr);
616 m_log.info("postData property not supplied, form data will not be preserved across SSO");
620 DDF postData = getPostData(application, request);
621 if (postData.isnull())
624 if (strstr(mech.second,"ss:") == mech.second) {
628 throw ConfigurationException("Unsupported postData mechanism ($1).", params(1, mech.second - 3));
632 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
633 DDFJanitor postjan(postData);
635 StorageService* storage = application.getServiceProvider().getStorageService(mech.second);
639 SAMLConfig::getConfig().generateRandomBytes(rsKey,32);
640 rsKey = SAMLArtifact::toHex(rsKey);
643 if (!storage->createString("PostData", rsKey.c_str(), out.str().c_str(), time(nullptr) + 600))
644 throw IOException("Attempted to insert duplicate storage key.");
645 postkey = string(mech.second-3) + ':' + rsKey;
648 m_log.error("storage-backed PostData mechanism with invalid StorageService ID (%s)", mech.second);
651 throw ConfigurationException("Lite version of library cannot be used out of process.");
654 else if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
655 DDF out,in = DDF("set::PostData").structure();
656 DDFJanitor jin(in),jout(out);
657 in.addmember("id").string(mech.second);
659 out = application.getServiceProvider().getListenerService()->send(in);
661 throw IOException("StorageService-backed PostData mechanism did not return a state key.");
662 postkey = string(mech.second-3) + ':' + out.string();
665 // Set a cookie with key info.
666 pair<string,const char*> shib_cookie = getPostCookieNameProps(application, relayState);
667 postkey += shib_cookie.second;
668 response.setCookie(shib_cookie.first.c_str(), postkey.c_str());
672 throw ConfigurationException("Unsupported postData mechanism ($1).", params(1,mech.second));
676 DDF AbstractHandler::recoverPostData(
677 const Application& application, const HTTPRequest& request, HTTPResponse& response, const char* relayState
680 // First we need the post recovery cookie.
681 pair<string,const char*> shib_cookie = getPostCookieNameProps(application, relayState);
682 const char* cookie = request.getCookie(shib_cookie.first.c_str());
683 if (!cookie || !*cookie)
687 string exp(shib_cookie.second);
688 exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
689 response.setCookie(shib_cookie.first.c_str(), exp.c_str());
691 // Look for StorageService-backed state of the form "ss:SSID:key".
692 const char* state = cookie;
693 if (strstr(state, "ss:") == state) {
695 const char* key = strchr(state, ':');
697 string ssid = string(cookie).substr(3, key - state);
699 if (!ssid.empty() && *key) {
700 SPConfig& conf = SPConfig::getConfig();
701 if (conf.isEnabled(SPConfig::OutOfProcess)) {
703 StorageService* storage = conf.getServiceProvider()->getStorageService(ssid.c_str());
705 if (storage->readString("PostData", key, &ssid) > 0) {
706 storage->deleteString("PostData", key);
707 istringstream inret(ssid);
713 m_log.error("failed to recover form post data using key (%s)", key);
717 m_log.error("storage-backed PostData with invalid StorageService ID (%s)", ssid.c_str());
721 else if (conf.isEnabled(SPConfig::InProcess)) {
722 DDF in = DDF("get::PostData").structure();
724 in.addmember("id").string(ssid.c_str());
725 in.addmember("key").string(key);
726 DDF out = application.getServiceProvider().getListenerService()->send(in);
730 m_log.error("storageService-backed PostData mechanism did not return preserved data.");
738 long AbstractHandler::sendPostResponse(
739 const Application& application, HTTPResponse& httpResponse, const char* url, DDF& postData
742 HTTPResponse::sanitizeURL(url);
744 const PropertySet* props=application.getPropertySet("Sessions");
745 pair<bool,const char*> postTemplate = props ? props->getString("postTemplate") : pair<bool,const char*>(true,nullptr);
746 if (!postTemplate.first)
747 postTemplate.second = "postTemplate.html";
749 string fname(postTemplate.second);
750 ifstream infile(XMLToolingConfig::getConfig().getPathResolver()->resolve(fname, PathResolver::XMLTOOLING_CFG_FILE).c_str());
752 throw ConfigurationException("Unable to access HTML template ($1).", params(1, fname.c_str()));
753 TemplateParameters respParam;
754 respParam.m_map["action"] = url;
756 // Load the parameters into objects for the template.
757 multimap<string,string>& collection = respParam.m_collectionMap["PostedData"];
758 DDF param = postData.first();
759 while (!param.isnull()) {
760 collection.insert(pair<const string,string>(param.name(), (param.string() ? param.string() : "")));
761 param = postData.next();
765 XMLToolingConfig::getConfig().getTemplateEngine()->run(infile, str, respParam);
767 pair<bool,bool> postExpire = props ? props->getBool("postExpire") : make_pair(false,false);
769 httpResponse.setContentType("text/html");
770 if (!postExpire.first || postExpire.second) {
771 httpResponse.setResponseHeader("Expires", "Wed, 01 Jan 1997 12:00:00 GMT");
772 httpResponse.setResponseHeader("Cache-Control", "no-cache, no-store, must-revalidate, private, max-age=0");
773 httpResponse.setResponseHeader("Pragma", "no-cache");
775 return httpResponse.sendResponse(str);
778 pair<string,const char*> AbstractHandler::getPostCookieNameProps(const Application& app, const char* relayState) const
780 // Decorates the name of the cookie with the relay state key, if any.
781 // Doing so gives a better assurance that the recovered data really
782 // belongs to the relayed request.
783 pair<string,const char*> shib_cookie=app.getCookieNameProps("_shibpost_");
784 if (strstr(relayState, "cookie:") == relayState) {
785 shib_cookie.first = string("_shibpost_") + (relayState + 7);
787 else if (strstr(relayState, "ss:") == relayState) {
788 const char* pch = strchr(relayState + 3, ':');
790 shib_cookie.first = string("_shibpost_") + (pch + 1);
795 DDF AbstractHandler::getPostData(const Application& application, const HTTPRequest& request) const
797 string contentType = request.getContentType();
798 if (contentType.compare("application/x-www-form-urlencoded") == 0) {
799 const PropertySet* props=application.getPropertySet("Sessions");
800 pair<bool,unsigned int> plimit = props ? props->getUnsignedInt("postLimit") : pair<bool,unsigned int>(false,0);
802 plimit.second = 1024 * 1024;
803 if (plimit.second == 0 || request.getContentLength() <= plimit.second) {
804 CGIParser cgi(request);
805 pair<CGIParser::walker,CGIParser::walker> params = cgi.getParameters(nullptr);
806 if (params.first == params.second)
807 return DDF("parameters").list();
809 DDF ret = DDF("parameters").list();
810 for (; params.first != params.second; ++params.first) {
811 if (!params.first->first.empty()) {
812 child = DDF(params.first->first.c_str()).unsafe_string(params.first->second);
819 m_log.warn("POST limit exceeded, ignoring %d bytes of posted data", request.getContentLength());
823 m_log.info("ignoring POST data with non-standard encoding (%s)", contentType.c_str());
828 pair<bool,bool> AbstractHandler::getBool(const char* name, const SPRequest& request, unsigned int type) const
830 if (type & HANDLER_PROPERTY_REQUEST) {
831 const char* param = request.getParameter(name);
833 return make_pair(true, (*param=='t' || *param=='1'));
836 if (type & HANDLER_PROPERTY_MAP) {
837 pair<bool,bool> ret = request.getRequestSettings().first->getBool(name);
842 if (type & HANDLER_PROPERTY_FIXED) {
843 return getBool(name);
846 return make_pair(false,false);
849 pair<bool,const char*> AbstractHandler::getString(const char* name, const SPRequest& request, unsigned int type) const
851 if (type & HANDLER_PROPERTY_REQUEST) {
852 const char* param = request.getParameter(name);
854 return make_pair(true, param);
857 if (type & HANDLER_PROPERTY_MAP) {
858 pair<bool,const char*> ret = request.getRequestSettings().first->getString(name);
863 if (type & HANDLER_PROPERTY_FIXED) {
864 return getString(name);
867 return pair<bool,const char*>(false,nullptr);
870 pair<bool,unsigned int> AbstractHandler::getUnsignedInt(const char* name, const SPRequest& request, unsigned int type) const
872 if (type & HANDLER_PROPERTY_REQUEST) {
873 const char* param = request.getParameter(name);
875 return pair<bool,unsigned int>(true, strtol(param,nullptr,10));
878 if (type & HANDLER_PROPERTY_MAP) {
879 pair<bool,unsigned int> ret = request.getRequestSettings().first->getUnsignedInt(name);
884 if (type & HANDLER_PROPERTY_FIXED) {
885 return getUnsignedInt(name);
888 return pair<bool,unsigned int>(false,0);
891 pair<bool,int> AbstractHandler::getInt(const char* name, const SPRequest& request, unsigned int type) const
893 if (type & HANDLER_PROPERTY_REQUEST) {
894 const char* param = request.getParameter(name);
896 return pair<bool,int>(true, atoi(param));
899 if (type & HANDLER_PROPERTY_MAP) {
900 pair<bool,int> ret = request.getRequestSettings().first->getInt(name);
905 if (type & HANDLER_PROPERTY_FIXED) {
909 return pair<bool,int>(false,0);