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