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