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