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