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