Handle signing if no role provided.
[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/SAMLConfig.h>
35 # include <saml/binding/SAMLArtifact.h>
36 # include <saml/saml1/core/Protocols.h>
37 # include <saml/saml2/core/Protocols.h>
38 # include <saml/saml2/metadata/Metadata.h>
39 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
40 # include <saml/util/SAMLConstants.h>
41 # include <xmltooling/util/StorageService.h>
42 using namespace opensaml::saml2md;
43 #else
44 # include "lite/SAMLConstants.h"
45 #endif
46
47 #include <xmltooling/XMLToolingConfig.h>
48 #include <xmltooling/util/URLEncoder.h>
49
50 using namespace shibsp;
51 using namespace samlconstants;
52 using namespace opensaml;
53 using namespace xmltooling;
54 using namespace xercesc;
55 using namespace std;
56
57 namespace shibsp {
58     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML1ConsumerFactory;
59     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2ConsumerFactory;
60     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2ArtifactResolutionFactory;
61     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory ChainingLogoutInitiatorFactory;
62     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory LocalLogoutInitiatorFactory;
63     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2LogoutInitiatorFactory;
64     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2LogoutFactory;
65     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2NameIDMgmtFactory;
66     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory AssertionLookupFactory;
67     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory MetadataGeneratorFactory;
68     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory StatusHandlerFactory;
69 };
70
71 void SHIBSP_API shibsp::registerHandlers()
72 {
73     SPConfig& conf=SPConfig::getConfig();
74     
75     conf.AssertionConsumerServiceManager.registerFactory(SAML1_PROFILE_BROWSER_ARTIFACT, SAML1ConsumerFactory);
76     conf.AssertionConsumerServiceManager.registerFactory(SAML1_PROFILE_BROWSER_POST, SAML1ConsumerFactory);
77     conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_POST, SAML2ConsumerFactory);
78     conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_POST_SIMPLESIGN, SAML2ConsumerFactory);
79     conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_ARTIFACT, SAML2ConsumerFactory);
80
81     conf.ArtifactResolutionServiceManager.registerFactory(SAML20_BINDING_SOAP, SAML2ArtifactResolutionFactory);
82
83     conf.HandlerManager.registerFactory(SAML20_BINDING_URI, AssertionLookupFactory);
84     conf.HandlerManager.registerFactory("MetadataGenerator", MetadataGeneratorFactory);
85     conf.HandlerManager.registerFactory("Status", StatusHandlerFactory);
86
87     conf.LogoutInitiatorManager.registerFactory(CHAINING_LOGOUT_INITIATOR, ChainingLogoutInitiatorFactory);
88     conf.LogoutInitiatorManager.registerFactory(LOCAL_LOGOUT_INITIATOR, LocalLogoutInitiatorFactory);
89     conf.LogoutInitiatorManager.registerFactory(SAML2_LOGOUT_INITIATOR, SAML2LogoutInitiatorFactory);
90     conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_SOAP, SAML2LogoutFactory);
91     conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_HTTP_REDIRECT, SAML2LogoutFactory);
92     conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_HTTP_POST, SAML2LogoutFactory);
93     conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_HTTP_POST_SIMPLESIGN, SAML2LogoutFactory);
94     conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_HTTP_ARTIFACT, SAML2LogoutFactory);
95
96     conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_SOAP, SAML2NameIDMgmtFactory);
97     conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_HTTP_REDIRECT, SAML2NameIDMgmtFactory);
98     conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_HTTP_POST, SAML2NameIDMgmtFactory);
99     conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_HTTP_POST_SIMPLESIGN, SAML2NameIDMgmtFactory);
100     conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_HTTP_ARTIFACT, SAML2NameIDMgmtFactory);
101 }
102
103 AbstractHandler::AbstractHandler(
104     const DOMElement* e, Category& log, DOMNodeFilter* filter, const map<string,string>* remapper
105     ) : m_log(log), m_configNS(shibspconstants::SHIB2SPCONFIG_NS) {
106     load(e,log,filter,remapper);
107 }
108
109 #ifndef SHIBSP_LITE
110
111 void AbstractHandler::checkError(const XMLObject* response, const saml2md::RoleDescriptor* role) const
112 {
113     const saml2p::StatusResponseType* r2 = dynamic_cast<const saml2p::StatusResponseType*>(response);
114     if (r2) {
115         const saml2p::Status* status = r2->getStatus();
116         if (status) {
117             const saml2p::StatusCode* sc = status->getStatusCode();
118             const XMLCh* code = sc ? sc->getValue() : NULL;
119             if (code && !XMLString::equals(code,saml2p::StatusCode::SUCCESS)) {
120                 FatalProfileException ex("SAML response contained an error.");
121                 annotateException(&ex, role, status);   // throws it
122             }
123         }
124     }
125
126     const saml1p::Response* r1 = dynamic_cast<const saml1p::Response*>(response);
127     if (r1) {
128         const saml1p::Status* status = r1->getStatus();
129         if (status) {
130             const saml1p::StatusCode* sc = status->getStatusCode();
131             const QName* code = sc ? sc->getValue() : NULL;
132             if (code && *code != saml1p::StatusCode::SUCCESS) {
133                 FatalProfileException ex("SAML response contained an error.");
134                 ex.addProperty("statusCode", code->toString().c_str());
135                 if (sc->getStatusCode()) {
136                     code = sc->getStatusCode()->getValue();
137                     if (code)
138                         ex.addProperty("statusCode2", code->toString().c_str());
139                 }
140                 if (status->getStatusMessage()) {
141                     auto_ptr_char msg(status->getStatusMessage()->getMessage());
142                     if (msg.get() && *msg.get())
143                         ex.addProperty("statusMessage", msg.get());
144                 }
145                 ex.raise();
146             }
147         }
148     }
149 }
150
151 void AbstractHandler::fillStatus(saml2p::StatusResponseType& response, const XMLCh* code, const XMLCh* subcode, const char* msg) const
152 {
153     saml2p::Status* status = saml2p::StatusBuilder::buildStatus();
154     saml2p::StatusCode* scode = saml2p::StatusCodeBuilder::buildStatusCode();
155     status->setStatusCode(scode);
156     scode->setValue(code);
157     if (subcode) {
158         saml2p::StatusCode* ssubcode = saml2p::StatusCodeBuilder::buildStatusCode();
159         scode->setStatusCode(ssubcode);
160         ssubcode->setValue(subcode);
161     }
162     if (msg) {
163         pair<bool,bool> flag = getBool("detailedErrors", m_configNS.get());
164         auto_ptr_XMLCh widemsg((flag.first && flag.second) ? msg : "Error processing request.");
165         saml2p::StatusMessage* sm = saml2p::StatusMessageBuilder::buildStatusMessage();
166         status->setStatusMessage(sm);
167         sm->setMessage(widemsg.get());
168     }
169     response.setStatus(status);
170 }
171
172 long AbstractHandler::sendMessage(
173     const MessageEncoder& encoder,
174     XMLObject* msg,
175     const char* relayState,
176     const char* destination,
177     const saml2md::RoleDescriptor* role,
178     const Application& application,
179     HTTPResponse& httpResponse,
180     bool signIfPossible
181     ) const
182 {
183     const EntityDescriptor* entity = role ? dynamic_cast<const EntityDescriptor*>(role->getParent()) : NULL;
184     const PropertySet* relyingParty = application.getRelyingParty(entity);
185     pair<bool,const char*> flag = signIfPossible ? make_pair(true,"true") : relyingParty->getString("signing");
186     if (role && flag.first &&
187         (!strcmp(flag.second, "true") ||
188             (encoder.isUserAgentPresent() && !strcmp(flag.second, "front")) ||
189             (!encoder.isUserAgentPresent() && !strcmp(flag.second, "back")))) {
190         CredentialResolver* credResolver=application.getCredentialResolver();
191         if (credResolver) {
192             Locker credLocker(credResolver);
193             const Credential* cred = NULL;
194             pair<bool,const char*> keyName = relyingParty->getString("keyName");
195             pair<bool,const XMLCh*> sigalg = relyingParty->getXMLString("signingAlg");
196             if (role) {
197                 MetadataCredentialCriteria mcc(*role);
198                 mcc.setUsage(Credential::SIGNING_CREDENTIAL);
199                 if (keyName.first)
200                     mcc.getKeyNames().insert(keyName.second);
201                 if (sigalg.first)
202                     mcc.setXMLAlgorithm(sigalg.second);
203                 cred = credResolver->resolve(&mcc);
204             }
205             else {
206                 CredentialCriteria cc;
207                 cc.setUsage(Credential::SIGNING_CREDENTIAL);
208                 if (keyName.first)
209                     cc.getKeyNames().insert(keyName.second);
210                 if (sigalg.first)
211                     cc.setXMLAlgorithm(sigalg.second);
212                 cred = credResolver->resolve(&cc);
213             }
214             if (cred) {
215                 // Signed request.
216                 return encoder.encode(
217                     httpResponse,
218                     msg,
219                     destination,
220                     entity,
221                     relayState,
222                     &application,
223                     cred,
224                     sigalg.second,
225                     relyingParty->getXMLString("digestAlg").second
226                     );
227             }
228             else {
229                 m_log.warn("no signing credential resolved, leaving message unsigned");
230             }
231         }
232         else {
233             m_log.warn("no credential resolver installed, leaving message unsigned");
234         }
235     }
236
237     // Unsigned request.
238     return encoder.encode(httpResponse, msg, destination, entity, relayState, &application);
239 }
240
241 #endif
242
243 void AbstractHandler::preserveRelayState(const Application& application, HTTPResponse& response, string& relayState) const
244 {
245     if (relayState.empty())
246         return;
247
248     // No setting means just pass it by value.
249     pair<bool,const char*> mech=getString("relayState");
250     if (!mech.first || !mech.second || !*mech.second)
251         return;
252
253     if (!strcmp(mech.second, "cookie")) {
254         // Here we store the state in a cookie and send a fixed
255         // value so we can recognize it on the way back.
256         if (relayState != "cookie") {
257             const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
258             pair<string,const char*> shib_cookie=application.getCookieNameProps("_shibstate_");
259             string stateval = urlenc->encode(relayState.c_str()) + shib_cookie.second;
260             response.setCookie(shib_cookie.first.c_str(),stateval.c_str());
261             relayState = "cookie";
262         }
263     }
264     else if (strstr(mech.second,"ss:")==mech.second) {
265         if (relayState.find("ss:")!=0) {
266             mech.second+=3;
267             if (*mech.second) {
268                 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
269 #ifndef SHIBSP_LITE
270                     StorageService* storage = application.getServiceProvider().getStorageService(mech.second);
271                     if (storage) {
272                         string rsKey;
273                         SAMLConfig::getConfig().generateRandomBytes(rsKey,10);
274                         rsKey = SAMLArtifact::toHex(rsKey);
275                         if (!storage->createString("RelayState", rsKey.c_str(), relayState.c_str(), time(NULL) + 600))
276                             throw IOException("Attempted to insert duplicate storage key.");
277                         relayState = string(mech.second-3) + ':' + rsKey;
278                     }
279                     else {
280                         m_log.error("Storage-backed RelayState with invalid StorageService ID (%s)", mech.second);
281                         relayState.erase();
282                     }
283 #endif
284                 }
285                 else if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
286                     DDF out,in = DDF("set::RelayState").structure();
287                     in.addmember("id").string(mech.second);
288                     in.addmember("value").string(relayState.c_str());
289                     DDFJanitor jin(in),jout(out);
290                     out = application.getServiceProvider().getListenerService()->send(in);
291                     if (!out.isstring())
292                         throw IOException("StorageService-backed RelayState mechanism did not return a state key.");
293                     relayState = string(mech.second-3) + ':' + out.string();
294                 }
295             }
296         }
297     }
298     else
299         throw ConfigurationException("Unsupported relayState mechanism ($1).", params(1,mech.second));
300 }
301
302 void AbstractHandler::recoverRelayState(const Application& application, HTTPRequest& httpRequest, string& relayState, bool clear) const
303 {
304     SPConfig& conf = SPConfig::getConfig();
305
306     // Look for StorageService-backed state of the form "ss:SSID:key".
307     const char* state = relayState.c_str();
308     if (strstr(state,"ss:")==state) {
309         state += 3;
310         const char* key = strchr(state,':');
311         if (key) {
312             string ssid = relayState.substr(3, key - state);
313             key++;
314             if (!ssid.empty() && *key) {
315                 if (conf.isEnabled(SPConfig::OutOfProcess)) {
316 #ifndef SHIBSP_LITE
317                     StorageService* storage = conf.getServiceProvider()->getStorageService(ssid.c_str());
318                     if (storage) {
319                         ssid = key;
320                         if (storage->readString("RelayState",ssid.c_str(),&relayState)>0) {
321                             if (clear)
322                                 storage->deleteString("RelayState",ssid.c_str());
323                             return;
324                         }
325                         else
326                             relayState.erase();
327                     }
328                     else {
329                         Category::getInstance(SHIBSP_LOGCAT".Handler").error(
330                             "Storage-backed RelayState with invalid StorageService ID (%s)", ssid.c_str()
331                             );
332                         relayState.erase();
333                     }
334 #endif
335                 }
336                 else if (conf.isEnabled(SPConfig::InProcess)) {
337                     DDF out,in = DDF("get::RelayState").structure();
338                     in.addmember("id").string(ssid.c_str());
339                     in.addmember("key").string(key);
340                     in.addmember("clear").integer(clear ? 1 : 0);
341                     DDFJanitor jin(in),jout(out);
342                     out = application.getServiceProvider().getListenerService()->send(in);
343                     if (!out.isstring()) {
344                         m_log.error("StorageService-backed RelayState mechanism did not return a state value.");
345                         relayState.erase();
346                     }
347                     else {
348                         relayState = out.string();
349                         return;
350                     }
351                 }
352             }
353         }
354     }
355     
356     if (conf.isEnabled(SPConfig::InProcess)) {
357         if (relayState == "cookie") {
358             // Pull the value from the "relay state" cookie.
359             pair<string,const char*> relay_cookie = application.getCookieNameProps("_shibstate_");
360             // In process, we should be able to cast down to a full SPRequest.
361             SPRequest& request = dynamic_cast<SPRequest&>(httpRequest);
362             const char* state = request.getCookie(relay_cookie.first.c_str());
363             if (state && *state) {
364                 // URL-decode the value.
365                 char* rscopy=strdup(state);
366                 XMLToolingConfig::getConfig().getURLEncoder()->decode(rscopy);
367                 relayState = rscopy;
368                 free(rscopy);
369                 
370                 if (clear)
371                     request.setCookie(relay_cookie.first.c_str(),relay_cookie.second);
372                 return;
373             }
374
375             relayState.erase();
376         }
377
378         // Check for "default" value.
379         if (relayState.empty() || relayState == "default") {
380             pair<bool,const char*> homeURL=application.getString("homeURL");
381             relayState=homeURL.first ? homeURL.second : "/";
382             return;
383         }
384     }
385
386     if (relayState == "default")
387         relayState.empty();
388 }