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