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