2 * Copyright 2001-2009 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 * Handles SAML 2.0 single logout protocol messages.
24 #include "exceptions.h"
25 #include "Application.h"
26 #include "ServiceProvider.h"
27 #include "handler/AbstractHandler.h"
28 #include "handler/LogoutHandler.h"
29 #include "util/SPConstants.h"
32 # include "SessionCacheEx.h"
33 # include "security/SecurityPolicy.h"
34 # include "metadata/MetadataProviderCriteria.h"
35 # include "util/TemplateParameters.h"
37 # include <saml/SAMLConfig.h>
38 # include <saml/saml2/core/Protocols.h>
39 # include <saml/saml2/metadata/EndpointManager.h>
40 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
41 # include <xmltooling/util/URLEncoder.h>
42 using namespace opensaml::saml2;
43 using namespace opensaml::saml2p;
44 using namespace opensaml::saml2md;
45 using namespace opensaml;
48 using namespace shibsp;
49 using namespace xmltooling;
54 #if defined (_MSC_VER)
55 #pragma warning( push )
56 #pragma warning( disable : 4250 )
59 class SHIBSP_DLLLOCAL SAML2Logout : public AbstractHandler, public LogoutHandler
62 SAML2Logout(const DOMElement* e, const char* appId);
63 virtual ~SAML2Logout() {
65 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
67 XMLString::release(&m_outgoing);
68 for_each(m_encoders.begin(), m_encoders.end(), cleanup_pair<const XMLCh*,MessageEncoder>());
73 void receive(DDF& in, ostream& out);
74 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
77 void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
78 const char* loc = getString("Location").second;
79 string hurl(handlerURL);
83 auto_ptr_XMLCh widen(hurl.c_str());
84 SingleLogoutService* ep = SingleLogoutServiceBuilder::buildSingleLogoutService();
85 ep->setLocation(widen.get());
86 ep->setBinding(getXMLString("Binding").second);
87 role.getSingleLogoutServices().push_back(ep);
88 role.addSupport(samlconstants::SAML20P_NS);
91 const char* getType() const {
92 return "SingleLogoutService";
97 pair<bool,long> doRequest(const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse) const;
100 pair<bool,long> sendResponse(
101 const XMLCh* requestID,
103 const XMLCh* subcode,
105 const char* relayState,
106 const RoleDescriptor* role,
107 const Application& application,
108 HTTPResponse& httpResponse,
112 xmltooling::QName m_role;
113 MessageDecoder* m_decoder;
115 vector<const XMLCh*> m_bindings;
116 map<const XMLCh*,MessageEncoder*> m_encoders;
120 #if defined (_MSC_VER)
121 #pragma warning( pop )
124 Handler* SHIBSP_DLLLOCAL SAML2LogoutFactory(const pair<const DOMElement*,const char*>& p)
126 return new SAML2Logout(p.first, p.second);
130 SAML2Logout::SAML2Logout(const DOMElement* e, const char* appId)
131 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".Logout.SAML2"))
133 ,m_role(samlconstants::SAML20MD_NS, IDPSSODescriptor::LOCAL_NAME), m_decoder(NULL), m_outgoing(NULL)
138 m_preserve.push_back("ID");
139 m_preserve.push_back("entityID");
140 m_preserve.push_back("RelayState");
142 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
143 SAMLConfig& conf = SAMLConfig::getConfig();
145 // Handle incoming binding.
146 m_decoder = conf.MessageDecoderManager.newPlugin(
147 getString("Binding").second, pair<const DOMElement*,const XMLCh*>(e,shibspconstants::SHIB2SPCONFIG_NS)
149 m_decoder->setArtifactResolver(SPConfig::getConfig().getArtifactResolver());
151 if (m_decoder->isUserAgentPresent()) {
152 // Handle front-channel binding setup.
153 pair<bool,const XMLCh*> outgoing = getXMLString("outgoingBindings", m_configNS.get());
154 if (outgoing.first) {
155 m_outgoing = XMLString::replicate(outgoing.second);
156 XMLString::trim(m_outgoing);
159 // No override, so we'll install a default binding precedence.
160 string prec = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
161 samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
162 m_outgoing = XMLString::transcode(prec.c_str());
166 XMLCh* start = m_outgoing;
167 while (start && *start) {
168 pos = XMLString::indexOf(start,chSpace);
170 *(start + pos)=chNull;
171 m_bindings.push_back(start);
173 auto_ptr_char b(start);
174 MessageEncoder * encoder = conf.MessageEncoderManager.newPlugin(
175 b.get(), pair<const DOMElement*,const XMLCh*>(e,shibspconstants::SHIB2SPCONFIG_NS)
177 if (encoder->isUserAgentPresent()) {
178 m_encoders[start] = encoder;
179 m_log.debug("supporting outgoing binding (%s)", b.get());
183 m_log.warn("skipping outgoing binding (%s), not a front-channel mechanism", b.get());
186 catch (exception& ex) {
187 m_log.error("error building MessageEncoder: %s", ex.what());
190 start = start + pos + 1;
196 MessageEncoder* encoder = conf.MessageEncoderManager.newPlugin(
197 getString("Binding").second, pair<const DOMElement*,const XMLCh*>(e,shibspconstants::SHIB2SPCONFIG_NS)
199 m_encoders.insert(pair<const XMLCh*,MessageEncoder*>(NULL, encoder));
204 string address(appId);
205 address += getString("Location").second;
206 setAddress(address.c_str());
209 pair<bool,long> SAML2Logout::run(SPRequest& request, bool isHandler) const
211 // Defer to base class for front-channel loop first.
212 // This won't initiate the loop, only continue/end it.
213 pair<bool,long> ret = LogoutHandler::run(request, isHandler);
217 SPConfig& conf = SPConfig::getConfig();
218 if (conf.isEnabled(SPConfig::OutOfProcess)) {
219 // When out of process, we run natively and directly process the message.
220 return doRequest(request.getApplication(), request, request);
223 // When not out of process, we remote all the message processing.
224 vector<string> headers(1,"Cookie");
225 DDF out,in = wrap(request, &headers, true);
226 DDFJanitor jin(in), jout(out);
227 out=request.getServiceProvider().getListenerService()->send(in);
228 return unwrap(request, out);
232 void SAML2Logout::receive(DDF& in, ostream& out)
235 const char* aid=in["application_id"].string();
236 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
238 // Something's horribly wrong.
239 m_log.error("couldn't find application (%s) for logout", aid ? aid : "(missing)");
240 throw ConfigurationException("Unable to locate application for logout, deleted?");
243 // Unpack the request.
244 auto_ptr<HTTPRequest> req(getRequest(in));
246 // Wrap a response shim.
248 DDFJanitor jout(ret);
249 auto_ptr<HTTPResponse> resp(getResponse(ret));
251 // Since we're remoted, the result should either be a throw, which we pass on,
252 // a false/0 return, which we just return as an empty structure, or a response/redirect,
253 // which we capture in the facade and send back.
254 doRequest(*app, *req.get(), *resp.get());
258 pair<bool,long> SAML2Logout::doRequest(const Application& application, const HTTPRequest& request, HTTPResponse& response) const
261 // First capture the active session ID.
262 SessionCache* cache = application.getServiceProvider().getSessionCache();
263 SessionCacheEx* cacheex = dynamic_cast<SessionCacheEx*>(cache);
264 string session_id = cache->active(application, request);
266 if (!strcmp(request.getMethod(),"GET") && request.getParameter("notifying")) {
267 // This is returning from a front-channel notification, so we have to do the back-channel and then
268 // respond. To do that, we need state from the original request.
269 if (!request.getParameter("entityID")) {
270 cache->remove(application, request, &response);
271 throw FatalProfileException("Application notification loop did not return entityID for LogoutResponse.");
274 // Best effort on back channel and to remove the user agent's session.
275 bool worked1 = false,worked2 = false;
276 if (!session_id.empty()) {
277 vector<string> sessions(1,session_id);
278 worked1 = notifyBackChannel(application, request.getRequestURL(), sessions, false);
280 cache->remove(application, request, &response);
283 catch (exception& ex) {
284 m_log.error("error removing session (%s): %s", session_id, ex.what());
288 worked1 = worked2 = true;
291 // We need metadata to issue a response.
292 MetadataProvider* m = application.getMetadataProvider();
293 Locker metadataLocker(m);
294 MetadataProviderCriteria mc(application, request.getParameter("entityID"), &IDPSSODescriptor::ELEMENT_QNAME, samlconstants::SAML20P_NS);
295 pair<const EntityDescriptor*,const RoleDescriptor*> entity = m->getEntityDescriptor(mc);
297 throw MetadataException(
298 "Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", request.getParameter("entityID"))
301 else if (!entity.second) {
302 throw MetadataException(
303 "Unable to locate SAML 2.0 IdP role for identity provider ($entityID).",
304 namedparams(1, "entityID", request.getParameter("entityID"))
308 auto_ptr_XMLCh reqid(request.getParameter("ID"));
309 if (worked1 && worked2) {
310 // Successful LogoutResponse. Has to be front-channel or we couldn't be here.
312 reqid.get(), StatusCode::SUCCESS, NULL, NULL, request.getParameter("RelayState"), entity.second, application, response, true
318 StatusCode::RESPONDER, NULL, "Unable to fully destroy principal's session.",
319 request.getParameter("RelayState"),
327 // If we get here, it's an external protocol message to decode.
329 // Locate policy key.
330 pair<bool,const char*> policyId = getString("policyId", m_configNS.get()); // namespace-qualified if inside handler element
332 policyId = application.getString("policyId"); // unqualified in Application(s) element
334 // Access policy properties.
335 const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId.second);
336 pair<bool,bool> validate = settings->getBool("validate");
338 // Lock metadata for use by policy.
339 Locker metadataLocker(application.getMetadataProvider());
341 // Create the policy.
342 shibsp::SecurityPolicy policy(application, &m_role, validate.first && validate.second);
344 // Decode the message.
346 auto_ptr<XMLObject> msg(m_decoder->decode(relayState, request, policy));
347 const LogoutRequest* logoutRequest = dynamic_cast<LogoutRequest*>(msg.get());
349 if (!policy.isAuthenticated())
350 throw SecurityPolicyException("Security of LogoutRequest not established.");
352 // Message from IdP to logout one or more sessions.
354 // If this is front-channel, we have to have a session_id to use already.
355 if (m_decoder->isUserAgentPresent() && session_id.empty()) {
356 m_log.error("no active session");
358 logoutRequest->getID(),
359 StatusCode::REQUESTER, StatusCode::UNKNOWN_PRINCIPAL, "No active session found in request.",
361 policy.getIssuerMetadata(),
368 bool ownedName = false;
369 NameID* nameid = logoutRequest->getNameID();
371 // Check for EncryptedID.
372 EncryptedID* encname = logoutRequest->getEncryptedID();
374 CredentialResolver* cr=application.getCredentialResolver();
376 m_log.warn("found encrypted NameID, but no decryption credential was available");
378 Locker credlocker(cr);
379 auto_ptr<MetadataCredentialCriteria> mcc(
380 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
383 auto_ptr<XMLObject> decryptedID(
386 application.getRelyingParty(policy.getIssuerMetadata() ? dynamic_cast<EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL)->getXMLString("entityID").second,
390 nameid = dynamic_cast<NameID*>(decryptedID.get());
393 decryptedID.release();
396 catch (exception& ex) {
397 m_log.error(ex.what());
403 // No NameID, so must respond with an error.
404 m_log.error("NameID not found in request");
406 logoutRequest->getID(),
407 StatusCode::REQUESTER, StatusCode::UNKNOWN_PRINCIPAL, "NameID not found in request.",
409 policy.getIssuerMetadata(),
412 m_decoder->isUserAgentPresent()
416 auto_ptr<NameID> namewrapper(ownedName ? nameid : NULL);
418 // Suck indexes out of the request for next steps.
420 EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL;
421 const vector<SessionIndex*> sindexes = logoutRequest->getSessionIndexs();
422 for (vector<SessionIndex*>::const_iterator i = sindexes.begin(); i != sindexes.end(); ++i) {
423 auto_ptr_char sindex((*i)->getSessionIndex());
424 indexes.insert(sindex.get());
427 // For a front-channel LogoutRequest, we have to match the information in the request
428 // against the current session.
429 if (!session_id.empty()) {
430 if (!cache->matches(application, request, entity, *nameid, &indexes)) {
432 logoutRequest->getID(),
433 StatusCode::REQUESTER, StatusCode::REQUEST_DENIED, "Active session did not match logout request.",
435 policy.getIssuerMetadata(),
444 // Now we perform "logout" by finding the matching sessions.
445 vector<string> sessions;
448 time_t expires = logoutRequest->getNotOnOrAfter() ? logoutRequest->getNotOnOrAfterEpoch() : 0;
449 cacheex->logout(application, entity, *nameid, &indexes, expires, sessions);
450 m_log.debug("session cache returned %d sessions bound to NameID in logout request", sessions.size());
452 // Now we actually terminate everything except for the active session,
453 // if this is front-channel, for notification purposes.
454 for (vector<string>::const_iterator sit = sessions.begin(); sit != sessions.end(); ++sit)
455 if (*sit != session_id)
456 cacheex->remove(application, sit->c_str()); // using the ID-based removal operation
459 m_log.warn("session cache does not support extended API, can't implement indirect logout of sessions");
460 if (!session_id.empty())
461 sessions.push_back(session_id);
464 catch (exception& ex) {
465 m_log.error("error while logging out matching sessions: %s", ex.what());
467 logoutRequest->getID(),
468 StatusCode::RESPONDER, NULL, ex.what(),
470 policy.getIssuerMetadata(),
473 m_decoder->isUserAgentPresent()
477 if (m_decoder->isUserAgentPresent()) {
478 // Pass control to the first front channel notification point, if any.
479 map<string,string> parammap;
480 if (!relayState.empty())
481 parammap["RelayState"] = relayState;
482 auto_ptr_char entityID(entity ? entity->getEntityID() : NULL);
484 parammap["entityID"] = entityID.get();
485 auto_ptr_char reqID(logoutRequest->getID());
487 parammap["ID"] = reqID.get();
488 pair<bool,long> result = notifyFrontChannel(application, request, response, ¶mmap);
493 // For back-channel requests, or if no front-channel notification is needed...
494 bool worked1 = notifyBackChannel(application, request.getRequestURL(), sessions, false);
496 if (!session_id.empty()) {
497 // One last session to yoink...
499 cache->remove(application, request, &response);
501 catch (exception& ex) {
503 m_log.error("error removing active session (%s): %s", session_id.c_str(), ex.what());
508 logoutRequest->getID(),
509 (worked1 && worked2) ? StatusCode::SUCCESS : StatusCode::RESPONDER,
510 (worked1 && worked2) ? NULL : StatusCode::PARTIAL_LOGOUT,
513 policy.getIssuerMetadata(),
516 m_decoder->isUserAgentPresent()
520 // A LogoutResponse completes an SP-initiated logout sequence.
521 const LogoutResponse* logoutResponse = dynamic_cast<LogoutResponse*>(msg.get());
522 if (logoutResponse) {
523 if (!policy.isAuthenticated()) {
524 SecurityPolicyException ex("Security of LogoutResponse not established.");
525 if (policy.getIssuerMetadata())
526 annotateException(&ex, policy.getIssuerMetadata()); // throws it
529 checkError(logoutResponse, policy.getIssuerMetadata()); // throws if Status doesn't look good...
531 // If relay state is set, recover the original return URL.
532 if (!relayState.empty())
533 recoverRelayState(application, request, response, relayState);
534 if (!relayState.empty())
535 return make_pair(true, response.sendRedirect(relayState.c_str()));
537 // Return template for completion of global logout, or redirect to homeURL.
538 return sendLogoutPage(application, request, response, false, "Global logout completed.");
541 FatalProfileException ex("Incoming message was not a samlp:LogoutRequest or samlp:LogoutResponse.");
542 if (policy.getIssuerMetadata())
543 annotateException(&ex, policy.getIssuerMetadata()); // throws it
545 return make_pair(false,0L); // never happen, satisfies compiler
547 throw ConfigurationException("Cannot process logout message using lite version of shibsp library.");
553 pair<bool,long> SAML2Logout::sendResponse(
554 const XMLCh* requestID,
556 const XMLCh* subcode,
558 const char* relayState,
559 const RoleDescriptor* role,
560 const Application& application,
561 HTTPResponse& httpResponse,
565 // Get endpoint and encoder to use.
566 const EndpointType* ep = NULL;
567 const MessageEncoder* encoder = NULL;
569 const IDPSSODescriptor* idp = dynamic_cast<const IDPSSODescriptor*>(role);
570 for (vector<const XMLCh*>::const_iterator b = m_bindings.begin(); idp && b!=m_bindings.end(); ++b) {
571 if (ep=EndpointManager<SingleLogoutService>(idp->getSingleLogoutServices()).getByBinding(*b)) {
572 map<const XMLCh*,MessageEncoder*>::const_iterator enc = m_encoders.find(*b);
573 if (enc!=m_encoders.end())
574 encoder = enc->second;
578 if (!ep || !encoder) {
579 auto_ptr_char id(dynamic_cast<EntityDescriptor*>(role->getParent())->getEntityID());
580 m_log.error("unable to locate compatible SLO service for provider (%s)", id.get());
581 MetadataException ex("Unable to locate endpoint at IdP ($entityID) to send LogoutResponse.");
582 annotateException(&ex, role); // throws it
586 encoder = m_encoders.begin()->second;
590 auto_ptr<LogoutResponse> logout(LogoutResponseBuilder::buildLogoutResponse());
591 logout->setInResponseTo(requestID);
593 const XMLCh* loc = ep->getResponseLocation();
595 loc = ep->getLocation();
596 logout->setDestination(loc);
598 Issuer* issuer = IssuerBuilder::buildIssuer();
599 logout->setIssuer(issuer);
600 issuer->setName(application.getRelyingParty(dynamic_cast<EntityDescriptor*>(role->getParent()))->getXMLString("entityID").second);
601 fillStatus(*logout.get(), code, subcode, msg);
603 auto_ptr_char dest(logout->getDestination());
605 long ret = sendMessage(*encoder, logout.get(), relayState, dest.get(), role, application, httpResponse);
606 logout.release(); // freed by encoder
607 return make_pair(true,ret);