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