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