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