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