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);
294 generateRandomHex(rsKey,32);
295 if (!storage->createString("RelayState", rsKey.c_str(), relayState.c_str(), time(nullptr) + 600))
296 throw IOException("Attempted to insert duplicate storage key.");
297 relayState = string(mech.second-3) + ':' + rsKey;
300 string msg("Storage-backed RelayState with invalid StorageService ID (");
301 msg = msg + mech.second+ ')';
302 log(SPRequest::SPError, msg);
307 else if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
308 DDF out,in = DDF("set::RelayState").structure();
309 in.addmember("id").string(mech.second);
310 in.addmember("value").unsafe_string(relayState.c_str());
311 DDFJanitor jin(in),jout(out);
312 out = application.getServiceProvider().getListenerService()->send(in);
314 throw IOException("StorageService-backed RelayState mechanism did not return a state key.");
315 relayState = string(mech.second-3) + ':' + out.string();
321 throw ConfigurationException("Unsupported relayState mechanism ($1).", params(1,mech.second));
324 void Handler::recoverRelayState(
325 const Application& application, const HTTPRequest& request, HTTPResponse& response, string& relayState, bool clear
328 SPConfig& conf = SPConfig::getConfig();
330 // Look for StorageService-backed state of the form "ss:SSID:key".
331 const char* state = relayState.c_str();
332 if (strstr(state,"ss:")==state) {
334 const char* key = strchr(state,':');
336 string ssid = relayState.substr(3, key - state);
338 if (!ssid.empty() && *key) {
339 if (conf.isEnabled(SPConfig::OutOfProcess)) {
341 StorageService* storage = conf.getServiceProvider()->getStorageService(ssid.c_str());
344 if (storage->readString("RelayState",ssid.c_str(),&relayState) > 0) {
346 storage->deleteString("RelayState",ssid.c_str());
347 absolutize(request, relayState);
354 string msg("Storage-backed RelayState with invalid StorageService ID (");
356 log(SPRequest::SPError, msg);
361 else if (conf.isEnabled(SPConfig::InProcess)) {
362 DDF out,in = DDF("get::RelayState").structure();
363 in.addmember("id").string(ssid.c_str());
364 in.addmember("key").string(key);
365 in.addmember("clear").integer(clear ? 1 : 0);
366 DDFJanitor jin(in),jout(out);
367 out = application.getServiceProvider().getListenerService()->send(in);
368 if (!out.isstring()) {
369 log(SPRequest::SPError, "StorageService-backed RelayState mechanism did not return a state value.");
373 relayState = out.string();
374 absolutize(request, relayState);
382 // Look for cookie-backed state of the form "cookie:key".
383 if (strstr(state,"cookie:")==state) {
386 // Pull the value from the "relay state" cookie.
387 pair<string,const char*> relay_cookie = application.getCookieNameProps("_shibstate_");
388 relay_cookie.first = string("_shibstate_") + state;
389 state = request.getCookie(relay_cookie.first.c_str());
390 if (state && *state) {
391 // URL-decode the value.
392 char* rscopy=strdup(state);
393 XMLToolingConfig::getConfig().getURLEncoder()->decode(rscopy);
398 string exp(relay_cookie.second);
399 exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
400 response.setCookie(relay_cookie.first.c_str(), exp.c_str());
402 absolutize(request, relayState);
410 // Check for "default" value (or the old "cookie" value that might come from stale bookmarks).
411 if (relayState.empty() || relayState == "default" || relayState == "cookie") {
412 pair<bool,const char*> homeURL=application.getString("homeURL");
414 relayState = homeURL.second;
419 absolutize(request, relayState);
422 AbstractHandler::AbstractHandler(
423 const DOMElement* e, Category& log, DOMNodeFilter* filter, const map<string,string>* remapper
424 ) : m_log(log), m_configNS(shibspconstants::SHIB2SPCONFIG_NS) {
425 load(e,nullptr,filter,remapper);
428 AbstractHandler::~AbstractHandler()
432 void AbstractHandler::log(SPRequest::SPLogLevel level, const string& msg) const
435 (level == SPRequest::SPDebug ? Priority::DEBUG :
436 (level == SPRequest::SPInfo ? Priority::INFO :
437 (level == SPRequest::SPWarn ? Priority::WARN :
438 (level == SPRequest::SPError ? Priority::ERROR : Priority::CRIT)))),
445 const char* Handler::getType() const
447 return getString("type").second;
450 void AbstractHandler::checkError(const XMLObject* response, const saml2md::RoleDescriptor* role) const
452 const saml2p::StatusResponseType* r2 = dynamic_cast<const saml2p::StatusResponseType*>(response);
454 const saml2p::Status* status = r2->getStatus();
456 const saml2p::StatusCode* sc = status->getStatusCode();
457 const XMLCh* code = sc ? sc->getValue() : nullptr;
458 if (code && !XMLString::equals(code,saml2p::StatusCode::SUCCESS)) {
459 FatalProfileException ex("SAML response contained an error.");
460 annotateException(&ex, role, status); // throws it
465 const saml1p::Response* r1 = dynamic_cast<const saml1p::Response*>(response);
467 const saml1p::Status* status = r1->getStatus();
469 const saml1p::StatusCode* sc = status->getStatusCode();
470 const xmltooling::QName* code = sc ? sc->getValue() : nullptr;
471 if (code && *code != saml1p::StatusCode::SUCCESS) {
472 FatalProfileException ex("SAML response contained an error.");
473 ex.addProperty("statusCode", code->toString().c_str());
474 if (sc->getStatusCode()) {
475 code = sc->getStatusCode()->getValue();
477 ex.addProperty("statusCode2", code->toString().c_str());
479 if (status->getStatusMessage()) {
480 auto_ptr_char msg(status->getStatusMessage()->getMessage());
481 if (msg.get() && *msg.get())
482 ex.addProperty("statusMessage", msg.get());
490 void AbstractHandler::fillStatus(saml2p::StatusResponseType& response, const XMLCh* code, const XMLCh* subcode, const char* msg) const
492 saml2p::Status* status = saml2p::StatusBuilder::buildStatus();
493 saml2p::StatusCode* scode = saml2p::StatusCodeBuilder::buildStatusCode();
494 status->setStatusCode(scode);
495 scode->setValue(code);
497 saml2p::StatusCode* ssubcode = saml2p::StatusCodeBuilder::buildStatusCode();
498 scode->setStatusCode(ssubcode);
499 ssubcode->setValue(subcode);
502 pair<bool,bool> flag = getBool("detailedErrors", m_configNS.get());
503 auto_ptr_XMLCh widemsg((flag.first && flag.second) ? msg : "Error processing request.");
504 saml2p::StatusMessage* sm = saml2p::StatusMessageBuilder::buildStatusMessage();
505 status->setStatusMessage(sm);
506 sm->setMessage(widemsg.get());
508 response.setStatus(status);
511 long AbstractHandler::sendMessage(
512 const MessageEncoder& encoder,
514 const char* relayState,
515 const char* destination,
516 const saml2md::RoleDescriptor* role,
517 const Application& application,
518 HTTPResponse& httpResponse,
522 const EntityDescriptor* entity = role ? dynamic_cast<const EntityDescriptor*>(role->getParent()) : nullptr;
523 const PropertySet* relyingParty = application.getRelyingParty(entity);
524 pair<bool,const char*> flag = signIfPossible ? make_pair(true,(const char*)"true") : relyingParty->getString("signing");
525 if (role && flag.first &&
526 (!strcmp(flag.second, "true") ||
527 (encoder.isUserAgentPresent() && !strcmp(flag.second, "front")) ||
528 (!encoder.isUserAgentPresent() && !strcmp(flag.second, "back")))) {
529 CredentialResolver* credResolver=application.getCredentialResolver();
531 Locker credLocker(credResolver);
532 const Credential* cred = nullptr;
533 pair<bool,const char*> keyName = relyingParty->getString("keyName");
534 pair<bool,const XMLCh*> sigalg = relyingParty->getXMLString("signingAlg");
536 MetadataCredentialCriteria mcc(*role);
537 mcc.setUsage(Credential::SIGNING_CREDENTIAL);
539 mcc.getKeyNames().insert(keyName.second);
541 // Using an explicit algorithm, so resolve a credential directly.
542 mcc.setXMLAlgorithm(sigalg.second);
543 cred = credResolver->resolve(&mcc);
546 // Prefer credential based on peer's requirements.
547 pair<const SigningMethod*,const Credential*> p = role->getSigningMethod(*credResolver, mcc);
549 sigalg = make_pair(true, p.first->getAlgorithm());
555 CredentialCriteria cc;
556 cc.setUsage(Credential::SIGNING_CREDENTIAL);
558 cc.getKeyNames().insert(keyName.second);
560 cc.setXMLAlgorithm(sigalg.second);
561 cred = credResolver->resolve(&cc);
565 pair<bool,const XMLCh*> digalg = relyingParty->getXMLString("digestAlg");
566 if (!digalg.first && role) {
567 const DigestMethod* dm = role->getDigestMethod();
569 digalg = make_pair(true, dm->getAlgorithm());
571 return encoder.encode(
580 (digalg.first ? digalg.second : nullptr)
584 m_log.warn("no signing credential resolved, leaving message unsigned");
588 m_log.warn("no credential resolver installed, leaving message unsigned");
593 return encoder.encode(httpResponse, msg, destination, entity, relayState, &application);
598 void AbstractHandler::preservePostData(
599 const Application& application, const HTTPRequest& request, HTTPResponse& response, const char* relayState
602 #ifdef HAVE_STRCASECMP
603 if (strcasecmp(request.getMethod(), "POST")) return;
605 if (stricmp(request.getMethod(), "POST")) return;
608 // No specs mean no save.
609 const PropertySet* props=application.getPropertySet("Sessions");
610 pair<bool,const char*> mech = props ? props->getString("postData") : pair<bool,const char*>(false,nullptr);
612 m_log.info("postData property not supplied, form data will not be preserved across SSO");
616 DDF postData = getPostData(application, request);
617 if (postData.isnull())
620 if (strstr(mech.second,"ss:") == mech.second) {
624 throw ConfigurationException("Unsupported postData mechanism ($1).", params(1, mech.second - 3));
628 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
629 DDFJanitor postjan(postData);
631 StorageService* storage = application.getServiceProvider().getStorageService(mech.second);
635 SAMLConfig::getConfig().generateRandomBytes(rsKey,32);
636 rsKey = SAMLArtifact::toHex(rsKey);
639 if (!storage->createString("PostData", rsKey.c_str(), out.str().c_str(), time(nullptr) + 600))
640 throw IOException("Attempted to insert duplicate storage key.");
641 postkey = string(mech.second-3) + ':' + rsKey;
644 m_log.error("storage-backed PostData mechanism with invalid StorageService ID (%s)", mech.second);
648 else if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
649 DDF out,in = DDF("set::PostData").structure();
650 DDFJanitor jin(in),jout(out);
651 in.addmember("id").string(mech.second);
653 out = application.getServiceProvider().getListenerService()->send(in);
655 throw IOException("StorageService-backed PostData mechanism did not return a state key.");
656 postkey = string(mech.second-3) + ':' + out.string();
659 // Set a cookie with key info.
660 pair<string,const char*> shib_cookie = getPostCookieNameProps(application, relayState);
661 postkey += shib_cookie.second;
662 response.setCookie(shib_cookie.first.c_str(), postkey.c_str());
666 throw ConfigurationException("Unsupported postData mechanism ($1).", params(1,mech.second));
670 DDF AbstractHandler::recoverPostData(
671 const Application& application, const HTTPRequest& request, HTTPResponse& response, const char* relayState
674 // First we need the post recovery cookie.
675 pair<string,const char*> shib_cookie = getPostCookieNameProps(application, relayState);
676 const char* cookie = request.getCookie(shib_cookie.first.c_str());
677 if (!cookie || !*cookie)
681 string exp(shib_cookie.second);
682 exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
683 response.setCookie(shib_cookie.first.c_str(), exp.c_str());
685 // Look for StorageService-backed state of the form "ss:SSID:key".
686 const char* state = cookie;
687 if (strstr(state, "ss:") == state) {
689 const char* key = strchr(state, ':');
691 string ssid = string(cookie).substr(3, key - state);
693 if (!ssid.empty() && *key) {
694 SPConfig& conf = SPConfig::getConfig();
695 if (conf.isEnabled(SPConfig::OutOfProcess)) {
697 StorageService* storage = conf.getServiceProvider()->getStorageService(ssid.c_str());
699 if (storage->readString("PostData", key, &ssid) > 0) {
700 storage->deleteString("PostData", key);
701 istringstream inret(ssid);
707 m_log.error("failed to recover form post data using key (%s)", key);
711 m_log.error("storage-backed PostData with invalid StorageService ID (%s)", ssid.c_str());
715 else if (conf.isEnabled(SPConfig::InProcess)) {
716 DDF in = DDF("get::PostData").structure();
718 in.addmember("id").string(ssid.c_str());
719 in.addmember("key").string(key);
720 DDF out = application.getServiceProvider().getListenerService()->send(in);
724 m_log.error("storageService-backed PostData mechanism did not return preserved data.");
732 long AbstractHandler::sendPostResponse(
733 const Application& application, HTTPResponse& httpResponse, const char* url, DDF& postData
736 HTTPResponse::sanitizeURL(url);
738 const PropertySet* props=application.getPropertySet("Sessions");
739 pair<bool,const char*> postTemplate = props ? props->getString("postTemplate") : pair<bool,const char*>(true,nullptr);
740 if (!postTemplate.first)
741 postTemplate.second = "postTemplate.html";
743 string fname(postTemplate.second);
744 ifstream infile(XMLToolingConfig::getConfig().getPathResolver()->resolve(fname, PathResolver::XMLTOOLING_CFG_FILE).c_str());
746 throw ConfigurationException("Unable to access HTML template ($1).", params(1, fname.c_str()));
747 TemplateParameters respParam;
748 respParam.m_map["action"] = url;
750 // Load the parameters into objects for the template.
751 multimap<string,string>& collection = respParam.m_collectionMap["PostedData"];
752 DDF param = postData.first();
753 while (!param.isnull()) {
754 collection.insert(pair<const string,string>(param.name(), (param.string() ? param.string() : "")));
755 param = postData.next();
759 XMLToolingConfig::getConfig().getTemplateEngine()->run(infile, str, respParam);
761 pair<bool,bool> postExpire = props ? props->getBool("postExpire") : make_pair(false,false);
763 httpResponse.setContentType("text/html");
764 if (!postExpire.first || postExpire.second) {
765 httpResponse.setResponseHeader("Expires", "01-Jan-1997 12:00:00 GMT");
766 httpResponse.setResponseHeader("Cache-Control", "no-cache, no-store, must-revalidate, private");
767 httpResponse.setResponseHeader("Pragma", "no-cache");
769 return httpResponse.sendResponse(str);
772 pair<string,const char*> AbstractHandler::getPostCookieNameProps(const Application& app, const char* relayState) const
774 // Decorates the name of the cookie with the relay state key, if any.
775 // Doing so gives a better assurance that the recovered data really
776 // belongs to the relayed request.
777 pair<string,const char*> shib_cookie=app.getCookieNameProps("_shibpost_");
778 if (strstr(relayState, "cookie:") == relayState) {
779 shib_cookie.first = string("_shibpost_") + (relayState + 7);
781 else if (strstr(relayState, "ss:") == relayState) {
782 const char* pch = strchr(relayState + 3, ':');
784 shib_cookie.first = string("_shibpost_") + (pch + 1);
789 DDF AbstractHandler::getPostData(const Application& application, const HTTPRequest& request) const
791 string contentType = request.getContentType();
792 if (contentType.compare("application/x-www-form-urlencoded") == 0) {
793 const PropertySet* props=application.getPropertySet("Sessions");
794 pair<bool,unsigned int> plimit = props ? props->getUnsignedInt("postLimit") : pair<bool,unsigned int>(false,0);
796 plimit.second = 1024 * 1024;
797 if (plimit.second == 0 || request.getContentLength() <= plimit.second) {
798 CGIParser cgi(request);
799 pair<CGIParser::walker,CGIParser::walker> params = cgi.getParameters(nullptr);
800 if (params.first == params.second)
801 return DDF("parameters").list();
803 DDF ret = DDF("parameters").list();
804 for (; params.first != params.second; ++params.first) {
805 if (!params.first->first.empty()) {
806 child = DDF(params.first->first.c_str()).unsafe_string(params.first->second);
813 m_log.warn("POST limit exceeded, ignoring %d bytes of posted data", request.getContentLength());
817 m_log.info("ignoring POST data with non-standard encoding (%s)", contentType.c_str());
822 pair<bool,bool> AbstractHandler::getBool(const char* name, const SPRequest& request, unsigned int type) const
824 if (type & HANDLER_PROPERTY_REQUEST) {
825 const char* param = request.getParameter(name);
827 return make_pair(true, (*param=='t' || *param=='1'));
830 if (type & HANDLER_PROPERTY_MAP) {
831 pair<bool,bool> ret = request.getRequestSettings().first->getBool(name);
836 if (type & HANDLER_PROPERTY_FIXED) {
837 return getBool(name);
840 return make_pair(false,false);
843 pair<bool,const char*> AbstractHandler::getString(const char* name, const SPRequest& request, unsigned int type) const
845 if (type & HANDLER_PROPERTY_REQUEST) {
846 const char* param = request.getParameter(name);
848 return make_pair(true, param);
851 if (type & HANDLER_PROPERTY_MAP) {
852 pair<bool,const char*> ret = request.getRequestSettings().first->getString(name);
857 if (type & HANDLER_PROPERTY_FIXED) {
858 return getString(name);
861 return pair<bool,const char*>(false,nullptr);
864 pair<bool,unsigned int> AbstractHandler::getUnsignedInt(const char* name, const SPRequest& request, unsigned int type) const
866 if (type & HANDLER_PROPERTY_REQUEST) {
867 const char* param = request.getParameter(name);
869 return pair<bool,unsigned int>(true, strtol(param,nullptr,10));
872 if (type & HANDLER_PROPERTY_MAP) {
873 pair<bool,unsigned int> ret = request.getRequestSettings().first->getUnsignedInt(name);
878 if (type & HANDLER_PROPERTY_FIXED) {
879 return getUnsignedInt(name);
882 return pair<bool,unsigned int>(false,0);
885 pair<bool,int> AbstractHandler::getInt(const char* name, const SPRequest& request, unsigned int type) const
887 if (type & HANDLER_PROPERTY_REQUEST) {
888 const char* param = request.getParameter(name);
890 return pair<bool,int>(true, atoi(param));
893 if (type & HANDLER_PROPERTY_MAP) {
894 pair<bool,int> ret = request.getRequestSettings().first->getInt(name);
899 if (type & HANDLER_PROPERTY_FIXED) {
903 return pair<bool,int>(false,0);