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