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