1054f4cae5ea0a5f17816b2379baafd71122be76
[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/util/SAMLConstants.h>
38 # include <xmltooling/util/StorageService.h>
39 #else
40 # include "lite/SAMLConstants.h"
41 #endif
42
43 #include <xmltooling/XMLToolingConfig.h>
44 #include <xmltooling/util/URLEncoder.h>
45
46 using namespace shibsp;
47 using namespace samlconstants;
48 using namespace opensaml;
49 using namespace xmltooling;
50 using namespace log4cpp;
51 using namespace xercesc;
52 using namespace std;
53
54 namespace shibsp {
55     SHIBSP_DLLLOCAL PluginManager<Handler,string,pair<const DOMElement*,const char*>>::Factory SAML1ConsumerFactory;
56     SHIBSP_DLLLOCAL PluginManager<Handler,string,pair<const DOMElement*,const char*>>::Factory SAML2ConsumerFactory;
57     SHIBSP_DLLLOCAL PluginManager<Handler,string,pair<const DOMElement*,const char*>>::Factory SAML2ArtifactResolutionFactory;
58 };
59
60 void SHIBSP_API shibsp::registerHandlers()
61 {
62     SPConfig& conf=SPConfig::getConfig();
63     
64     conf.AssertionConsumerServiceManager.registerFactory(SAML1_PROFILE_BROWSER_ARTIFACT, SAML1ConsumerFactory);
65     conf.AssertionConsumerServiceManager.registerFactory(SAML1_PROFILE_BROWSER_POST, SAML1ConsumerFactory);
66     conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_ARTIFACT, SAML2ConsumerFactory);
67     conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_POST, SAML2ConsumerFactory);
68     conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_POST_SIMPLESIGN, SAML2ConsumerFactory);
69
70     conf.ArtifactResolutionServiceManager.registerFactory(SAML20_BINDING_SOAP, SAML2ArtifactResolutionFactory);
71 }
72
73 AbstractHandler::AbstractHandler(
74     const DOMElement* e, log4cpp::Category& log, DOMNodeFilter* filter, const map<string,string>* remapper
75     ) : m_log(log), m_configNS(shibspconstants::SHIB2SPCONFIG_NS) {
76     load(e,log,filter,remapper);
77 }
78
79 #ifndef SHIBSP_LITE
80 void AbstractHandler::checkError(const XMLObject* response) const
81 {
82     const saml2p::StatusResponseType* r2 = dynamic_cast<const saml2p::StatusResponseType*>(response);
83     if (r2) {
84         const saml2p::Status* status = r2->getStatus();
85         if (status) {
86             const saml2p::StatusCode* sc = status->getStatusCode();
87             const XMLCh* code = sc ? sc->getValue() : NULL;
88             if (code && !XMLString::equals(code,saml2p::StatusCode::SUCCESS)) {
89                 FatalProfileException ex("SAML Response message contained an error.");
90                 auto_ptr_char c1(code);
91                 ex.addProperty("StatusCode", c1.get());
92                 if (sc->getStatusCode()) {
93                     code = sc->getStatusCode()->getValue();
94                     auto_ptr_char c2(code);
95                     ex.addProperty("StatusCode2", c2.get());
96                 }
97                 if (status->getStatusMessage()) {
98                     auto_ptr_char msg(status->getStatusMessage()->getMessage());
99                     ex.addProperty("StatusMessage", msg.get());
100                 }
101             }
102         }
103     }
104
105     const saml1p::Response* r1 = dynamic_cast<const saml1p::Response*>(response);
106     if (r1) {
107         const saml1p::Status* status = r1->getStatus();
108         if (status) {
109             const saml1p::StatusCode* sc = status->getStatusCode();
110             const QName* code = sc ? sc->getValue() : NULL;
111             if (code && *code != saml1p::StatusCode::SUCCESS) {
112                 FatalProfileException ex("SAML Response message contained an error.");
113                 ex.addProperty("StatusCode", code->toString().c_str());
114                 if (sc->getStatusCode()) {
115                     code = sc->getStatusCode()->getValue();
116                     if (code)
117                         ex.addProperty("StatusCode2", code->toString().c_str());
118                 }
119                 if (status->getStatusMessage()) {
120                     auto_ptr_char msg(status->getStatusMessage()->getMessage());
121                     ex.addProperty("StatusMessage", msg.get());
122                 }
123             }
124         }
125     }
126 }
127
128 void AbstractHandler::prepareResponse(saml2p::StatusResponseType& response, const XMLCh* code, const XMLCh* subcode, const char* msg) const
129 {
130     saml2p::Status* status = saml2p::StatusBuilder::buildStatus();
131     saml2p::StatusCode* scode = saml2p::StatusCodeBuilder::buildStatusCode();
132     status->setStatusCode(scode);
133     scode->setValue(code);
134     if (subcode) {
135         saml2p::StatusCode* ssubcode = saml2p::StatusCodeBuilder::buildStatusCode();
136         scode->setStatusCode(ssubcode);
137         ssubcode->setValue(subcode);
138     }
139     if (msg) {
140         pair<bool,bool> flag = getBool("detailedErrors", m_configNS.get());
141         auto_ptr_XMLCh widemsg((flag.first && flag.second) ? msg : "Error processing request.");
142         saml2p::StatusMessage* sm = saml2p::StatusMessageBuilder::buildStatusMessage();
143         status->setStatusMessage(sm);
144         sm->setMessage(widemsg.get());
145     }
146     response.setStatus(status);
147 }
148 #endif
149
150 void AbstractHandler::preserveRelayState(const Application& application, HTTPResponse& response, string& relayState) const
151 {
152     if (relayState.empty())
153         return;
154
155     // No setting means just pass it by value.
156     pair<bool,const char*> mech=getString("relayState");
157     if (!mech.first || !mech.second || !*mech.second)
158         return;
159
160     if (!strcmp(mech.second, "cookie")) {
161         // Here we store the state in a cookie and send a fixed
162         // value so we can recognize it on the way back.
163         if (relayState != "cookie") {
164             const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
165             pair<string,const char*> shib_cookie=application.getCookieNameProps("_shibstate_");
166             string stateval = urlenc->encode(relayState.c_str()) + shib_cookie.second;
167             response.setCookie(shib_cookie.first.c_str(),stateval.c_str());
168             relayState = "cookie";
169         }
170     }
171     else if (strstr(mech.second,"ss:")==mech.second) {
172         if (relayState.find("ss:")!=0) {
173             mech.second+=3;
174             if (*mech.second) {
175                 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
176 #ifndef SHIBSP_LITE
177                     StorageService* storage = application.getServiceProvider().getStorageService(mech.second);
178                     if (storage) {
179                         string rsKey;
180                         SAMLConfig::getConfig().generateRandomBytes(rsKey,10);
181                         rsKey = SAMLArtifact::toHex(rsKey);
182                         storage->createString("RelayState", rsKey.c_str(), relayState.c_str(), time(NULL) + 600);
183                         relayState = string(mech.second-3) + ':' + rsKey;
184                     }
185                     else {
186                         m_log.error("Storage-backed RelayState with invalid StorageService ID (%s)", mech.second);
187                         relayState.erase();
188                     }
189 #endif
190                 }
191                 else if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
192                     DDF out,in = DDF("set::RelayState").structure();
193                     in.addmember("id").string(mech.second);
194                     in.addmember("value").string(relayState.c_str());
195                     DDFJanitor jin(in),jout(out);
196                     out = application.getServiceProvider().getListenerService()->send(in);
197                     if (!out.isstring())
198                         throw IOException("StorageService-backed RelayState mechanism did not return a state key.");
199                     relayState = string(mech.second-3) + ':' + out.string();
200                 }
201             }
202         }
203     }
204     else
205         throw ConfigurationException("Unsupported relayState mechanism ($1).", params(1,mech.second));
206 }
207
208 void AbstractHandler::recoverRelayState(const Application& application, HTTPRequest& httpRequest, string& relayState, bool clear) const
209 {
210     SPConfig& conf = SPConfig::getConfig();
211
212     // Look for StorageService-backed state of the form "ss:SSID:key".
213     const char* state = relayState.c_str();
214     if (strstr(state,"ss:")==state) {
215         state += 3;
216         const char* key = strchr(state,':');
217         if (key) {
218             string ssid = relayState.substr(3, key - state);
219             key++;
220             if (!ssid.empty() && *key) {
221                 if (conf.isEnabled(SPConfig::OutOfProcess)) {
222 #ifndef SHIBSP_LITE
223                     StorageService* storage = conf.getServiceProvider()->getStorageService(ssid.c_str());
224                     if (storage) {
225                         ssid = key;
226                         if (storage->readString("RelayState",ssid.c_str(),&relayState)>0) {
227                             if (clear)
228                                 storage->deleteString("RelayState",ssid.c_str());
229                             return;
230                         }
231                         else
232                             relayState.erase();
233                     }
234                     else {
235                         Category::getInstance(SHIBSP_LOGCAT".Handler").error(
236                             "Storage-backed RelayState with invalid StorageService ID (%s)", ssid.c_str()
237                             );
238                         relayState.erase();
239                     }
240 #endif
241                 }
242                 else if (conf.isEnabled(SPConfig::InProcess)) {
243                     DDF out,in = DDF("get::RelayState").structure();
244                     in.addmember("id").string(ssid.c_str());
245                     in.addmember("key").string(key);
246                     in.addmember("clear").integer(clear ? 1 : 0);
247                     DDFJanitor jin(in),jout(out);
248                     out = application.getServiceProvider().getListenerService()->send(in);
249                     if (!out.isstring()) {
250                         m_log.error("StorageService-backed RelayState mechanism did not return a state value.");
251                         relayState.erase();
252                     }
253                     else {
254                         relayState = out.string();
255                         return;
256                     }
257                 }
258             }
259         }
260     }
261     
262     if (conf.isEnabled(SPConfig::InProcess)) {
263         if (relayState == "cookie") {
264             // Pull the value from the "relay state" cookie.
265             pair<string,const char*> relay_cookie = application.getCookieNameProps("_shibstate_");
266             // In process, we should be able to cast down to a full SPRequest.
267             SPRequest& request = dynamic_cast<SPRequest&>(httpRequest);
268             const char* state = request.getCookie(relay_cookie.first.c_str());
269             if (state && *state) {
270                 // URL-decode the value.
271                 char* rscopy=strdup(state);
272                 XMLToolingConfig::getConfig().getURLEncoder()->decode(rscopy);
273                 relayState = rscopy;
274                 free(rscopy);
275                 
276                 if (clear)
277                     request.setCookie(relay_cookie.first.c_str(),relay_cookie.second);
278                 return;
279             }
280
281             relayState.erase();
282         }
283
284         // Check for "default" value.
285         if (relayState.empty() || relayState == "default") {
286             pair<bool,const char*> homeURL=application.getString("homeURL");
287             relayState=homeURL.first ? homeURL.second : "/";
288             return;
289         }
290     }
291
292     if (relayState == "default")
293         relayState.empty();
294 }