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