ca7e3c2cc0205d7c2f31c0a02dec08ab480d391f
[shibboleth/sp.git] / shibsp / handler / impl / AbstractHandler.cpp
1 /*\r
2  *  Copyright 2001-2009 Internet2\r
3  *\r
4  * Licensed under the Apache License, Version 2.0 (the "License");\r
5  * you may not use this file except in compliance with the License.\r
6  * You may obtain a copy of the License at\r
7  *\r
8  *     http://www.apache.org/licenses/LICENSE-2.0\r
9  *\r
10  * Unless required by applicable law or agreed to in writing, software\r
11  * distributed under the License is distributed on an "AS IS" BASIS,\r
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
13  * See the License for the specific language governing permissions and\r
14  * limitations under the License.\r
15  */\r
16 \r
17 /**\r
18  * AbstractHandler.cpp\r
19  *\r
20  * Base class for handlers based on a DOMPropertySet.\r
21  */\r
22 \r
23 #include "internal.h"\r
24 #include "exceptions.h"\r
25 #include "Application.h"\r
26 #include "ServiceProvider.h"\r
27 #include "SPRequest.h"\r
28 #include "handler/AbstractHandler.h"\r
29 #include "handler/LogoutHandler.h"\r
30 #include "remoting/ListenerService.h"\r
31 #include "util/CGIParser.h"\r
32 #include "util/SPConstants.h"\r
33 #include "util/TemplateParameters.h"\r
34 \r
35 #include <vector>\r
36 #include <fstream>\r
37 #include <xmltooling/XMLToolingConfig.h>\r
38 #include <xmltooling/util/PathResolver.h>\r
39 #include <xmltooling/util/URLEncoder.h>\r
40 \r
41 \r
42 #ifndef SHIBSP_LITE\r
43 # include <saml/exceptions.h>\r
44 # include <saml/SAMLConfig.h>\r
45 # include <saml/binding/SAMLArtifact.h>\r
46 # include <saml/saml1/core/Protocols.h>\r
47 # include <saml/saml2/core/Protocols.h>\r
48 # include <saml/saml2/metadata/Metadata.h>\r
49 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>\r
50 # include <saml/util/SAMLConstants.h>\r
51 # include <xmltooling/security/Credential.h>\r
52 # include <xmltooling/security/CredentialResolver.h>\r
53 # include <xmltooling/util/StorageService.h>\r
54 using namespace opensaml::saml2md;\r
55 using namespace opensaml;\r
56 #else\r
57 # include "lite/SAMLConstants.h"\r
58 #endif\r
59 \r
60 #include <xmltooling/XMLToolingConfig.h>\r
61 #include <xmltooling/util/URLEncoder.h>\r
62 \r
63 using namespace shibsp;\r
64 using namespace samlconstants;\r
65 using namespace xmltooling;\r
66 using namespace xercesc;\r
67 using namespace std;\r
68 \r
69 namespace shibsp {\r
70     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML1ConsumerFactory;\r
71     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2ConsumerFactory;\r
72     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2ArtifactResolutionFactory;\r
73     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory ChainingLogoutInitiatorFactory;\r
74     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory LocalLogoutInitiatorFactory;\r
75     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2LogoutInitiatorFactory;\r
76     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2LogoutFactory;\r
77     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2NameIDMgmtFactory;\r
78     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory AssertionLookupFactory;\r
79     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory MetadataGeneratorFactory;\r
80     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory StatusHandlerFactory;\r
81     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SessionHandlerFactory;\r
82 \r
83     void SHIBSP_DLLLOCAL generateRandomHex(std::string& buf, unsigned int len) {\r
84         static char DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};\r
85         int r;\r
86         unsigned char b1,b2;\r
87         buf.erase();\r
88         for (unsigned int i=0; i<len; i+=4) {\r
89             r = rand();\r
90             b1 = (0x00FF & r);\r
91             b2 = (0xFF00 & r)  >> 8;\r
92             buf += (DIGITS[(0xF0 & b1) >> 4 ]);\r
93             buf += (DIGITS[0x0F & b1]);\r
94             buf += (DIGITS[(0xF0 & b2) >> 4 ]);\r
95             buf += (DIGITS[0x0F & b2]);\r
96         }\r
97     }\r
98 };\r
99 \r
100 void SHIBSP_API shibsp::registerHandlers()\r
101 {\r
102     SPConfig& conf=SPConfig::getConfig();\r
103 \r
104     conf.AssertionConsumerServiceManager.registerFactory(SAML1_PROFILE_BROWSER_ARTIFACT, SAML1ConsumerFactory);\r
105     conf.AssertionConsumerServiceManager.registerFactory(SAML1_PROFILE_BROWSER_POST, SAML1ConsumerFactory);\r
106     conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_POST, SAML2ConsumerFactory);\r
107     conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_POST_SIMPLESIGN, SAML2ConsumerFactory);\r
108     conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_ARTIFACT, SAML2ConsumerFactory);\r
109     conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_PAOS, SAML2ConsumerFactory);\r
110 \r
111     conf.ArtifactResolutionServiceManager.registerFactory(SAML20_BINDING_SOAP, SAML2ArtifactResolutionFactory);\r
112 \r
113     conf.HandlerManager.registerFactory(SAML20_BINDING_URI, AssertionLookupFactory);\r
114     conf.HandlerManager.registerFactory(METADATA_GENERATOR_HANDLER, MetadataGeneratorFactory);\r
115     conf.HandlerManager.registerFactory(STATUS_HANDLER, StatusHandlerFactory);\r
116     conf.HandlerManager.registerFactory(SESSION_HANDLER, SessionHandlerFactory);\r
117 \r
118     conf.LogoutInitiatorManager.registerFactory(CHAINING_LOGOUT_INITIATOR, ChainingLogoutInitiatorFactory);\r
119     conf.LogoutInitiatorManager.registerFactory(LOCAL_LOGOUT_INITIATOR, LocalLogoutInitiatorFactory);\r
120     conf.LogoutInitiatorManager.registerFactory(SAML2_LOGOUT_INITIATOR, SAML2LogoutInitiatorFactory);\r
121     conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_SOAP, SAML2LogoutFactory);\r
122     conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_HTTP_REDIRECT, SAML2LogoutFactory);\r
123     conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_HTTP_POST, SAML2LogoutFactory);\r
124     conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_HTTP_POST_SIMPLESIGN, SAML2LogoutFactory);\r
125     conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_HTTP_ARTIFACT, SAML2LogoutFactory);\r
126 \r
127     conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_SOAP, SAML2NameIDMgmtFactory);\r
128     conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_HTTP_REDIRECT, SAML2NameIDMgmtFactory);\r
129     conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_HTTP_POST, SAML2NameIDMgmtFactory);\r
130     conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_HTTP_POST_SIMPLESIGN, SAML2NameIDMgmtFactory);\r
131     conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_HTTP_ARTIFACT, SAML2NameIDMgmtFactory);\r
132 }\r
133 \r
134 Handler::Handler()\r
135 {\r
136 }\r
137 \r
138 Handler::~Handler()\r
139 {\r
140 }\r
141 \r
142 AbstractHandler::AbstractHandler(\r
143     const DOMElement* e, Category& log, DOMNodeFilter* filter, const map<string,string>* remapper\r
144     ) : m_log(log), m_configNS(shibspconstants::SHIB2SPCONFIG_NS) {\r
145     load(e,NULL,filter,remapper);\r
146 }\r
147 \r
148 AbstractHandler::~AbstractHandler()\r
149 {\r
150 }\r
151 \r
152 #ifndef SHIBSP_LITE\r
153 \r
154 const char* Handler::getType() const\r
155 {\r
156     return getString("type").second;\r
157 }\r
158 \r
159 void AbstractHandler::checkError(const XMLObject* response, const saml2md::RoleDescriptor* role) const\r
160 {\r
161     const saml2p::StatusResponseType* r2 = dynamic_cast<const saml2p::StatusResponseType*>(response);\r
162     if (r2) {\r
163         const saml2p::Status* status = r2->getStatus();\r
164         if (status) {\r
165             const saml2p::StatusCode* sc = status->getStatusCode();\r
166             const XMLCh* code = sc ? sc->getValue() : NULL;\r
167             if (code && !XMLString::equals(code,saml2p::StatusCode::SUCCESS)) {\r
168                 FatalProfileException ex("SAML response contained an error.");\r
169                 annotateException(&ex, role, status);   // throws it\r
170             }\r
171         }\r
172     }\r
173 \r
174     const saml1p::Response* r1 = dynamic_cast<const saml1p::Response*>(response);\r
175     if (r1) {\r
176         const saml1p::Status* status = r1->getStatus();\r
177         if (status) {\r
178             const saml1p::StatusCode* sc = status->getStatusCode();\r
179             const xmltooling::QName* code = sc ? sc->getValue() : NULL;\r
180             if (code && *code != saml1p::StatusCode::SUCCESS) {\r
181                 FatalProfileException ex("SAML response contained an error.");\r
182                 ex.addProperty("statusCode", code->toString().c_str());\r
183                 if (sc->getStatusCode()) {\r
184                     code = sc->getStatusCode()->getValue();\r
185                     if (code)\r
186                         ex.addProperty("statusCode2", code->toString().c_str());\r
187                 }\r
188                 if (status->getStatusMessage()) {\r
189                     auto_ptr_char msg(status->getStatusMessage()->getMessage());\r
190                     if (msg.get() && *msg.get())\r
191                         ex.addProperty("statusMessage", msg.get());\r
192                 }\r
193                 ex.raise();\r
194             }\r
195         }\r
196     }\r
197 }\r
198 \r
199 void AbstractHandler::fillStatus(saml2p::StatusResponseType& response, const XMLCh* code, const XMLCh* subcode, const char* msg) const\r
200 {\r
201     saml2p::Status* status = saml2p::StatusBuilder::buildStatus();\r
202     saml2p::StatusCode* scode = saml2p::StatusCodeBuilder::buildStatusCode();\r
203     status->setStatusCode(scode);\r
204     scode->setValue(code);\r
205     if (subcode) {\r
206         saml2p::StatusCode* ssubcode = saml2p::StatusCodeBuilder::buildStatusCode();\r
207         scode->setStatusCode(ssubcode);\r
208         ssubcode->setValue(subcode);\r
209     }\r
210     if (msg) {\r
211         pair<bool,bool> flag = getBool("detailedErrors", m_configNS.get());\r
212         auto_ptr_XMLCh widemsg((flag.first && flag.second) ? msg : "Error processing request.");\r
213         saml2p::StatusMessage* sm = saml2p::StatusMessageBuilder::buildStatusMessage();\r
214         status->setStatusMessage(sm);\r
215         sm->setMessage(widemsg.get());\r
216     }\r
217     response.setStatus(status);\r
218 }\r
219 \r
220 long AbstractHandler::sendMessage(\r
221     const MessageEncoder& encoder,\r
222     XMLObject* msg,\r
223     const char* relayState,\r
224     const char* destination,\r
225     const saml2md::RoleDescriptor* role,\r
226     const Application& application,\r
227     HTTPResponse& httpResponse,\r
228     bool signIfPossible\r
229     ) const\r
230 {\r
231     const EntityDescriptor* entity = role ? dynamic_cast<const EntityDescriptor*>(role->getParent()) : NULL;\r
232     const PropertySet* relyingParty = application.getRelyingParty(entity);\r
233     pair<bool,const char*> flag = signIfPossible ? make_pair(true,(const char*)"true") : relyingParty->getString("signing");\r
234     if (role && flag.first &&\r
235         (!strcmp(flag.second, "true") ||\r
236             (encoder.isUserAgentPresent() && !strcmp(flag.second, "front")) ||\r
237             (!encoder.isUserAgentPresent() && !strcmp(flag.second, "back")))) {\r
238         CredentialResolver* credResolver=application.getCredentialResolver();\r
239         if (credResolver) {\r
240             Locker credLocker(credResolver);\r
241             const Credential* cred = NULL;\r
242             pair<bool,const char*> keyName = relyingParty->getString("keyName");\r
243             pair<bool,const XMLCh*> sigalg = relyingParty->getXMLString("signingAlg");\r
244             if (role) {\r
245                 MetadataCredentialCriteria mcc(*role);\r
246                 mcc.setUsage(Credential::SIGNING_CREDENTIAL);\r
247                 if (keyName.first)\r
248                     mcc.getKeyNames().insert(keyName.second);\r
249                 if (sigalg.first)\r
250                     mcc.setXMLAlgorithm(sigalg.second);\r
251                 cred = credResolver->resolve(&mcc);\r
252             }\r
253             else {\r
254                 CredentialCriteria cc;\r
255                 cc.setUsage(Credential::SIGNING_CREDENTIAL);\r
256                 if (keyName.first)\r
257                     cc.getKeyNames().insert(keyName.second);\r
258                 if (sigalg.first)\r
259                     cc.setXMLAlgorithm(sigalg.second);\r
260                 cred = credResolver->resolve(&cc);\r
261             }\r
262             if (cred) {\r
263                 // Signed request.\r
264                 return encoder.encode(\r
265                     httpResponse,\r
266                     msg,\r
267                     destination,\r
268                     entity,\r
269                     relayState,\r
270                     &application,\r
271                     cred,\r
272                     sigalg.second,\r
273                     relyingParty->getXMLString("digestAlg").second\r
274                     );\r
275             }\r
276             else {\r
277                 m_log.warn("no signing credential resolved, leaving message unsigned");\r
278             }\r
279         }\r
280         else {\r
281             m_log.warn("no credential resolver installed, leaving message unsigned");\r
282         }\r
283     }\r
284 \r
285     // Unsigned request.\r
286     return encoder.encode(httpResponse, msg, destination, entity, relayState, &application);\r
287 }\r
288 \r
289 #endif\r
290 \r
291 void AbstractHandler::preserveRelayState(const Application& application, HTTPResponse& response, string& relayState) const\r
292 {\r
293     if (relayState.empty())\r
294         return;\r
295 \r
296     // No setting means just pass it by value.\r
297     pair<bool,const char*> mech=getString("relayState");\r
298     if (!mech.first || !mech.second || !*mech.second)\r
299         return;\r
300 \r
301     if (!strcmp(mech.second, "cookie")) {\r
302         // Here we store the state in a cookie and send a fixed\r
303         // value so we can recognize it on the way back.\r
304         if (relayState.find("cookie:") != 0) {\r
305             const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();\r
306             pair<string,const char*> shib_cookie=application.getCookieNameProps("_shibstate_");\r
307             string stateval = urlenc->encode(relayState.c_str()) + shib_cookie.second;\r
308             // Generate a random key for the cookie name instead of the fixed name.\r
309             string rsKey;\r
310             generateRandomHex(rsKey,5);\r
311             shib_cookie.first = "_shibstate_" + rsKey;\r
312             response.setCookie(shib_cookie.first.c_str(),stateval.c_str());\r
313             relayState = "cookie:" + rsKey;\r
314         }\r
315     }\r
316     else if (strstr(mech.second,"ss:")==mech.second) {\r
317         if (relayState.find("ss:") != 0) {\r
318             mech.second+=3;\r
319             if (*mech.second) {\r
320                 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {\r
321 #ifndef SHIBSP_LITE\r
322                     StorageService* storage = application.getServiceProvider().getStorageService(mech.second);\r
323                     if (storage) {\r
324                         string rsKey;\r
325                         generateRandomHex(rsKey,5);\r
326                         if (!storage->createString("RelayState", rsKey.c_str(), relayState.c_str(), time(NULL) + 600))\r
327                             throw IOException("Attempted to insert duplicate storage key.");\r
328                         relayState = string(mech.second-3) + ':' + rsKey;\r
329                     }\r
330                     else {\r
331                         m_log.error("Storage-backed RelayState with invalid StorageService ID (%s)", mech.second);\r
332                         relayState.erase();\r
333                     }\r
334 #endif\r
335                 }\r
336                 else if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {\r
337                     DDF out,in = DDF("set::RelayState").structure();\r
338                     in.addmember("id").string(mech.second);\r
339                     in.addmember("value").unsafe_string(relayState.c_str());\r
340                     DDFJanitor jin(in),jout(out);\r
341                     out = application.getServiceProvider().getListenerService()->send(in);\r
342                     if (!out.isstring())\r
343                         throw IOException("StorageService-backed RelayState mechanism did not return a state key.");\r
344                     relayState = string(mech.second-3) + ':' + out.string();\r
345                 }\r
346             }\r
347         }\r
348     }\r
349     else\r
350         throw ConfigurationException("Unsupported relayState mechanism ($1).", params(1,mech.second));\r
351 }\r
352 \r
353 void AbstractHandler::recoverRelayState(\r
354     const Application& application, const HTTPRequest& request, HTTPResponse& response, string& relayState, bool clear\r
355     ) const\r
356 {\r
357     SPConfig& conf = SPConfig::getConfig();\r
358 \r
359     // Look for StorageService-backed state of the form "ss:SSID:key".\r
360     const char* state = relayState.c_str();\r
361     if (strstr(state,"ss:")==state) {\r
362         state += 3;\r
363         const char* key = strchr(state,':');\r
364         if (key) {\r
365             string ssid = relayState.substr(3, key - state);\r
366             key++;\r
367             if (!ssid.empty() && *key) {\r
368                 if (conf.isEnabled(SPConfig::OutOfProcess)) {\r
369 #ifndef SHIBSP_LITE\r
370                     StorageService* storage = conf.getServiceProvider()->getStorageService(ssid.c_str());\r
371                     if (storage) {\r
372                         ssid = key;\r
373                         if (storage->readString("RelayState",ssid.c_str(),&relayState)>0) {\r
374                             if (clear)\r
375                                 storage->deleteString("RelayState",ssid.c_str());\r
376                             return;\r
377                         }\r
378                         else\r
379                             relayState.erase();\r
380                     }\r
381                     else {\r
382                         m_log.error("Storage-backed RelayState with invalid StorageService ID (%s)", ssid.c_str());\r
383                         relayState.erase();\r
384                     }\r
385 #endif\r
386                 }\r
387                 else if (conf.isEnabled(SPConfig::InProcess)) {\r
388                     DDF out,in = DDF("get::RelayState").structure();\r
389                     in.addmember("id").string(ssid.c_str());\r
390                     in.addmember("key").string(key);\r
391                     in.addmember("clear").integer(clear ? 1 : 0);\r
392                     DDFJanitor jin(in),jout(out);\r
393                     out = application.getServiceProvider().getListenerService()->send(in);\r
394                     if (!out.isstring()) {\r
395                         m_log.error("StorageService-backed RelayState mechanism did not return a state value.");\r
396                         relayState.erase();\r
397                     }\r
398                     else {\r
399                         relayState = out.string();\r
400                         return;\r
401                     }\r
402                 }\r
403             }\r
404         }\r
405     }\r
406 \r
407     // Look for cookie-backed state of the form "cookie:key".\r
408     if (strstr(state,"cookie:")==state) {\r
409         state += 7;\r
410         if (*state) {\r
411             // Pull the value from the "relay state" cookie.\r
412             pair<string,const char*> relay_cookie = application.getCookieNameProps("_shibstate_");\r
413             relay_cookie.first = string("_shibstate_") + state;\r
414             state = request.getCookie(relay_cookie.first.c_str());\r
415             if (state && *state) {\r
416                 // URL-decode the value.\r
417                 char* rscopy=strdup(state);\r
418                 XMLToolingConfig::getConfig().getURLEncoder()->decode(rscopy);\r
419                 relayState = rscopy;\r
420                 free(rscopy);\r
421 \r
422                 if (clear) {\r
423                     string exp(relay_cookie.second);\r
424                     exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";\r
425                     response.setCookie(relay_cookie.first.c_str(), exp.c_str());\r
426                 }\r
427                 return;\r
428             }\r
429         }\r
430 \r
431         relayState.erase();\r
432     }\r
433 \r
434     // Check for "default" value (or the old "cookie" value that might come from stale bookmarks).\r
435     if (relayState.empty() || relayState == "default" || relayState == "cookie") {\r
436         pair<bool,const char*> homeURL=application.getString("homeURL");\r
437         if (homeURL.first)\r
438             relayState=homeURL.second;\r
439         else {\r
440             // Compute a URL to the root of the site.\r
441             int port = request.getPort();\r
442             const char* scheme = request.getScheme();\r
443             relayState = string(scheme) + "://" + request.getHostname();\r
444             if ((!strcmp(scheme,"http") && port!=80) || (!strcmp(scheme,"https") && port!=443)) {\r
445                 ostringstream portstr;\r
446                 portstr << port;\r
447                 relayState += ":" + portstr.str();\r
448             }\r
449             relayState += '/';\r
450         }\r
451     }\r
452 }\r
453 \r
454 void AbstractHandler::preservePostData(\r
455     const Application& application, const HTTPRequest& request, HTTPResponse& response, const char* relayState\r
456     ) const\r
457 {\r
458 #ifdef HAVE_STRCASECMP\r
459     if (strcasecmp(request.getMethod(), "POST")) return;\r
460 #else\r
461     if (stricmp(request.getMethod(), "POST")) return;\r
462 #endif\r
463 \r
464     // No specs mean no save.\r
465     const PropertySet* props=application.getPropertySet("Sessions");\r
466     pair<bool,const char*> mech = props->getString("postData");\r
467     if (!mech.first) {\r
468         m_log.info("postData property not supplied, form data will not be preserved across SSO");\r
469         return;\r
470     }\r
471 \r
472     DDF postData = getPostData(application, request);\r
473     if (postData.isnull())\r
474         return;\r
475 \r
476     if (strstr(mech.second,"ss:") == mech.second) {\r
477         mech.second+=3;\r
478         if (!*mech.second) {\r
479             postData.destroy();\r
480             throw ConfigurationException("Unsupported postData mechanism ($1).", params(1, mech.second - 3));\r
481         }\r
482 \r
483         string postkey;\r
484         if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {\r
485             DDFJanitor postjan(postData);\r
486 #ifndef SHIBSP_LITE\r
487             StorageService* storage = application.getServiceProvider().getStorageService(mech.second);\r
488             if (storage) {\r
489                 // Use a random key\r
490                 string rsKey;\r
491                 SAMLConfig::getConfig().generateRandomBytes(rsKey,20);\r
492                 rsKey = SAMLArtifact::toHex(rsKey);\r
493                 ostringstream out;\r
494                 out << postData;\r
495                 if (!storage->createString("PostData", rsKey.c_str(), out.str().c_str(), time(NULL) + 600))\r
496                     throw IOException("Attempted to insert duplicate storage key.");\r
497                 postkey = string(mech.second-3) + ':' + rsKey;\r
498             }\r
499             else {\r
500                 m_log.error("storage-backed PostData mechanism with invalid StorageService ID (%s)", mech.second);\r
501             }\r
502 #endif\r
503         }\r
504         else if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {\r
505             DDF out,in = DDF("set::PostData").structure();\r
506             DDFJanitor jin(in),jout(out);\r
507             in.addmember("id").string(mech.second);\r
508             in.add(postData);\r
509             out = application.getServiceProvider().getListenerService()->send(in);\r
510             if (!out.isstring())\r
511                 throw IOException("StorageService-backed PostData mechanism did not return a state key.");\r
512             postkey = string(mech.second-3) + ':' + out.string();\r
513         }\r
514 \r
515         // Set a cookie with key info.\r
516         pair<string,const char*> shib_cookie = getPostCookieNameProps(application, relayState);\r
517         postkey += shib_cookie.second;\r
518         response.setCookie(shib_cookie.first.c_str(), postkey.c_str());\r
519     }\r
520     else {\r
521         postData.destroy();\r
522         throw ConfigurationException("Unsupported postData mechanism ($1).", params(1,mech.second));\r
523     }\r
524 }\r
525 \r
526 DDF AbstractHandler::recoverPostData(\r
527     const Application& application, const HTTPRequest& request, HTTPResponse& response, const char* relayState\r
528     ) const\r
529 {\r
530     // First we need the post recovery cookie.\r
531     pair<string,const char*> shib_cookie = getPostCookieNameProps(application, relayState);\r
532     const char* cookie = request.getCookie(shib_cookie.first.c_str());\r
533     if (!cookie || !*cookie)\r
534         return DDF();\r
535 \r
536     // Clear the cookie.\r
537     string exp(shib_cookie.second);\r
538     exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";\r
539     response.setCookie(shib_cookie.first.c_str(), exp.c_str());\r
540 \r
541     // Look for StorageService-backed state of the form "ss:SSID:key".\r
542     const char* state = cookie;\r
543     if (strstr(state, "ss:") == state) {\r
544         state += 3;\r
545         const char* key = strchr(state, ':');\r
546         if (key) {\r
547             string ssid = string(cookie).substr(3, key - state);\r
548             key++;\r
549             if (!ssid.empty() && *key) {\r
550                 SPConfig& conf = SPConfig::getConfig();\r
551                 if (conf.isEnabled(SPConfig::OutOfProcess)) {\r
552 #ifndef SHIBSP_LITE\r
553                     StorageService* storage = conf.getServiceProvider()->getStorageService(ssid.c_str());\r
554                     if (storage) {\r
555                         if (storage->readString("PostData", key, &ssid) > 0) {\r
556                             storage->deleteString("PostData", key);\r
557                             istringstream inret(ssid);\r
558                             DDF ret;\r
559                             inret >> ret;\r
560                             return ret;\r
561                         }\r
562                         else {\r
563                             m_log.error("failed to recover form post data using key (%s)", key);\r
564                         }\r
565                     }\r
566                     else {\r
567                         m_log.error("storage-backed PostData with invalid StorageService ID (%s)", ssid.c_str());\r
568                     }\r
569 #endif\r
570                 }\r
571                 else if (conf.isEnabled(SPConfig::InProcess)) {\r
572                     DDF in = DDF("get::PostData").structure();\r
573                     DDFJanitor jin(in);\r
574                     in.addmember("id").string(ssid.c_str());\r
575                     in.addmember("key").string(key);\r
576                     DDF out = application.getServiceProvider().getListenerService()->send(in);\r
577                     if (out.islist())\r
578                         return out;\r
579                     out.destroy();\r
580                     m_log.error("storageService-backed PostData mechanism did not return preserved data.");\r
581                 }\r
582             }\r
583         }\r
584     }\r
585     return DDF();\r
586 }\r
587 \r
588 long AbstractHandler::sendPostResponse(\r
589     const Application& application, HTTPResponse& httpResponse, const char* url, DDF& postData\r
590     ) const\r
591 {\r
592     HTTPResponse::sanitizeURL(url);\r
593 \r
594     const PropertySet* props=application.getPropertySet("Sessions");\r
595     pair<bool,const char*> postTemplate = props->getString("postTemplate");\r
596     if (!postTemplate.first)\r
597         throw ConfigurationException("Missing postTemplate property, unable to recreate form post.");\r
598 \r
599     string fname(postTemplate.second);\r
600     ifstream infile(XMLToolingConfig::getConfig().getPathResolver()->resolve(fname, PathResolver::XMLTOOLING_CFG_FILE).c_str());\r
601     if (!infile)\r
602         throw ConfigurationException("Unable to access HTML template ($1).", params(1, fname.c_str()));\r
603     TemplateParameters respParam;\r
604     respParam.m_map["action"] = url;\r
605 \r
606     // Load the parameters into objects for the template.\r
607     multimap<string,string>& collection = respParam.m_collectionMap["PostedData"];\r
608     DDF param = postData.first();\r
609     while (!param.isnull()) {\r
610         collection.insert(pair<const string,string>(param.name(), (param.string() ? param.string() : "")));\r
611         param = postData.next();\r
612     }\r
613 \r
614     stringstream str;\r
615     XMLToolingConfig::getConfig().getTemplateEngine()->run(infile, str, respParam);\r
616 \r
617     pair<bool,bool> postExpire = props->getBool("postExpire");\r
618 \r
619     httpResponse.setContentType("text/html");\r
620     if (!postExpire.first || postExpire.second) {\r
621         httpResponse.setResponseHeader("Expires", "01-Jan-1997 12:00:00 GMT");\r
622         httpResponse.setResponseHeader("Cache-Control", "no-cache, no-store, must-revalidate, private");\r
623         httpResponse.setResponseHeader("Pragma", "no-cache");\r
624     }\r
625     return httpResponse.sendResponse(str);\r
626 }\r
627 \r
628 pair<string,const char*> AbstractHandler::getPostCookieNameProps(const Application& app, const char* relayState) const\r
629 {\r
630     // Decorates the name of the cookie with the relay state key, if any.\r
631     // Doing so gives a better assurance that the recovered data really\r
632     // belongs to the relayed request.\r
633     pair<string,const char*> shib_cookie=app.getCookieNameProps("_shibpost_");\r
634     if (strstr(relayState, "cookie:") == relayState) {\r
635         shib_cookie.first = string("_shibpost_") + (relayState + 7);\r
636     }\r
637     else if (strstr(relayState, "ss:") == relayState) {\r
638         const char* pch = strchr(relayState + 3, ':');\r
639         if (pch)\r
640             shib_cookie.first = string("_shibpost_") + (pch + 1);\r
641     }\r
642     return shib_cookie;\r
643 }\r
644 \r
645 DDF AbstractHandler::getPostData(const Application& application, const HTTPRequest& request) const\r
646 {\r
647     string contentType = request.getContentType();\r
648     if (contentType.compare("application/x-www-form-urlencoded") == 0) {\r
649         const PropertySet* props=application.getPropertySet("Sessions");\r
650         pair<bool,unsigned int> plimit = props->getUnsignedInt("postLimit");\r
651         if (!plimit.first)\r
652             plimit.second = 1024 * 1024;\r
653         if (plimit.second == 0 || request.getContentLength() <= plimit.second) {\r
654             CGIParser cgi(request);\r
655             pair<CGIParser::walker,CGIParser::walker> params = cgi.getParameters(NULL);\r
656             if (params.first == params.second)\r
657                 return DDF("parameters").list();\r
658             DDF child;\r
659             DDF ret = DDF("parameters").list();\r
660             for (; params.first != params.second; ++params.first) {\r
661                 if (!params.first->first.empty()) {\r
662                     child = DDF(params.first->first.c_str()).unsafe_string(params.first->second);\r
663                     ret.add(child);\r
664                 }\r
665             }\r
666             return ret;\r
667         }\r
668         else {\r
669             m_log.warn("POST limit exceeded, ignoring %d bytes of posted data", request.getContentLength());\r
670         }\r
671     }\r
672     else {\r
673         m_log.info("ignoring POST data with non-standard encoding (%s)", contentType.c_str());\r
674     }\r
675     return DDF();\r
676 }\r