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 "remoting/ListenerService.h"
30 #include "util/SPConstants.h"
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/saml2/metadata/Metadata.h>
38 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
39 # include <saml/util/SAMLConstants.h>
40 # include <xmltooling/util/StorageService.h>
41 using namespace opensaml::saml2md;
43 # include "lite/SAMLConstants.h"
46 #include <xmltooling/XMLToolingConfig.h>
47 #include <xmltooling/util/URLEncoder.h>
49 using namespace shibsp;
50 using namespace samlconstants;
51 using namespace opensaml;
52 using namespace xmltooling;
53 using namespace log4cpp;
54 using namespace xercesc;
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 AssertionLookupFactory;
62 SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory ChainingLogoutInitiatorFactory;
63 SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory LocalLogoutInitiatorFactory;
64 SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2LogoutInitiatorFactory;
67 void SHIBSP_API shibsp::registerHandlers()
69 SPConfig& conf=SPConfig::getConfig();
71 conf.AssertionConsumerServiceManager.registerFactory(SAML1_PROFILE_BROWSER_ARTIFACT, SAML1ConsumerFactory);
72 conf.AssertionConsumerServiceManager.registerFactory(SAML1_PROFILE_BROWSER_POST, SAML1ConsumerFactory);
73 conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_ARTIFACT, SAML2ConsumerFactory);
74 conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_POST, SAML2ConsumerFactory);
75 conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_POST_SIMPLESIGN, SAML2ConsumerFactory);
77 conf.ArtifactResolutionServiceManager.registerFactory(SAML20_BINDING_SOAP, SAML2ArtifactResolutionFactory);
79 conf.HandlerManager.registerFactory(SAML20_BINDING_URI, AssertionLookupFactory);
81 conf.LogoutInitiatorManager.registerFactory(CHAINING_LOGOUT_INITIATOR, ChainingLogoutInitiatorFactory);
82 conf.LogoutInitiatorManager.registerFactory(LOCAL_LOGOUT_INITIATOR, LocalLogoutInitiatorFactory);
83 conf.LogoutInitiatorManager.registerFactory(SAML2_LOGOUT_INITIATOR, SAML2LogoutInitiatorFactory);
86 AbstractHandler::AbstractHandler(
87 const DOMElement* e, log4cpp::Category& log, DOMNodeFilter* filter, const map<string,string>* remapper
88 ) : m_log(log), m_configNS(shibspconstants::SHIB2SPCONFIG_NS) {
89 load(e,log,filter,remapper);
94 void AbstractHandler::checkError(const XMLObject* response, const saml2md::RoleDescriptor* role) const
96 const saml2p::StatusResponseType* r2 = dynamic_cast<const saml2p::StatusResponseType*>(response);
98 const saml2p::Status* status = r2->getStatus();
100 const saml2p::StatusCode* sc = status->getStatusCode();
101 const XMLCh* code = sc ? sc->getValue() : NULL;
102 if (code && !XMLString::equals(code,saml2p::StatusCode::SUCCESS)) {
103 FatalProfileException ex("SAML response contained an error.");
104 annotateException(&ex, role, status); // throws it
109 const saml1p::Response* r1 = dynamic_cast<const saml1p::Response*>(response);
111 const saml1p::Status* status = r1->getStatus();
113 const saml1p::StatusCode* sc = status->getStatusCode();
114 const QName* code = sc ? sc->getValue() : NULL;
115 if (code && *code != saml1p::StatusCode::SUCCESS) {
116 FatalProfileException ex("SAML response contained an error.");
117 ex.addProperty("statusCode", code->toString().c_str());
118 if (sc->getStatusCode()) {
119 code = sc->getStatusCode()->getValue();
121 ex.addProperty("statusCode2", code->toString().c_str());
123 if (status->getStatusMessage()) {
124 auto_ptr_char msg(status->getStatusMessage()->getMessage());
125 if (msg.get() && *msg.get())
126 ex.addProperty("statusMessage", msg.get());
134 void AbstractHandler::fillStatus(saml2p::StatusResponseType& response, const XMLCh* code, const XMLCh* subcode, const char* msg) const
136 saml2p::Status* status = saml2p::StatusBuilder::buildStatus();
137 saml2p::StatusCode* scode = saml2p::StatusCodeBuilder::buildStatusCode();
138 status->setStatusCode(scode);
139 scode->setValue(code);
141 saml2p::StatusCode* ssubcode = saml2p::StatusCodeBuilder::buildStatusCode();
142 scode->setStatusCode(ssubcode);
143 ssubcode->setValue(subcode);
146 pair<bool,bool> flag = getBool("detailedErrors", m_configNS.get());
147 auto_ptr_XMLCh widemsg((flag.first && flag.second) ? msg : "Error processing request.");
148 saml2p::StatusMessage* sm = saml2p::StatusMessageBuilder::buildStatusMessage();
149 status->setStatusMessage(sm);
150 sm->setMessage(widemsg.get());
152 response.setStatus(status);
155 long AbstractHandler::sendMessage(
156 const MessageEncoder& encoder,
158 const char* relayState,
159 const char* destination,
160 const saml2md::RoleDescriptor* role,
161 const Application& application,
162 HTTPResponse& httpResponse,
163 const char* signingOption,
167 const EntityDescriptor* entity = role ? dynamic_cast<const EntityDescriptor*>(role->getParent()) : NULL;
168 const PropertySet* relyingParty = application.getRelyingParty(entity);
169 pair<bool,const char*> flag = signIfPossible ? make_pair(true,"true") : relyingParty->getString(signingOption);
170 if (role && flag.first &&
171 (!strcmp(flag.second, "true") ||
172 (encoder.isUserAgentPresent() && !strcmp(flag.second, "front")) ||
173 (!encoder.isUserAgentPresent() && !strcmp(flag.second, "back")))) {
174 CredentialResolver* credResolver=application.getCredentialResolver();
176 Locker credLocker(credResolver);
177 // Fill in criteria to use.
178 MetadataCredentialCriteria mcc(*role);
179 mcc.setUsage(CredentialCriteria::SIGNING_CREDENTIAL);
180 pair<bool,const char*> keyName = relyingParty->getString("keyName");
182 mcc.getKeyNames().insert(keyName.second);
183 pair<bool,const XMLCh*> sigalg = relyingParty->getXMLString("signatureAlg");
185 mcc.setXMLAlgorithm(sigalg.second);
186 const Credential* cred = credResolver->resolve(&mcc);
189 return encoder.encode(
198 relyingParty->getXMLString("digestAlg").second
202 m_log.warn("no signing credential resolved, leaving message unsigned");
206 m_log.warn("no credential resolver installed, leaving message unsigned");
211 return encoder.encode(httpResponse, msg, destination, entity, relayState, &application);
216 void AbstractHandler::preserveRelayState(const Application& application, HTTPResponse& response, string& relayState) const
218 if (relayState.empty())
221 // No setting means just pass it by value.
222 pair<bool,const char*> mech=getString("relayState");
223 if (!mech.first || !mech.second || !*mech.second)
226 if (!strcmp(mech.second, "cookie")) {
227 // Here we store the state in a cookie and send a fixed
228 // value so we can recognize it on the way back.
229 if (relayState != "cookie") {
230 const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
231 pair<string,const char*> shib_cookie=application.getCookieNameProps("_shibstate_");
232 string stateval = urlenc->encode(relayState.c_str()) + shib_cookie.second;
233 response.setCookie(shib_cookie.first.c_str(),stateval.c_str());
234 relayState = "cookie";
237 else if (strstr(mech.second,"ss:")==mech.second) {
238 if (relayState.find("ss:")!=0) {
241 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
243 StorageService* storage = application.getServiceProvider().getStorageService(mech.second);
246 SAMLConfig::getConfig().generateRandomBytes(rsKey,10);
247 rsKey = SAMLArtifact::toHex(rsKey);
248 if (!storage->createString("RelayState", rsKey.c_str(), relayState.c_str(), time(NULL) + 600))
249 throw IOException("Attempted to insert duplicate storage key.");
250 relayState = string(mech.second-3) + ':' + rsKey;
253 m_log.error("Storage-backed RelayState with invalid StorageService ID (%s)", mech.second);
258 else if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
259 DDF out,in = DDF("set::RelayState").structure();
260 in.addmember("id").string(mech.second);
261 in.addmember("value").string(relayState.c_str());
262 DDFJanitor jin(in),jout(out);
263 out = application.getServiceProvider().getListenerService()->send(in);
265 throw IOException("StorageService-backed RelayState mechanism did not return a state key.");
266 relayState = string(mech.second-3) + ':' + out.string();
272 throw ConfigurationException("Unsupported relayState mechanism ($1).", params(1,mech.second));
275 void AbstractHandler::recoverRelayState(const Application& application, HTTPRequest& httpRequest, string& relayState, bool clear) const
277 SPConfig& conf = SPConfig::getConfig();
279 // Look for StorageService-backed state of the form "ss:SSID:key".
280 const char* state = relayState.c_str();
281 if (strstr(state,"ss:")==state) {
283 const char* key = strchr(state,':');
285 string ssid = relayState.substr(3, key - state);
287 if (!ssid.empty() && *key) {
288 if (conf.isEnabled(SPConfig::OutOfProcess)) {
290 StorageService* storage = conf.getServiceProvider()->getStorageService(ssid.c_str());
293 if (storage->readString("RelayState",ssid.c_str(),&relayState)>0) {
295 storage->deleteString("RelayState",ssid.c_str());
302 Category::getInstance(SHIBSP_LOGCAT".Handler").error(
303 "Storage-backed RelayState with invalid StorageService ID (%s)", ssid.c_str()
309 else if (conf.isEnabled(SPConfig::InProcess)) {
310 DDF out,in = DDF("get::RelayState").structure();
311 in.addmember("id").string(ssid.c_str());
312 in.addmember("key").string(key);
313 in.addmember("clear").integer(clear ? 1 : 0);
314 DDFJanitor jin(in),jout(out);
315 out = application.getServiceProvider().getListenerService()->send(in);
316 if (!out.isstring()) {
317 m_log.error("StorageService-backed RelayState mechanism did not return a state value.");
321 relayState = out.string();
329 if (conf.isEnabled(SPConfig::InProcess)) {
330 if (relayState == "cookie") {
331 // Pull the value from the "relay state" cookie.
332 pair<string,const char*> relay_cookie = application.getCookieNameProps("_shibstate_");
333 // In process, we should be able to cast down to a full SPRequest.
334 SPRequest& request = dynamic_cast<SPRequest&>(httpRequest);
335 const char* state = request.getCookie(relay_cookie.first.c_str());
336 if (state && *state) {
337 // URL-decode the value.
338 char* rscopy=strdup(state);
339 XMLToolingConfig::getConfig().getURLEncoder()->decode(rscopy);
344 request.setCookie(relay_cookie.first.c_str(),relay_cookie.second);
351 // Check for "default" value.
352 if (relayState.empty() || relayState == "default") {
353 pair<bool,const char*> homeURL=application.getString("homeURL");
354 relayState=homeURL.first ? homeURL.second : "/";
359 if (relayState == "default")