2 * Copyright 2001-2007 Internet2
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
20 * Base class for handlers based on a DOMPropertySet.
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"
34 # include <saml/saml1/core/Protocols.h>
35 # include <saml/saml2/core/Protocols.h>
36 # include <saml/saml2/metadata/Metadata.h>
37 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
38 # include <saml/util/SAMLConstants.h>
39 # include <xmltooling/util/StorageService.h>
40 using namespace opensaml::saml2md;
42 # include "lite/SAMLConstants.h"
45 #include <xmltooling/XMLToolingConfig.h>
46 #include <xmltooling/util/URLEncoder.h>
48 using namespace shibsp;
49 using namespace samlconstants;
50 using namespace opensaml;
51 using namespace xmltooling;
52 using namespace xercesc;
56 SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML1ConsumerFactory;
57 SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2ConsumerFactory;
58 SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2ArtifactResolutionFactory;
59 SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory ChainingLogoutInitiatorFactory;
60 SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory LocalLogoutInitiatorFactory;
61 SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2LogoutInitiatorFactory;
62 SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2LogoutFactory;
63 SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2NameIDMgmtFactory;
64 SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory AssertionLookupFactory;
65 SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory MetadataGeneratorFactory;
66 SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory StatusHandlerFactory;
67 SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SessionHandlerFactory;
69 void SHIBSP_DLLLOCAL generateRandomHex(std::string& buf, unsigned int len) {
70 static char DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
74 for (unsigned int i=0; i<len; i+=4) {
77 b2 = (0xFF00 & r) >> 8;
78 buf += (DIGITS[(0xF0 & b1) >> 4 ]);
79 buf += (DIGITS[0x0F & b1]);
80 buf += (DIGITS[(0xF0 & b2) >> 4 ]);
81 buf += (DIGITS[0x0F & b2]);
86 void SHIBSP_API shibsp::registerHandlers()
88 SPConfig& conf=SPConfig::getConfig();
90 conf.AssertionConsumerServiceManager.registerFactory(SAML1_PROFILE_BROWSER_ARTIFACT, SAML1ConsumerFactory);
91 conf.AssertionConsumerServiceManager.registerFactory(SAML1_PROFILE_BROWSER_POST, SAML1ConsumerFactory);
92 conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_POST, SAML2ConsumerFactory);
93 conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_POST_SIMPLESIGN, SAML2ConsumerFactory);
94 conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_ARTIFACT, SAML2ConsumerFactory);
95 conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_PAOS, SAML2ConsumerFactory);
97 conf.ArtifactResolutionServiceManager.registerFactory(SAML20_BINDING_SOAP, SAML2ArtifactResolutionFactory);
99 conf.HandlerManager.registerFactory(SAML20_BINDING_URI, AssertionLookupFactory);
100 conf.HandlerManager.registerFactory(METADATA_GENERATOR_HANDLER, MetadataGeneratorFactory);
101 conf.HandlerManager.registerFactory(STATUS_HANDLER, StatusHandlerFactory);
102 conf.HandlerManager.registerFactory(SESSION_HANDLER, SessionHandlerFactory);
104 conf.LogoutInitiatorManager.registerFactory(CHAINING_LOGOUT_INITIATOR, ChainingLogoutInitiatorFactory);
105 conf.LogoutInitiatorManager.registerFactory(LOCAL_LOGOUT_INITIATOR, LocalLogoutInitiatorFactory);
106 conf.LogoutInitiatorManager.registerFactory(SAML2_LOGOUT_INITIATOR, SAML2LogoutInitiatorFactory);
107 conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_SOAP, SAML2LogoutFactory);
108 conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_HTTP_REDIRECT, SAML2LogoutFactory);
109 conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_HTTP_POST, SAML2LogoutFactory);
110 conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_HTTP_POST_SIMPLESIGN, SAML2LogoutFactory);
111 conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_HTTP_ARTIFACT, SAML2LogoutFactory);
113 conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_SOAP, SAML2NameIDMgmtFactory);
114 conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_HTTP_REDIRECT, SAML2NameIDMgmtFactory);
115 conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_HTTP_POST, SAML2NameIDMgmtFactory);
116 conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_HTTP_POST_SIMPLESIGN, SAML2NameIDMgmtFactory);
117 conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_HTTP_ARTIFACT, SAML2NameIDMgmtFactory);
120 AbstractHandler::AbstractHandler(
121 const DOMElement* e, Category& log, DOMNodeFilter* filter, const map<string,string>* remapper
122 ) : m_log(log), m_configNS(shibspconstants::SHIB2SPCONFIG_NS) {
123 load(e,NULL,filter,remapper);
128 void AbstractHandler::checkError(const XMLObject* response, const saml2md::RoleDescriptor* role) const
130 const saml2p::StatusResponseType* r2 = dynamic_cast<const saml2p::StatusResponseType*>(response);
132 const saml2p::Status* status = r2->getStatus();
134 const saml2p::StatusCode* sc = status->getStatusCode();
135 const XMLCh* code = sc ? sc->getValue() : NULL;
136 if (code && !XMLString::equals(code,saml2p::StatusCode::SUCCESS)) {
137 FatalProfileException ex("SAML response contained an error.");
138 annotateException(&ex, role, status); // throws it
143 const saml1p::Response* r1 = dynamic_cast<const saml1p::Response*>(response);
145 const saml1p::Status* status = r1->getStatus();
147 const saml1p::StatusCode* sc = status->getStatusCode();
148 const QName* code = sc ? sc->getValue() : NULL;
149 if (code && *code != saml1p::StatusCode::SUCCESS) {
150 FatalProfileException ex("SAML response contained an error.");
151 ex.addProperty("statusCode", code->toString().c_str());
152 if (sc->getStatusCode()) {
153 code = sc->getStatusCode()->getValue();
155 ex.addProperty("statusCode2", code->toString().c_str());
157 if (status->getStatusMessage()) {
158 auto_ptr_char msg(status->getStatusMessage()->getMessage());
159 if (msg.get() && *msg.get())
160 ex.addProperty("statusMessage", msg.get());
168 void AbstractHandler::fillStatus(saml2p::StatusResponseType& response, const XMLCh* code, const XMLCh* subcode, const char* msg) const
170 saml2p::Status* status = saml2p::StatusBuilder::buildStatus();
171 saml2p::StatusCode* scode = saml2p::StatusCodeBuilder::buildStatusCode();
172 status->setStatusCode(scode);
173 scode->setValue(code);
175 saml2p::StatusCode* ssubcode = saml2p::StatusCodeBuilder::buildStatusCode();
176 scode->setStatusCode(ssubcode);
177 ssubcode->setValue(subcode);
180 pair<bool,bool> flag = getBool("detailedErrors", m_configNS.get());
181 auto_ptr_XMLCh widemsg((flag.first && flag.second) ? msg : "Error processing request.");
182 saml2p::StatusMessage* sm = saml2p::StatusMessageBuilder::buildStatusMessage();
183 status->setStatusMessage(sm);
184 sm->setMessage(widemsg.get());
186 response.setStatus(status);
189 long AbstractHandler::sendMessage(
190 const MessageEncoder& encoder,
192 const char* relayState,
193 const char* destination,
194 const saml2md::RoleDescriptor* role,
195 const Application& application,
196 HTTPResponse& httpResponse,
200 const EntityDescriptor* entity = role ? dynamic_cast<const EntityDescriptor*>(role->getParent()) : NULL;
201 const PropertySet* relyingParty = application.getRelyingParty(entity);
202 pair<bool,const char*> flag = signIfPossible ? make_pair(true,(const char*)"true") : relyingParty->getString("signing");
203 if (role && flag.first &&
204 (!strcmp(flag.second, "true") ||
205 (encoder.isUserAgentPresent() && !strcmp(flag.second, "front")) ||
206 (!encoder.isUserAgentPresent() && !strcmp(flag.second, "back")))) {
207 CredentialResolver* credResolver=application.getCredentialResolver();
209 Locker credLocker(credResolver);
210 const Credential* cred = NULL;
211 pair<bool,const char*> keyName = relyingParty->getString("keyName");
212 pair<bool,const XMLCh*> sigalg = relyingParty->getXMLString("signingAlg");
214 MetadataCredentialCriteria mcc(*role);
215 mcc.setUsage(Credential::SIGNING_CREDENTIAL);
217 mcc.getKeyNames().insert(keyName.second);
219 mcc.setXMLAlgorithm(sigalg.second);
220 cred = credResolver->resolve(&mcc);
223 CredentialCriteria cc;
224 cc.setUsage(Credential::SIGNING_CREDENTIAL);
226 cc.getKeyNames().insert(keyName.second);
228 cc.setXMLAlgorithm(sigalg.second);
229 cred = credResolver->resolve(&cc);
233 return encoder.encode(
242 relyingParty->getXMLString("digestAlg").second
246 m_log.warn("no signing credential resolved, leaving message unsigned");
250 m_log.warn("no credential resolver installed, leaving message unsigned");
255 return encoder.encode(httpResponse, msg, destination, entity, relayState, &application);
260 void AbstractHandler::preserveRelayState(const Application& application, HTTPResponse& response, string& relayState) const
262 if (relayState.empty())
265 // No setting means just pass it by value.
266 pair<bool,const char*> mech=getString("relayState");
267 if (!mech.first || !mech.second || !*mech.second)
270 if (!strcmp(mech.second, "cookie")) {
271 // Here we store the state in a cookie and send a fixed
272 // value so we can recognize it on the way back.
273 if (relayState.find("cookie:") != 0) {
274 const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
275 pair<string,const char*> shib_cookie=application.getCookieNameProps("_shibstate_");
276 string stateval = urlenc->encode(relayState.c_str()) + shib_cookie.second;
277 // Generate a random key for the cookie name instead of the fixed name.
279 generateRandomHex(rsKey,5);
280 shib_cookie.first = "_shibstate_" + rsKey;
281 response.setCookie(shib_cookie.first.c_str(),stateval.c_str());
282 relayState = "cookie:" + rsKey;
285 else if (strstr(mech.second,"ss:")==mech.second) {
286 if (relayState.find("ss:") != 0) {
289 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
291 StorageService* storage = application.getServiceProvider().getStorageService(mech.second);
294 generateRandomHex(rsKey,5);
295 if (!storage->createString("RelayState", rsKey.c_str(), relayState.c_str(), time(NULL) + 600))
296 throw IOException("Attempted to insert duplicate storage key.");
297 relayState = string(mech.second-3) + ':' + rsKey;
300 m_log.error("Storage-backed RelayState with invalid StorageService ID (%s)", mech.second);
305 else if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
306 DDF out,in = DDF("set::RelayState").structure();
307 in.addmember("id").string(mech.second);
308 in.addmember("value").string(relayState.c_str());
309 DDFJanitor jin(in),jout(out);
310 out = application.getServiceProvider().getListenerService()->send(in);
312 throw IOException("StorageService-backed RelayState mechanism did not return a state key.");
313 relayState = string(mech.second-3) + ':' + out.string();
319 throw ConfigurationException("Unsupported relayState mechanism ($1).", params(1,mech.second));
322 void AbstractHandler::recoverRelayState(
323 const Application& application, const HTTPRequest& request, HTTPResponse& response, string& relayState, bool clear
326 SPConfig& conf = SPConfig::getConfig();
328 // Look for StorageService-backed state of the form "ss:SSID:key".
329 const char* state = relayState.c_str();
330 if (strstr(state,"ss:")==state) {
332 const char* key = strchr(state,':');
334 string ssid = relayState.substr(3, key - state);
336 if (!ssid.empty() && *key) {
337 if (conf.isEnabled(SPConfig::OutOfProcess)) {
339 StorageService* storage = conf.getServiceProvider()->getStorageService(ssid.c_str());
342 if (storage->readString("RelayState",ssid.c_str(),&relayState)>0) {
344 storage->deleteString("RelayState",ssid.c_str());
351 Category::getInstance(SHIBSP_LOGCAT".Handler").error(
352 "Storage-backed RelayState with invalid StorageService ID (%s)", ssid.c_str()
358 else if (conf.isEnabled(SPConfig::InProcess)) {
359 DDF out,in = DDF("get::RelayState").structure();
360 in.addmember("id").string(ssid.c_str());
361 in.addmember("key").string(key);
362 in.addmember("clear").integer(clear ? 1 : 0);
363 DDFJanitor jin(in),jout(out);
364 out = application.getServiceProvider().getListenerService()->send(in);
365 if (!out.isstring()) {
366 m_log.error("StorageService-backed RelayState mechanism did not return a state value.");
370 relayState = out.string();
378 // Look for cookie-backed state of the form "cookie:key".
379 if (strstr(state,"cookie:")==state) {
382 // Pull the value from the "relay state" cookie.
383 pair<string,const char*> relay_cookie = application.getCookieNameProps("_shibstate_");
384 relay_cookie.first = string("_shibstate_") + state;
385 state = request.getCookie(relay_cookie.first.c_str());
386 if (state && *state) {
387 // URL-decode the value.
388 char* rscopy=strdup(state);
389 XMLToolingConfig::getConfig().getURLEncoder()->decode(rscopy);
394 string exp(relay_cookie.second);
395 exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
396 response.setCookie(relay_cookie.first.c_str(), exp.c_str());
405 // Check for "default" value.
406 if (relayState.empty() || relayState == "default") {
407 pair<bool,const char*> homeURL=application.getString("homeURL");
408 relayState=homeURL.first ? homeURL.second : "/";
412 if (relayState == "default")