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