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