https://issues.shibboleth.net/jira/browse/SSPCPP-92
[shibboleth/cpp-sp.git] / shibsp / handler / impl / AbstractHandler.cpp
1 /*
2  *  Copyright 2001-2007 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 "Application.h"
25 #include "exceptions.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/SPConstants.h"
32
33 #ifndef SHIBSP_LITE
34 # include <saml/saml1/core/Protocols.h>
35 # include <saml/saml2/core/Protocols.h>
36 # include <saml/saml2/metadata/Metadata.h>
37 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
38 # include <saml/util/SAMLConstants.h>
39 # include <xmltooling/util/StorageService.h>
40 using namespace opensaml::saml2md;
41 #else
42 # include "lite/SAMLConstants.h"
43 #endif
44
45 #include <xmltooling/XMLToolingConfig.h>
46 #include <xmltooling/util/URLEncoder.h>
47
48 using namespace shibsp;
49 using namespace samlconstants;
50 using namespace opensaml;
51 using namespace xmltooling;
52 using namespace xercesc;
53 using namespace std;
54
55 namespace shibsp {
56     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML1ConsumerFactory;
57     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2ConsumerFactory;
58     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2ArtifactResolutionFactory;
59     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory ChainingLogoutInitiatorFactory;
60     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory LocalLogoutInitiatorFactory;
61     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2LogoutInitiatorFactory;
62     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2LogoutFactory;
63     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2NameIDMgmtFactory;
64     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory AssertionLookupFactory;
65     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory MetadataGeneratorFactory;
66     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory StatusHandlerFactory;
67     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SessionHandlerFactory;
68
69     void SHIBSP_DLLLOCAL generateRandomHex(std::string& buf, unsigned int len) {
70         static char DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
71         int r;
72         unsigned char b1,b2;
73         buf.erase();
74         for (unsigned int i=0; i<len; i+=4) {
75             r = rand();
76             b1 = (0x00FF & r);
77             b2 = (0xFF00 & r)  >> 8;
78             buf += (DIGITS[(0xF0 & b1) >> 4 ]);
79             buf += (DIGITS[0x0F & b1]);
80             buf += (DIGITS[(0xF0 & b2) >> 4 ]);
81             buf += (DIGITS[0x0F & b2]);
82         }
83     }
84 };
85
86 void SHIBSP_API shibsp::registerHandlers()
87 {
88     SPConfig& conf=SPConfig::getConfig();
89     
90     conf.AssertionConsumerServiceManager.registerFactory(SAML1_PROFILE_BROWSER_ARTIFACT, SAML1ConsumerFactory);
91     conf.AssertionConsumerServiceManager.registerFactory(SAML1_PROFILE_BROWSER_POST, SAML1ConsumerFactory);
92     conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_POST, SAML2ConsumerFactory);
93     conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_POST_SIMPLESIGN, SAML2ConsumerFactory);
94     conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_ARTIFACT, SAML2ConsumerFactory);
95     conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_PAOS, SAML2ConsumerFactory);
96
97     conf.ArtifactResolutionServiceManager.registerFactory(SAML20_BINDING_SOAP, SAML2ArtifactResolutionFactory);
98
99     conf.HandlerManager.registerFactory(SAML20_BINDING_URI, AssertionLookupFactory);
100     conf.HandlerManager.registerFactory(METADATA_GENERATOR_HANDLER, MetadataGeneratorFactory);
101     conf.HandlerManager.registerFactory(STATUS_HANDLER, StatusHandlerFactory);
102     conf.HandlerManager.registerFactory(SESSION_HANDLER, SessionHandlerFactory);
103
104     conf.LogoutInitiatorManager.registerFactory(CHAINING_LOGOUT_INITIATOR, ChainingLogoutInitiatorFactory);
105     conf.LogoutInitiatorManager.registerFactory(LOCAL_LOGOUT_INITIATOR, LocalLogoutInitiatorFactory);
106     conf.LogoutInitiatorManager.registerFactory(SAML2_LOGOUT_INITIATOR, SAML2LogoutInitiatorFactory);
107     conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_SOAP, SAML2LogoutFactory);
108     conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_HTTP_REDIRECT, SAML2LogoutFactory);
109     conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_HTTP_POST, SAML2LogoutFactory);
110     conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_HTTP_POST_SIMPLESIGN, SAML2LogoutFactory);
111     conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_HTTP_ARTIFACT, SAML2LogoutFactory);
112
113     conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_SOAP, SAML2NameIDMgmtFactory);
114     conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_HTTP_REDIRECT, SAML2NameIDMgmtFactory);
115     conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_HTTP_POST, SAML2NameIDMgmtFactory);
116     conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_HTTP_POST_SIMPLESIGN, SAML2NameIDMgmtFactory);
117     conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_HTTP_ARTIFACT, SAML2NameIDMgmtFactory);
118 }
119
120 AbstractHandler::AbstractHandler(
121     const DOMElement* e, Category& log, DOMNodeFilter* filter, const map<string,string>* remapper
122     ) : m_log(log), m_configNS(shibspconstants::SHIB2SPCONFIG_NS) {
123     load(e,NULL,filter,remapper);
124 }
125
126 #ifndef SHIBSP_LITE
127
128 void AbstractHandler::checkError(const XMLObject* response, const saml2md::RoleDescriptor* role) const
129 {
130     const saml2p::StatusResponseType* r2 = dynamic_cast<const saml2p::StatusResponseType*>(response);
131     if (r2) {
132         const saml2p::Status* status = r2->getStatus();
133         if (status) {
134             const saml2p::StatusCode* sc = status->getStatusCode();
135             const XMLCh* code = sc ? sc->getValue() : NULL;
136             if (code && !XMLString::equals(code,saml2p::StatusCode::SUCCESS)) {
137                 FatalProfileException ex("SAML response contained an error.");
138                 annotateException(&ex, role, status);   // throws it
139             }
140         }
141     }
142
143     const saml1p::Response* r1 = dynamic_cast<const saml1p::Response*>(response);
144     if (r1) {
145         const saml1p::Status* status = r1->getStatus();
146         if (status) {
147             const saml1p::StatusCode* sc = status->getStatusCode();
148             const QName* code = sc ? sc->getValue() : NULL;
149             if (code && *code != saml1p::StatusCode::SUCCESS) {
150                 FatalProfileException ex("SAML response contained an error.");
151                 ex.addProperty("statusCode", code->toString().c_str());
152                 if (sc->getStatusCode()) {
153                     code = sc->getStatusCode()->getValue();
154                     if (code)
155                         ex.addProperty("statusCode2", code->toString().c_str());
156                 }
157                 if (status->getStatusMessage()) {
158                     auto_ptr_char msg(status->getStatusMessage()->getMessage());
159                     if (msg.get() && *msg.get())
160                         ex.addProperty("statusMessage", msg.get());
161                 }
162                 ex.raise();
163             }
164         }
165     }
166 }
167
168 void AbstractHandler::fillStatus(saml2p::StatusResponseType& response, const XMLCh* code, const XMLCh* subcode, const char* msg) const
169 {
170     saml2p::Status* status = saml2p::StatusBuilder::buildStatus();
171     saml2p::StatusCode* scode = saml2p::StatusCodeBuilder::buildStatusCode();
172     status->setStatusCode(scode);
173     scode->setValue(code);
174     if (subcode) {
175         saml2p::StatusCode* ssubcode = saml2p::StatusCodeBuilder::buildStatusCode();
176         scode->setStatusCode(ssubcode);
177         ssubcode->setValue(subcode);
178     }
179     if (msg) {
180         pair<bool,bool> flag = getBool("detailedErrors", m_configNS.get());
181         auto_ptr_XMLCh widemsg((flag.first && flag.second) ? msg : "Error processing request.");
182         saml2p::StatusMessage* sm = saml2p::StatusMessageBuilder::buildStatusMessage();
183         status->setStatusMessage(sm);
184         sm->setMessage(widemsg.get());
185     }
186     response.setStatus(status);
187 }
188
189 long AbstractHandler::sendMessage(
190     const MessageEncoder& encoder,
191     XMLObject* msg,
192     const char* relayState,
193     const char* destination,
194     const saml2md::RoleDescriptor* role,
195     const Application& application,
196     HTTPResponse& httpResponse,
197     bool signIfPossible
198     ) const
199 {
200     const EntityDescriptor* entity = role ? dynamic_cast<const EntityDescriptor*>(role->getParent()) : NULL;
201     const PropertySet* relyingParty = application.getRelyingParty(entity);
202     pair<bool,const char*> flag = signIfPossible ? make_pair(true,(const char*)"true") : relyingParty->getString("signing");
203     if (role && flag.first &&
204         (!strcmp(flag.second, "true") ||
205             (encoder.isUserAgentPresent() && !strcmp(flag.second, "front")) ||
206             (!encoder.isUserAgentPresent() && !strcmp(flag.second, "back")))) {
207         CredentialResolver* credResolver=application.getCredentialResolver();
208         if (credResolver) {
209             Locker credLocker(credResolver);
210             const Credential* cred = NULL;
211             pair<bool,const char*> keyName = relyingParty->getString("keyName");
212             pair<bool,const XMLCh*> sigalg = relyingParty->getXMLString("signingAlg");
213             if (role) {
214                 MetadataCredentialCriteria mcc(*role);
215                 mcc.setUsage(Credential::SIGNING_CREDENTIAL);
216                 if (keyName.first)
217                     mcc.getKeyNames().insert(keyName.second);
218                 if (sigalg.first)
219                     mcc.setXMLAlgorithm(sigalg.second);
220                 cred = credResolver->resolve(&mcc);
221             }
222             else {
223                 CredentialCriteria cc;
224                 cc.setUsage(Credential::SIGNING_CREDENTIAL);
225                 if (keyName.first)
226                     cc.getKeyNames().insert(keyName.second);
227                 if (sigalg.first)
228                     cc.setXMLAlgorithm(sigalg.second);
229                 cred = credResolver->resolve(&cc);
230             }
231             if (cred) {
232                 // Signed request.
233                 return encoder.encode(
234                     httpResponse,
235                     msg,
236                     destination,
237                     entity,
238                     relayState,
239                     &application,
240                     cred,
241                     sigalg.second,
242                     relyingParty->getXMLString("digestAlg").second
243                     );
244             }
245             else {
246                 m_log.warn("no signing credential resolved, leaving message unsigned");
247             }
248         }
249         else {
250             m_log.warn("no credential resolver installed, leaving message unsigned");
251         }
252     }
253
254     // Unsigned request.
255     return encoder.encode(httpResponse, msg, destination, entity, relayState, &application);
256 }
257
258 #endif
259
260 void AbstractHandler::preserveRelayState(const Application& application, HTTPResponse& response, string& relayState) const
261 {
262     if (relayState.empty())
263         return;
264
265     // No setting means just pass it by value.
266     pair<bool,const char*> mech=getString("relayState");
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                         string rsKey;
294                         generateRandomHex(rsKey,5);
295                         if (!storage->createString("RelayState", rsKey.c_str(), relayState.c_str(), time(NULL) + 600))
296                             throw IOException("Attempted to insert duplicate storage key.");
297                         relayState = string(mech.second-3) + ':' + rsKey;
298                     }
299                     else {
300                         m_log.error("Storage-backed RelayState with invalid StorageService ID (%s)", mech.second);
301                         relayState.erase();
302                     }
303 #endif
304                 }
305                 else if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
306                     DDF out,in = DDF("set::RelayState").structure();
307                     in.addmember("id").string(mech.second);
308                     in.addmember("value").string(relayState.c_str());
309                     DDFJanitor jin(in),jout(out);
310                     out = application.getServiceProvider().getListenerService()->send(in);
311                     if (!out.isstring())
312                         throw IOException("StorageService-backed RelayState mechanism did not return a state key.");
313                     relayState = string(mech.second-3) + ':' + out.string();
314                 }
315             }
316         }
317     }
318     else
319         throw ConfigurationException("Unsupported relayState mechanism ($1).", params(1,mech.second));
320 }
321
322 void AbstractHandler::recoverRelayState(
323     const Application& application, const HTTPRequest& request, HTTPResponse& response, string& relayState, bool clear
324     ) const
325 {
326     SPConfig& conf = SPConfig::getConfig();
327
328     // Look for StorageService-backed state of the form "ss:SSID:key".
329     const char* state = relayState.c_str();
330     if (strstr(state,"ss:")==state) {
331         state += 3;
332         const char* key = strchr(state,':');
333         if (key) {
334             string ssid = relayState.substr(3, key - state);
335             key++;
336             if (!ssid.empty() && *key) {
337                 if (conf.isEnabled(SPConfig::OutOfProcess)) {
338 #ifndef SHIBSP_LITE
339                     StorageService* storage = conf.getServiceProvider()->getStorageService(ssid.c_str());
340                     if (storage) {
341                         ssid = key;
342                         if (storage->readString("RelayState",ssid.c_str(),&relayState)>0) {
343                             if (clear)
344                                 storage->deleteString("RelayState",ssid.c_str());
345                             return;
346                         }
347                         else
348                             relayState.erase();
349                     }
350                     else {
351                         Category::getInstance(SHIBSP_LOGCAT".Handler").error(
352                             "Storage-backed RelayState with invalid StorageService ID (%s)", ssid.c_str()
353                             );
354                         relayState.erase();
355                     }
356 #endif
357                 }
358                 else if (conf.isEnabled(SPConfig::InProcess)) {
359                     DDF out,in = DDF("get::RelayState").structure();
360                     in.addmember("id").string(ssid.c_str());
361                     in.addmember("key").string(key);
362                     in.addmember("clear").integer(clear ? 1 : 0);
363                     DDFJanitor jin(in),jout(out);
364                     out = application.getServiceProvider().getListenerService()->send(in);
365                     if (!out.isstring()) {
366                         m_log.error("StorageService-backed RelayState mechanism did not return a state value.");
367                         relayState.erase();
368                     }
369                     else {
370                         relayState = out.string();
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                 return;
399             }
400         }
401
402         relayState.erase();
403     }
404
405     // Check for "default" value.
406     if (relayState.empty() || relayState == "default") {
407         pair<bool,const char*> homeURL=application.getString("homeURL");
408         relayState=homeURL.first ? homeURL.second : "/";
409         return;
410     }
411
412     if (relayState == "default")
413         relayState.empty();
414 }