Sync post data key size to match new relay state size.
[shibboleth/sp.git] / shibsp / handler / impl / AbstractHandler.cpp
1 /*
2  *  Copyright 2001-2010 Internet2
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /**
18  * AbstractHandler.cpp
19  *
20  * Base class for handlers based on a DOMPropertySet.
21  */
22
23 #include "internal.h"
24 #include "exceptions.h"
25 #include "Application.h"
26 #include "ServiceProvider.h"
27 #include "SPRequest.h"
28 #include "handler/AbstractHandler.h"
29 #include "handler/LogoutHandler.h"
30 #include "remoting/ListenerService.h"
31 #include "util/CGIParser.h"
32 #include "util/SPConstants.h"
33 #include "util/TemplateParameters.h"
34
35 #include <vector>
36 #include <fstream>
37 #include <xmltooling/XMLToolingConfig.h>
38 #include <xmltooling/util/PathResolver.h>
39 #include <xmltooling/util/URLEncoder.h>
40
41
42 #ifndef SHIBSP_LITE
43 # include <saml/exceptions.h>
44 # include <saml/SAMLConfig.h>
45 # include <saml/binding/SAMLArtifact.h>
46 # include <saml/saml1/core/Protocols.h>
47 # include <saml/saml2/core/Protocols.h>
48 # include <saml/saml2/metadata/Metadata.h>
49 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
50 # include <saml/util/SAMLConstants.h>
51 # include <xmltooling/security/Credential.h>
52 # include <xmltooling/security/CredentialResolver.h>
53 # include <xmltooling/util/StorageService.h>
54 using namespace opensaml::saml2md;
55 using namespace opensaml;
56 #else
57 # include "lite/SAMLConstants.h"
58 #endif
59
60 #include <xmltooling/XMLToolingConfig.h>
61 #include <xmltooling/util/URLEncoder.h>
62
63 using namespace shibsp;
64 using namespace samlconstants;
65 using namespace xmltooling;
66 using namespace xercesc;
67 using namespace std;
68
69 namespace shibsp {
70
71     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML1ConsumerFactory;
72     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2ConsumerFactory;
73     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2ArtifactResolutionFactory;
74     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2LogoutFactory;
75     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2NameIDMgmtFactory;
76     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory AssertionLookupFactory;
77     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory DiscoveryFeedFactory;
78     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory MetadataGeneratorFactory;
79     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory StatusHandlerFactory;
80     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SessionHandlerFactory;
81
82     void SHIBSP_DLLLOCAL absolutize(const HTTPRequest& request, string& url) {
83         if (url.empty())
84             url = '/';
85         if (url[0] == '/') {
86             // Compute a URL to the root of the site.
87             int port = request.getPort();
88             const char* scheme = request.getScheme();
89             string root = string(scheme) + "://" + request.getHostname();
90             if ((!strcmp(scheme,"http") && port!=80) || (!strcmp(scheme,"https") && port!=443)) {
91                 ostringstream portstr;
92                 portstr << port;
93                 root += ":" + portstr.str();
94             }
95             url = root + url;
96         }
97     }
98
99     void SHIBSP_DLLLOCAL generateRandomHex(std::string& buf, unsigned int len) {
100         static char DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
101         int r;
102         unsigned char b1,b2;
103         buf.erase();
104         for (unsigned int i=0; i<len; i+=4) {
105             r = rand();
106             b1 = (0x00FF & r);
107             b2 = (0xFF00 & r)  >> 8;
108             buf += (DIGITS[(0xF0 & b1) >> 4 ]);
109             buf += (DIGITS[0x0F & b1]);
110             buf += (DIGITS[(0xF0 & b2) >> 4 ]);
111             buf += (DIGITS[0x0F & b2]);
112         }
113     }
114
115
116 };
117
118 void SHIBSP_API shibsp::registerHandlers()
119 {
120     SPConfig& conf=SPConfig::getConfig();
121
122     conf.AssertionConsumerServiceManager.registerFactory(SAML1_ASSERTION_CONSUMER_SERVICE, SAML1ConsumerFactory);
123     conf.AssertionConsumerServiceManager.registerFactory(SAML1_PROFILE_BROWSER_ARTIFACT, SAML1ConsumerFactory);
124     conf.AssertionConsumerServiceManager.registerFactory(SAML1_PROFILE_BROWSER_POST, SAML1ConsumerFactory);
125     conf.AssertionConsumerServiceManager.registerFactory(SAML20_ASSERTION_CONSUMER_SERVICE, SAML2ConsumerFactory);
126     conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_POST, SAML2ConsumerFactory);
127     conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_POST_SIMPLESIGN, SAML2ConsumerFactory);
128     conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_ARTIFACT, SAML2ConsumerFactory);
129     conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_PAOS, SAML2ConsumerFactory);
130
131     conf.ArtifactResolutionServiceManager.registerFactory(SAML20_ARTIFACT_RESOLUTION_SERVICE, SAML2ArtifactResolutionFactory);
132     conf.ArtifactResolutionServiceManager.registerFactory(SAML20_BINDING_SOAP, SAML2ArtifactResolutionFactory);
133
134     conf.HandlerManager.registerFactory(SAML20_BINDING_URI, AssertionLookupFactory);
135     conf.HandlerManager.registerFactory(DISCOVERY_FEED_HANDLER, DiscoveryFeedFactory);
136     conf.HandlerManager.registerFactory(METADATA_GENERATOR_HANDLER, MetadataGeneratorFactory);
137     conf.HandlerManager.registerFactory(STATUS_HANDLER, StatusHandlerFactory);
138     conf.HandlerManager.registerFactory(SESSION_HANDLER, SessionHandlerFactory);
139
140     conf.SingleLogoutServiceManager.registerFactory(SAML20_LOGOUT_HANDLER, SAML2LogoutFactory);
141     conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_SOAP, SAML2LogoutFactory);
142     conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_HTTP_REDIRECT, SAML2LogoutFactory);
143     conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_HTTP_POST, SAML2LogoutFactory);
144     conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_HTTP_POST_SIMPLESIGN, SAML2LogoutFactory);
145     conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_HTTP_ARTIFACT, SAML2LogoutFactory);
146
147     conf.ManageNameIDServiceManager.registerFactory(SAML20_NAMEID_MGMT_SERVICE, SAML2NameIDMgmtFactory);
148     conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_SOAP, SAML2NameIDMgmtFactory);
149     conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_HTTP_REDIRECT, SAML2NameIDMgmtFactory);
150     conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_HTTP_POST, SAML2NameIDMgmtFactory);
151     conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_HTTP_POST_SIMPLESIGN, SAML2NameIDMgmtFactory);
152     conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_HTTP_ARTIFACT, SAML2NameIDMgmtFactory);
153 }
154
155 Handler::Handler()
156 {
157 }
158
159 Handler::~Handler()
160 {
161 }
162
163 #ifndef SHIBSP_LITE
164
165 void Handler::generateMetadata(SPSSODescriptor& role, const char* handlerURL) const
166 {
167 }
168
169 #endif
170
171 const XMLCh* Handler::getProtocolFamily() const
172 {
173     return nullptr;
174 }
175
176 void Handler::log(SPRequest::SPLogLevel level, const string& msg) const
177 {
178     Category::getInstance(SHIBSP_LOGCAT".Handler").log(
179         (level == SPRequest::SPDebug ? Priority::DEBUG :
180         (level == SPRequest::SPInfo ? Priority::INFO :
181         (level == SPRequest::SPWarn ? Priority::WARN :
182         (level == SPRequest::SPError ? Priority::ERROR : Priority::CRIT)))),
183         msg
184         );
185 }
186
187 void Handler::preserveRelayState(const Application& application, HTTPResponse& response, string& relayState) const
188 {
189     // The empty string implies no state to deal with.
190     if (relayState.empty())
191         return;
192
193     // No setting means just pass state by value.
194     pair<bool,const char*> mech = getString("relayState");
195     if (!mech.first) {
196         // Check for setting on Sessions element.
197         const PropertySet* sessionprop = application.getPropertySet("Sessions");
198         if (sessionprop)
199             mech = sessionprop->getString("relayState");
200     }
201     if (!mech.first || !mech.second || !*mech.second)
202         return;
203
204     if (!strcmp(mech.second, "cookie")) {
205         // Here we store the state in a cookie and send a fixed
206         // value so we can recognize it on the way back.
207         if (relayState.find("cookie:") != 0) {
208             const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
209             pair<string,const char*> shib_cookie=application.getCookieNameProps("_shibstate_");
210             string stateval = urlenc->encode(relayState.c_str()) + shib_cookie.second;
211             // Generate a random key for the cookie name instead of the fixed name.
212             string rsKey;
213             generateRandomHex(rsKey,5);
214             shib_cookie.first = "_shibstate_" + rsKey;
215             response.setCookie(shib_cookie.first.c_str(),stateval.c_str());
216             relayState = "cookie:" + rsKey;
217         }
218     }
219     else if (strstr(mech.second,"ss:")==mech.second) {
220         if (relayState.find("ss:") != 0) {
221             mech.second+=3;
222             if (*mech.second) {
223                 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
224 #ifndef SHIBSP_LITE
225                     StorageService* storage = application.getServiceProvider().getStorageService(mech.second);
226                     if (storage) {
227                         string rsKey;
228                         generateRandomHex(rsKey,32);
229                         if (!storage->createString("RelayState", rsKey.c_str(), relayState.c_str(), time(nullptr) + 600))
230                             throw IOException("Attempted to insert duplicate storage key.");
231                         relayState = string(mech.second-3) + ':' + rsKey;
232                     }
233                     else {
234                         string msg("Storage-backed RelayState with invalid StorageService ID (");
235                         msg = msg + mech.second+ ')';
236                         log(SPRequest::SPError, msg);
237                         relayState.erase();
238                     }
239 #endif
240                 }
241                 else if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
242                     DDF out,in = DDF("set::RelayState").structure();
243                     in.addmember("id").string(mech.second);
244                     in.addmember("value").unsafe_string(relayState.c_str());
245                     DDFJanitor jin(in),jout(out);
246                     out = application.getServiceProvider().getListenerService()->send(in);
247                     if (!out.isstring())
248                         throw IOException("StorageService-backed RelayState mechanism did not return a state key.");
249                     relayState = string(mech.second-3) + ':' + out.string();
250                 }
251             }
252         }
253     }
254     else
255         throw ConfigurationException("Unsupported relayState mechanism ($1).", params(1,mech.second));
256 }
257
258 void Handler::recoverRelayState(
259     const Application& application, const HTTPRequest& request, HTTPResponse& response, string& relayState, bool clear
260     ) const
261 {
262     SPConfig& conf = SPConfig::getConfig();
263
264     // Look for StorageService-backed state of the form "ss:SSID:key".
265     const char* state = relayState.c_str();
266     if (strstr(state,"ss:")==state) {
267         state += 3;
268         const char* key = strchr(state,':');
269         if (key) {
270             string ssid = relayState.substr(3, key - state);
271             key++;
272             if (!ssid.empty() && *key) {
273                 if (conf.isEnabled(SPConfig::OutOfProcess)) {
274 #ifndef SHIBSP_LITE
275                     StorageService* storage = conf.getServiceProvider()->getStorageService(ssid.c_str());
276                     if (storage) {
277                         ssid = key;
278                         if (storage->readString("RelayState",ssid.c_str(),&relayState) > 0) {
279                             if (clear)
280                                 storage->deleteString("RelayState",ssid.c_str());
281                             absolutize(request, relayState);
282                             return;
283                         }
284                         else
285                             relayState.erase();
286                     }
287                     else {
288                         string msg("Storage-backed RelayState with invalid StorageService ID (");
289                         msg += ssid + ')';
290                         log(SPRequest::SPError, msg);
291                         relayState.erase();
292                     }
293 #endif
294                 }
295                 else if (conf.isEnabled(SPConfig::InProcess)) {
296                     DDF out,in = DDF("get::RelayState").structure();
297                     in.addmember("id").string(ssid.c_str());
298                     in.addmember("key").string(key);
299                     in.addmember("clear").integer(clear ? 1 : 0);
300                     DDFJanitor jin(in),jout(out);
301                     out = application.getServiceProvider().getListenerService()->send(in);
302                     if (!out.isstring()) {
303                         log(SPRequest::SPError, "StorageService-backed RelayState mechanism did not return a state value.");
304                         relayState.erase();
305                     }
306                     else {
307                         relayState = out.string();
308                         absolutize(request, relayState);
309                         return;
310                     }
311                 }
312             }
313         }
314     }
315
316     // Look for cookie-backed state of the form "cookie:key".
317     if (strstr(state,"cookie:")==state) {
318         state += 7;
319         if (*state) {
320             // Pull the value from the "relay state" cookie.
321             pair<string,const char*> relay_cookie = application.getCookieNameProps("_shibstate_");
322             relay_cookie.first = string("_shibstate_") + state;
323             state = request.getCookie(relay_cookie.first.c_str());
324             if (state && *state) {
325                 // URL-decode the value.
326                 char* rscopy=strdup(state);
327                 XMLToolingConfig::getConfig().getURLEncoder()->decode(rscopy);
328                 relayState = rscopy;
329                 free(rscopy);
330
331                 if (clear) {
332                     string exp(relay_cookie.second);
333                     exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
334                     response.setCookie(relay_cookie.first.c_str(), exp.c_str());
335                 }
336                 absolutize(request, relayState);
337                 return;
338             }
339         }
340
341         relayState.erase();
342     }
343
344     // Check for "default" value (or the old "cookie" value that might come from stale bookmarks).
345     if (relayState.empty() || relayState == "default" || relayState == "cookie") {
346         pair<bool,const char*> homeURL=application.getString("homeURL");
347         if (homeURL.first)
348             relayState = homeURL.second;
349         else
350             relayState = '/';
351     }
352
353     absolutize(request, relayState);
354 }
355
356 AbstractHandler::AbstractHandler(
357     const DOMElement* e, Category& log, DOMNodeFilter* filter, const map<string,string>* remapper
358     ) : m_log(log), m_configNS(shibspconstants::SHIB2SPCONFIG_NS) {
359     load(e,nullptr,filter,remapper);
360 }
361
362 AbstractHandler::~AbstractHandler()
363 {
364 }
365
366 void AbstractHandler::log(SPRequest::SPLogLevel level, const string& msg) const
367 {
368     m_log.log(
369         (level == SPRequest::SPDebug ? Priority::DEBUG :
370         (level == SPRequest::SPInfo ? Priority::INFO :
371         (level == SPRequest::SPWarn ? Priority::WARN :
372         (level == SPRequest::SPError ? Priority::ERROR : Priority::CRIT)))),
373         msg
374         );
375 }
376
377 #ifndef SHIBSP_LITE
378
379 const char* Handler::getType() const
380 {
381     return getString("type").second;
382 }
383
384 void AbstractHandler::checkError(const XMLObject* response, const saml2md::RoleDescriptor* role) const
385 {
386     const saml2p::StatusResponseType* r2 = dynamic_cast<const saml2p::StatusResponseType*>(response);
387     if (r2) {
388         const saml2p::Status* status = r2->getStatus();
389         if (status) {
390             const saml2p::StatusCode* sc = status->getStatusCode();
391             const XMLCh* code = sc ? sc->getValue() : nullptr;
392             if (code && !XMLString::equals(code,saml2p::StatusCode::SUCCESS)) {
393                 FatalProfileException ex("SAML response contained an error.");
394                 annotateException(&ex, role, status);   // throws it
395             }
396         }
397     }
398
399     const saml1p::Response* r1 = dynamic_cast<const saml1p::Response*>(response);
400     if (r1) {
401         const saml1p::Status* status = r1->getStatus();
402         if (status) {
403             const saml1p::StatusCode* sc = status->getStatusCode();
404             const xmltooling::QName* code = sc ? sc->getValue() : nullptr;
405             if (code && *code != saml1p::StatusCode::SUCCESS) {
406                 FatalProfileException ex("SAML response contained an error.");
407                 ex.addProperty("statusCode", code->toString().c_str());
408                 if (sc->getStatusCode()) {
409                     code = sc->getStatusCode()->getValue();
410                     if (code)
411                         ex.addProperty("statusCode2", code->toString().c_str());
412                 }
413                 if (status->getStatusMessage()) {
414                     auto_ptr_char msg(status->getStatusMessage()->getMessage());
415                     if (msg.get() && *msg.get())
416                         ex.addProperty("statusMessage", msg.get());
417                 }
418                 ex.raise();
419             }
420         }
421     }
422 }
423
424 void AbstractHandler::fillStatus(saml2p::StatusResponseType& response, const XMLCh* code, const XMLCh* subcode, const char* msg) const
425 {
426     saml2p::Status* status = saml2p::StatusBuilder::buildStatus();
427     saml2p::StatusCode* scode = saml2p::StatusCodeBuilder::buildStatusCode();
428     status->setStatusCode(scode);
429     scode->setValue(code);
430     if (subcode) {
431         saml2p::StatusCode* ssubcode = saml2p::StatusCodeBuilder::buildStatusCode();
432         scode->setStatusCode(ssubcode);
433         ssubcode->setValue(subcode);
434     }
435     if (msg) {
436         pair<bool,bool> flag = getBool("detailedErrors", m_configNS.get());
437         auto_ptr_XMLCh widemsg((flag.first && flag.second) ? msg : "Error processing request.");
438         saml2p::StatusMessage* sm = saml2p::StatusMessageBuilder::buildStatusMessage();
439         status->setStatusMessage(sm);
440         sm->setMessage(widemsg.get());
441     }
442     response.setStatus(status);
443 }
444
445 long AbstractHandler::sendMessage(
446     const MessageEncoder& encoder,
447     XMLObject* msg,
448     const char* relayState,
449     const char* destination,
450     const saml2md::RoleDescriptor* role,
451     const Application& application,
452     HTTPResponse& httpResponse,
453     bool signIfPossible
454     ) const
455 {
456     const EntityDescriptor* entity = role ? dynamic_cast<const EntityDescriptor*>(role->getParent()) : nullptr;
457     const PropertySet* relyingParty = application.getRelyingParty(entity);
458     pair<bool,const char*> flag = signIfPossible ? make_pair(true,(const char*)"true") : relyingParty->getString("signing");
459     if (role && flag.first &&
460         (!strcmp(flag.second, "true") ||
461             (encoder.isUserAgentPresent() && !strcmp(flag.second, "front")) ||
462             (!encoder.isUserAgentPresent() && !strcmp(flag.second, "back")))) {
463         CredentialResolver* credResolver=application.getCredentialResolver();
464         if (credResolver) {
465             Locker credLocker(credResolver);
466             const Credential* cred = nullptr;
467             pair<bool,const char*> keyName = relyingParty->getString("keyName");
468             pair<bool,const XMLCh*> sigalg = relyingParty->getXMLString("signingAlg");
469             if (role) {
470                 MetadataCredentialCriteria mcc(*role);
471                 mcc.setUsage(Credential::SIGNING_CREDENTIAL);
472                 if (keyName.first)
473                     mcc.getKeyNames().insert(keyName.second);
474                 if (sigalg.first) {
475                     // Using an explicit algorithm, so resolve a credential directly.
476                     mcc.setXMLAlgorithm(sigalg.second);
477                     cred = credResolver->resolve(&mcc);
478                 }
479                 else {
480                     // Prefer credential based on peer's requirements.
481                     pair<const SigningMethod*,const Credential*> p = role->getSigningMethod(*credResolver, mcc);
482                     if (p.first)
483                         sigalg = make_pair(true, p.first->getAlgorithm());
484                     if (p.second)
485                         cred = p.second;
486                 }
487             }
488             else {
489                 CredentialCriteria cc;
490                 cc.setUsage(Credential::SIGNING_CREDENTIAL);
491                 if (keyName.first)
492                     cc.getKeyNames().insert(keyName.second);
493                 if (sigalg.first)
494                     cc.setXMLAlgorithm(sigalg.second);
495                 cred = credResolver->resolve(&cc);
496             }
497             if (cred) {
498                 // Signed request.
499                 pair<bool,const XMLCh*> digalg = relyingParty->getXMLString("digestAlg");
500                 if (!digalg.first && role) {
501                     const DigestMethod* dm = role->getDigestMethod();
502                     if (dm)
503                         digalg = make_pair(true, dm->getAlgorithm());
504                 }
505                 return encoder.encode(
506                     httpResponse,
507                     msg,
508                     destination,
509                     entity,
510                     relayState,
511                     &application,
512                     cred,
513                     sigalg.second,
514                     (digalg.first ? digalg.second : nullptr)
515                     );
516             }
517             else {
518                 m_log.warn("no signing credential resolved, leaving message unsigned");
519             }
520         }
521         else {
522             m_log.warn("no credential resolver installed, leaving message unsigned");
523         }
524     }
525
526     // Unsigned request.
527     return encoder.encode(httpResponse, msg, destination, entity, relayState, &application);
528 }
529
530 #endif
531
532 void AbstractHandler::preservePostData(
533     const Application& application, const HTTPRequest& request, HTTPResponse& response, const char* relayState
534     ) const
535 {
536 #ifdef HAVE_STRCASECMP
537     if (strcasecmp(request.getMethod(), "POST")) return;
538 #else
539     if (stricmp(request.getMethod(), "POST")) return;
540 #endif
541
542     // No specs mean no save.
543     const PropertySet* props=application.getPropertySet("Sessions");
544     pair<bool,const char*> mech = props ? props->getString("postData") : pair<bool,const char*>(false,nullptr);
545     if (!mech.first) {
546         m_log.info("postData property not supplied, form data will not be preserved across SSO");
547         return;
548     }
549
550     DDF postData = getPostData(application, request);
551     if (postData.isnull())
552         return;
553
554     if (strstr(mech.second,"ss:") == mech.second) {
555         mech.second+=3;
556         if (!*mech.second) {
557             postData.destroy();
558             throw ConfigurationException("Unsupported postData mechanism ($1).", params(1, mech.second - 3));
559         }
560
561         string postkey;
562         if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
563             DDFJanitor postjan(postData);
564 #ifndef SHIBSP_LITE
565             StorageService* storage = application.getServiceProvider().getStorageService(mech.second);
566             if (storage) {
567                 // Use a random key
568                 string rsKey;
569                 SAMLConfig::getConfig().generateRandomBytes(rsKey,32);
570                 rsKey = SAMLArtifact::toHex(rsKey);
571                 ostringstream out;
572                 out << postData;
573                 if (!storage->createString("PostData", rsKey.c_str(), out.str().c_str(), time(nullptr) + 600))
574                     throw IOException("Attempted to insert duplicate storage key.");
575                 postkey = string(mech.second-3) + ':' + rsKey;
576             }
577             else {
578                 m_log.error("storage-backed PostData mechanism with invalid StorageService ID (%s)", mech.second);
579             }
580 #endif
581         }
582         else if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
583             DDF out,in = DDF("set::PostData").structure();
584             DDFJanitor jin(in),jout(out);
585             in.addmember("id").string(mech.second);
586             in.add(postData);
587             out = application.getServiceProvider().getListenerService()->send(in);
588             if (!out.isstring())
589                 throw IOException("StorageService-backed PostData mechanism did not return a state key.");
590             postkey = string(mech.second-3) + ':' + out.string();
591         }
592
593         // Set a cookie with key info.
594         pair<string,const char*> shib_cookie = getPostCookieNameProps(application, relayState);
595         postkey += shib_cookie.second;
596         response.setCookie(shib_cookie.first.c_str(), postkey.c_str());
597     }
598     else {
599         postData.destroy();
600         throw ConfigurationException("Unsupported postData mechanism ($1).", params(1,mech.second));
601     }
602 }
603
604 DDF AbstractHandler::recoverPostData(
605     const Application& application, const HTTPRequest& request, HTTPResponse& response, const char* relayState
606     ) const
607 {
608     // First we need the post recovery cookie.
609     pair<string,const char*> shib_cookie = getPostCookieNameProps(application, relayState);
610     const char* cookie = request.getCookie(shib_cookie.first.c_str());
611     if (!cookie || !*cookie)
612         return DDF();
613
614     // Clear the cookie.
615     string exp(shib_cookie.second);
616     exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
617     response.setCookie(shib_cookie.first.c_str(), exp.c_str());
618
619     // Look for StorageService-backed state of the form "ss:SSID:key".
620     const char* state = cookie;
621     if (strstr(state, "ss:") == state) {
622         state += 3;
623         const char* key = strchr(state, ':');
624         if (key) {
625             string ssid = string(cookie).substr(3, key - state);
626             key++;
627             if (!ssid.empty() && *key) {
628                 SPConfig& conf = SPConfig::getConfig();
629                 if (conf.isEnabled(SPConfig::OutOfProcess)) {
630 #ifndef SHIBSP_LITE
631                     StorageService* storage = conf.getServiceProvider()->getStorageService(ssid.c_str());
632                     if (storage) {
633                         if (storage->readString("PostData", key, &ssid) > 0) {
634                             storage->deleteString("PostData", key);
635                             istringstream inret(ssid);
636                             DDF ret;
637                             inret >> ret;
638                             return ret;
639                         }
640                         else {
641                             m_log.error("failed to recover form post data using key (%s)", key);
642                         }
643                     }
644                     else {
645                         m_log.error("storage-backed PostData with invalid StorageService ID (%s)", ssid.c_str());
646                     }
647 #endif
648                 }
649                 else if (conf.isEnabled(SPConfig::InProcess)) {
650                     DDF in = DDF("get::PostData").structure();
651                     DDFJanitor jin(in);
652                     in.addmember("id").string(ssid.c_str());
653                     in.addmember("key").string(key);
654                     DDF out = application.getServiceProvider().getListenerService()->send(in);
655                     if (out.islist())
656                         return out;
657                     out.destroy();
658                     m_log.error("storageService-backed PostData mechanism did not return preserved data.");
659                 }
660             }
661         }
662     }
663     return DDF();
664 }
665
666 long AbstractHandler::sendPostResponse(
667     const Application& application, HTTPResponse& httpResponse, const char* url, DDF& postData
668     ) const
669 {
670     HTTPResponse::sanitizeURL(url);
671
672     const PropertySet* props=application.getPropertySet("Sessions");
673     pair<bool,const char*> postTemplate = props ? props->getString("postTemplate") : pair<bool,const char*>(true,nullptr);
674     if (!postTemplate.first)
675         postTemplate.second = "postTemplate.html";
676
677     string fname(postTemplate.second);
678     ifstream infile(XMLToolingConfig::getConfig().getPathResolver()->resolve(fname, PathResolver::XMLTOOLING_CFG_FILE).c_str());
679     if (!infile)
680         throw ConfigurationException("Unable to access HTML template ($1).", params(1, fname.c_str()));
681     TemplateParameters respParam;
682     respParam.m_map["action"] = url;
683
684     // Load the parameters into objects for the template.
685     multimap<string,string>& collection = respParam.m_collectionMap["PostedData"];
686     DDF param = postData.first();
687     while (!param.isnull()) {
688         collection.insert(pair<const string,string>(param.name(), (param.string() ? param.string() : "")));
689         param = postData.next();
690     }
691
692     stringstream str;
693     XMLToolingConfig::getConfig().getTemplateEngine()->run(infile, str, respParam);
694
695     pair<bool,bool> postExpire = props ? props->getBool("postExpire") : make_pair(false,false);
696
697     httpResponse.setContentType("text/html");
698     if (!postExpire.first || postExpire.second) {
699         httpResponse.setResponseHeader("Expires", "01-Jan-1997 12:00:00 GMT");
700         httpResponse.setResponseHeader("Cache-Control", "no-cache, no-store, must-revalidate, private");
701         httpResponse.setResponseHeader("Pragma", "no-cache");
702     }
703     return httpResponse.sendResponse(str);
704 }
705
706 pair<string,const char*> AbstractHandler::getPostCookieNameProps(const Application& app, const char* relayState) const
707 {
708     // Decorates the name of the cookie with the relay state key, if any.
709     // Doing so gives a better assurance that the recovered data really
710     // belongs to the relayed request.
711     pair<string,const char*> shib_cookie=app.getCookieNameProps("_shibpost_");
712     if (strstr(relayState, "cookie:") == relayState) {
713         shib_cookie.first = string("_shibpost_") + (relayState + 7);
714     }
715     else if (strstr(relayState, "ss:") == relayState) {
716         const char* pch = strchr(relayState + 3, ':');
717         if (pch)
718             shib_cookie.first = string("_shibpost_") + (pch + 1);
719     }
720     return shib_cookie;
721 }
722
723 DDF AbstractHandler::getPostData(const Application& application, const HTTPRequest& request) const
724 {
725     string contentType = request.getContentType();
726     if (contentType.compare("application/x-www-form-urlencoded") == 0) {
727         const PropertySet* props=application.getPropertySet("Sessions");
728         pair<bool,unsigned int> plimit = props ? props->getUnsignedInt("postLimit") : pair<bool,unsigned int>(false,0);
729         if (!plimit.first)
730             plimit.second = 1024 * 1024;
731         if (plimit.second == 0 || request.getContentLength() <= plimit.second) {
732             CGIParser cgi(request);
733             pair<CGIParser::walker,CGIParser::walker> params = cgi.getParameters(nullptr);
734             if (params.first == params.second)
735                 return DDF("parameters").list();
736             DDF child;
737             DDF ret = DDF("parameters").list();
738             for (; params.first != params.second; ++params.first) {
739                 if (!params.first->first.empty()) {
740                     child = DDF(params.first->first.c_str()).unsafe_string(params.first->second);
741                     ret.add(child);
742                 }
743             }
744             return ret;
745         }
746         else {
747             m_log.warn("POST limit exceeded, ignoring %d bytes of posted data", request.getContentLength());
748         }
749     }
750     else {
751         m_log.info("ignoring POST data with non-standard encoding (%s)", contentType.c_str());
752     }
753     return DDF();
754 }
755
756 pair<bool,bool> AbstractHandler::getBool(const char* name, const SPRequest& request, unsigned int type) const
757 {
758     if (type & HANDLER_PROPERTY_REQUEST) {
759         const char* param = request.getParameter(name);
760         if (param && *param)
761             return make_pair(true, (*param=='t' || *param=='1'));
762     }
763     
764     if (type & HANDLER_PROPERTY_MAP) {
765         pair<bool,bool> ret = request.getRequestSettings().first->getBool(name);
766         if (ret.first)
767             return ret;
768     }
769
770     if (type & HANDLER_PROPERTY_FIXED) {
771         return getBool(name);
772     }
773
774     return make_pair(false,false);
775 }
776
777 pair<bool,const char*> AbstractHandler::getString(const char* name, const SPRequest& request, unsigned int type) const
778 {
779     if (type & HANDLER_PROPERTY_REQUEST) {
780         const char* param = request.getParameter(name);
781         if (param && *param)
782             return make_pair(true, param);
783     }
784     
785     if (type & HANDLER_PROPERTY_MAP) {
786         pair<bool,const char*> ret = request.getRequestSettings().first->getString(name);
787         if (ret.first)
788             return ret;
789     }
790
791     if (type & HANDLER_PROPERTY_FIXED) {
792         return getString(name);
793     }
794
795     return pair<bool,const char*>(false,nullptr);
796 }
797
798 pair<bool,unsigned int> AbstractHandler::getUnsignedInt(const char* name, const SPRequest& request, unsigned int type) const
799 {
800     if (type & HANDLER_PROPERTY_REQUEST) {
801         const char* param = request.getParameter(name);
802         if (param && *param)
803             return pair<bool,unsigned int>(true, strtol(param,nullptr,10));
804     }
805     
806     if (type & HANDLER_PROPERTY_MAP) {
807         pair<bool,unsigned int> ret = request.getRequestSettings().first->getUnsignedInt(name);
808         if (ret.first)
809             return ret;
810     }
811
812     if (type & HANDLER_PROPERTY_FIXED) {
813         return getUnsignedInt(name);
814     }
815
816     return pair<bool,unsigned int>(false,0);
817 }
818
819 pair<bool,int> AbstractHandler::getInt(const char* name, const SPRequest& request, unsigned int type) const
820 {
821     if (type & HANDLER_PROPERTY_REQUEST) {
822         const char* param = request.getParameter(name);
823         if (param && *param)
824             return pair<bool,int>(true, atoi(param));
825     }
826     
827     if (type & HANDLER_PROPERTY_MAP) {
828         pair<bool,int> ret = request.getRequestSettings().first->getInt(name);
829         if (ret.first)
830             return ret;
831     }
832
833     if (type & HANDLER_PROPERTY_FIXED) {
834         return getInt(name);
835     }
836
837     return pair<bool,int>(false,0);
838 }