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