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 * 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 "SessionCache.h"
33 # include "security/SecurityPolicy.h"
34 # include "util/TemplateParameters.h"
36 # include <saml/SAMLConfig.h>
37 # include <saml/saml2/core/Protocols.h>
38 # include <saml/saml2/metadata/EndpointManager.h>
39 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
40 # include <xmltooling/util/URLEncoder.h>
41 using namespace opensaml::saml2;
42 using namespace opensaml::saml2p;
43 using namespace opensaml::saml2md;
44 using namespace opensaml;
47 using namespace shibsp;
48 using namespace xmltooling;
53 #if defined (_MSC_VER)
54 #pragma warning( push )
55 #pragma warning( disable : 4250 )
58 class SHIBSP_DLLLOCAL SAML2Logout : public AbstractHandler, public LogoutHandler
61 SAML2Logout(const DOMElement* e, const char* appId);
62 virtual ~SAML2Logout() {
64 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
66 XMLString::release(&m_outgoing);
67 for_each(m_encoders.begin(), m_encoders.end(), cleanup_pair<const XMLCh*,MessageEncoder>());
72 void receive(DDF& in, ostream& out);
73 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
76 void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
77 const char* loc = getString("Location").second;
78 string hurl(handlerURL);
82 auto_ptr_XMLCh widen(hurl.c_str());
83 SingleLogoutService* ep = SingleLogoutServiceBuilder::buildSingleLogoutService();
84 ep->setLocation(widen.get());
85 ep->setBinding(getXMLString("Binding").second);
86 role.getSingleLogoutServices().push_back(ep);
87 role.addSupport(samlconstants::SAML20P_NS);
90 const char* getType() const {
91 return "SingleLogoutService";
96 pair<bool,long> doRequest(
97 const Application& application, const char* session_id, const HTTPRequest& httpRequest, HTTPResponse& httpResponse
101 bool stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const;
103 pair<bool,long> sendResponse(
104 const XMLCh* requestID,
106 const XMLCh* subcode,
108 const char* relayState,
109 const RoleDescriptor* role,
110 const Application& application,
111 HTTPResponse& httpResponse,
116 MessageDecoder* m_decoder;
118 vector<const XMLCh*> m_bindings;
119 map<const XMLCh*,MessageEncoder*> m_encoders;
123 #if defined (_MSC_VER)
124 #pragma warning( pop )
127 Handler* SHIBSP_DLLLOCAL SAML2LogoutFactory(const pair<const DOMElement*,const char*>& p)
129 return new SAML2Logout(p.first, p.second);
133 SAML2Logout::SAML2Logout(const DOMElement* e, const char* appId)
134 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".Logout.SAML2"))
136 ,m_role(samlconstants::SAML20MD_NS, IDPSSODescriptor::LOCAL_NAME), m_decoder(NULL), m_outgoing(NULL)
141 m_preserve.push_back("ID");
142 m_preserve.push_back("entityID");
143 m_preserve.push_back("RelayState");
145 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
146 SAMLConfig& conf = SAMLConfig::getConfig();
148 // Handle incoming binding.
149 m_decoder = conf.MessageDecoderManager.newPlugin(getString("Binding").second,make_pair(e,shibspconstants::SHIB2SPCONFIG_NS));
150 m_decoder->setArtifactResolver(SPConfig::getConfig().getArtifactResolver());
152 if (m_decoder->isUserAgentPresent()) {
153 // Handle front-channel binding setup.
154 pair<bool,const XMLCh*> outgoing = getXMLString("outgoingBindings", m_configNS.get());
155 if (outgoing.first) {
156 m_outgoing = XMLString::replicate(outgoing.second);
157 XMLString::trim(m_outgoing);
160 // No override, so we'll install a default binding precedence.
161 string prec = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
162 samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
163 m_outgoing = XMLString::transcode(prec.c_str());
167 XMLCh* start = m_outgoing;
168 while (start && *start) {
169 pos = XMLString::indexOf(start,chSpace);
171 *(start + pos)=chNull;
172 m_bindings.push_back(start);
174 auto_ptr_char b(start);
175 MessageEncoder * encoder = conf.MessageEncoderManager.newPlugin(b.get(),make_pair(e,shibspconstants::SHIB2SPCONFIG_NS));
176 m_encoders[start] = encoder;
177 m_log.debug("supporting outgoing front-channel binding (%s)", b.get());
179 catch (exception& ex) {
180 m_log.error("error building MessageEncoder: %s", ex.what());
183 start = start + pos + 1;
189 MessageEncoder* encoder = conf.MessageEncoderManager.newPlugin(
190 getString("Binding").second,make_pair(e,shibspconstants::SHIB2SPCONFIG_NS)
192 m_encoders.insert(pair<const XMLCh*,MessageEncoder*>(NULL, encoder));
197 string address(appId);
198 address += getString("Location").second;
199 setAddress(address.c_str());
202 pair<bool,long> SAML2Logout::run(SPRequest& request, bool isHandler) const
204 // Defer to base class for front-channel loop first.
205 // This won't initiate the loop, only continue/end it.
206 pair<bool,long> ret = LogoutHandler::run(request, isHandler);
210 // Get the session_id in case this is a front-channel LogoutRequest.
211 pair<string,const char*> shib_cookie = request.getApplication().getCookieNameProps("_shibsession_");
212 const char* session_id = request.getCookie(shib_cookie.first.c_str());
214 SPConfig& conf = SPConfig::getConfig();
215 if (conf.isEnabled(SPConfig::OutOfProcess)) {
216 // When out of process, we run natively and directly process the message.
217 return doRequest(request.getApplication(), session_id, request, request);
220 // When not out of process, we remote all the message processing.
221 DDF out,in = wrap(request, NULL, true);
222 DDFJanitor jin(in), jout(out);
224 in.addmember("session_id").string(session_id);
225 out=request.getServiceProvider().getListenerService()->send(in);
226 return unwrap(request, out);
230 void SAML2Logout::receive(DDF& in, ostream& out)
233 const char* aid=in["application_id"].string();
234 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
236 // Something's horribly wrong.
237 m_log.error("couldn't find application (%s) for logout", aid ? aid : "(missing)");
238 throw ConfigurationException("Unable to locate application for logout, deleted?");
241 // Unpack the request.
243 DDFJanitor jout(ret);
244 auto_ptr<HTTPRequest> req(getRequest(in));
245 auto_ptr<HTTPResponse> resp(getResponse(ret));
247 // Since we're remoted, the result should either be a throw, which we pass on,
248 // a false/0 return, which we just return as an empty structure, or a response/redirect,
249 // which we capture in the facade and send back.
250 doRequest(*app, in["session_id"].string(), *req.get(), *resp.get());
254 pair<bool,long> SAML2Logout::doRequest(
255 const Application& application, const char* session_id, const HTTPRequest& request, HTTPResponse& response
259 SessionCache* cache = application.getServiceProvider().getSessionCache();
260 if (!strcmp(request.getMethod(),"GET") && request.getParameter("notifying")) {
262 // This is returning from a front-channel notification, so we have to do the back-channel and then
263 // respond. To do that, we need state from the original request.
264 if (!request.getParameter("entityID")) {
266 cache->remove(session_id, application);
268 pair<string,const char*> shib_cookie=application.getCookieNameProps("_shibsession_");
269 response.setCookie(shib_cookie.first.c_str(), shib_cookie.second);
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;
277 vector<string> sessions(1,session_id);
278 worked1 = notifyBackChannel(application, request.getRequestURL(), sessions, false);
280 cache->remove(session_id, application);
283 catch (exception& ex) {
284 m_log.error("error removing session (%s): %s", session_id, ex.what());
288 pair<string,const char*> shib_cookie=application.getCookieNameProps("_shibsession_");
289 response.setCookie(shib_cookie.first.c_str(), shib_cookie.second);
292 worked1 = worked2 = true;
295 // We need metadata to issue a response.
296 Locker metadataLocker(application.getMetadataProvider());
297 const EntityDescriptor* entity = application.getMetadataProvider()->getEntityDescriptor(request.getParameter("entityID"));
299 throw MetadataException(
300 "Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", request.getParameter("entityID"))
303 const IDPSSODescriptor* idp = find_if(entity->getIDPSSODescriptors(), isValidForProtocol(samlconstants::SAML20P_NS));
305 throw MetadataException(
306 "Unable to locate SAML 2.0 IdP role for identity provider ($entityID).",
307 namedparams(1, "entityID", request.getParameter("entityID"))
311 auto_ptr_XMLCh reqid(request.getParameter("ID"));
312 if (worked1 && worked2) {
313 // Successful LogoutResponse. Has to be front-channel or we couldn't be here.
315 reqid.get(), StatusCode::SUCCESS, NULL, NULL, request.getParameter("RelayState"), idp, application, response, true
321 StatusCode::RESPONDER, NULL, "Unable to fully destroy principal's session.",
322 request.getParameter("RelayState"),
330 // If we get here, it's an external protocol message to decode.
332 // Locate policy key.
333 pair<bool,const char*> policyId = getString("policyId", m_configNS.get()); // namespace-qualified if inside handler element
335 policyId = application.getString("policyId"); // unqualified in Application(s) element
337 // Access policy properties.
338 const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId.second);
339 pair<bool,bool> validate = settings->getBool("validate");
341 // Lock metadata for use by policy.
342 Locker metadataLocker(application.getMetadataProvider());
344 // Create the policy.
345 shibsp::SecurityPolicy policy(application, &m_role, validate.first && validate.second);
347 // Decode the message.
349 auto_ptr<XMLObject> msg(m_decoder->decode(relayState, request, policy));
350 const LogoutRequest* logoutRequest = dynamic_cast<LogoutRequest*>(msg.get());
352 if (!policy.isAuthenticated())
353 throw SecurityPolicyException("Security of LogoutRequest not established.");
355 // Message from IdP to logout one or more sessions.
357 // If this is front-channel, we have to have a session_id to use already.
358 if (m_decoder->isUserAgentPresent() && !session_id) {
359 m_log.error("no active session");
361 logoutRequest->getID(),
362 StatusCode::REQUESTER, StatusCode::UNKNOWN_PRINCIPAL, "No active session found in request.",
364 policy.getIssuerMetadata(),
371 bool ownedName = false;
372 NameID* nameid = logoutRequest->getNameID();
374 // Check for EncryptedID.
375 EncryptedID* encname = logoutRequest->getEncryptedID();
377 CredentialResolver* cr=application.getCredentialResolver();
379 m_log.warn("found encrypted NameID, but no decryption credential was available");
381 Locker credlocker(cr);
382 auto_ptr<MetadataCredentialCriteria> mcc(
383 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
386 auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr,application.getXMLString("entityID").second,mcc.get()));
387 nameid = dynamic_cast<NameID*>(decryptedID.get());
390 decryptedID.release();
393 catch (exception& ex) {
394 m_log.error(ex.what());
400 // No NameID, so must respond with an error.
401 m_log.error("NameID not found in request");
403 logoutRequest->getID(),
404 StatusCode::REQUESTER, StatusCode::UNKNOWN_PRINCIPAL, "NameID not found in request.",
406 policy.getIssuerMetadata(),
409 m_decoder->isUserAgentPresent()
413 auto_ptr<NameID> namewrapper(ownedName ? nameid : NULL);
415 // Suck indexes out of the request for next steps.
417 EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL;
418 const vector<SessionIndex*> sindexes = logoutRequest->getSessionIndexs();
419 for (vector<SessionIndex*>::const_iterator i = sindexes.begin(); i != sindexes.end(); ++i) {
420 auto_ptr_char sindex((*i)->getSessionIndex());
421 indexes.insert(sindex.get());
424 // For a front-channel LogoutRequest, we have to match the information in the request
425 // against the current session.
427 if (!cache->matches(session_id, entity, *nameid, &indexes, application)) {
429 logoutRequest->getID(),
430 StatusCode::REQUESTER, StatusCode::REQUEST_DENIED, "Active sessions did not match logout request.",
432 policy.getIssuerMetadata(),
441 // Now we perform "logout" by finding the matching sessions.
442 vector<string> sessions;
444 time_t expires = logoutRequest->getNotOnOrAfter() ? logoutRequest->getNotOnOrAfterEpoch() : 0;
445 cache->logout(entity, *nameid, &indexes, expires, application, sessions);
447 // Now we actually terminate everything except for the active session,
448 // if this is front-channel, for notification purposes.
449 for (vector<string>::const_iterator sit = sessions.begin(); sit != sessions.end(); ++sit)
450 if (session_id && strcmp(sit->c_str(), session_id))
451 cache->remove(sit->c_str(), application);
453 catch (exception& ex) {
454 m_log.error("error while logging out matching sessions: %s", ex.what());
456 logoutRequest->getID(),
457 StatusCode::RESPONDER, NULL, ex.what(),
459 policy.getIssuerMetadata(),
462 m_decoder->isUserAgentPresent()
466 if (m_decoder->isUserAgentPresent()) {
467 // Pass control to the first front channel notification point, if any.
468 map<string,string> parammap;
469 if (!relayState.empty())
470 parammap["RelayState"] = relayState;
471 auto_ptr_char entityID(entity ? entity->getEntityID() : NULL);
473 parammap["entityID"] = entityID.get();
474 auto_ptr_char reqID(logoutRequest->getID());
476 parammap["ID"] = reqID.get();
477 pair<bool,long> result = notifyFrontChannel(application, request, response, ¶mmap);
482 // For back-channel requests, or if no front-channel notification is needed...
483 bool worked1 = false,worked2 = false;
484 worked1 = notifyBackChannel(application, request.getRequestURL(), sessions, false);
486 // One last session to yoink...
488 cache->remove(session_id, application);
491 catch (exception& ex) {
492 m_log.error("error removing active session (%s): %s", session_id, ex.what());
496 pair<string,const char*> shib_cookie=application.getCookieNameProps("_shibsession_");
497 response.setCookie(shib_cookie.first.c_str(), shib_cookie.second);
501 logoutRequest->getID(),
502 (worked1 && worked2) ? StatusCode::SUCCESS : StatusCode::RESPONDER,
503 (worked1 && worked2) ? NULL : StatusCode::PARTIAL_LOGOUT,
506 policy.getIssuerMetadata(),
509 m_decoder->isUserAgentPresent()
513 // A LogoutResponse completes an SP-initiated logout sequence.
514 const LogoutResponse* logoutResponse = dynamic_cast<LogoutResponse*>(msg.get());
515 if (logoutResponse) {
516 if (!policy.isAuthenticated()) {
517 SecurityPolicyException ex("Security of LogoutResponse not established.");
518 if (policy.getIssuerMetadata())
519 annotateException(&ex, policy.getIssuerMetadata()); // throws it
522 checkError(logoutResponse, policy.getIssuerMetadata()); // throws if Status doesn't look good...
524 // Return template for completion of global logout, or redirect to homeURL.
525 return sendLogoutPage(application, response, false, "Global logout completed.");
528 FatalProfileException ex("Incoming message was not a samlp:LogoutRequest or samlp:LogoutResponse.");
529 if (policy.getIssuerMetadata())
530 annotateException(&ex, policy.getIssuerMetadata()); // throws it
532 return make_pair(false,0); // never happen, satisfies compiler
534 throw ConfigurationException("Cannot process logout message using lite version of shibsp library.");
540 bool SAML2Logout::stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const
542 if (!XMLString::equals(n1.getName(), n2.getName()))
545 const XMLCh* s1 = n1.getFormat();
546 const XMLCh* s2 = n2.getFormat();
548 s1 = saml2::NameID::UNSPECIFIED;
550 s2 = saml2::NameID::UNSPECIFIED;
551 if (!XMLString::equals(s1,s2))
554 s1 = n1.getNameQualifier();
555 s2 = n2.getNameQualifier();
560 if (!XMLString::equals(s1,s2))
563 s1 = n1.getSPNameQualifier();
564 s2 = n2.getSPNameQualifier();
569 if (!XMLString::equals(s1,s2))
575 pair<bool,long> SAML2Logout::sendResponse(
576 const XMLCh* requestID,
578 const XMLCh* subcode,
580 const char* relayState,
581 const RoleDescriptor* role,
582 const Application& application,
583 HTTPResponse& httpResponse,
587 // Get endpoint and encoder to use.
588 const EndpointType* ep = NULL;
589 const MessageEncoder* encoder = NULL;
591 const IDPSSODescriptor* idp = dynamic_cast<const IDPSSODescriptor*>(role);
592 for (vector<const XMLCh*>::const_iterator b = m_bindings.begin(); idp && b!=m_bindings.end(); ++b) {
593 if (ep=EndpointManager<SingleLogoutService>(idp->getSingleLogoutServices()).getByBinding(*b)) {
594 map<const XMLCh*,MessageEncoder*>::const_iterator enc = m_encoders.find(*b);
595 if (enc!=m_encoders.end())
596 encoder = enc->second;
600 if (!ep || !encoder) {
601 auto_ptr_char id(dynamic_cast<EntityDescriptor*>(role->getParent())->getEntityID());
602 m_log.error("unable to locate compatible SLO service for provider (%s)", id.get());
603 MetadataException ex("Unable to locate endpoint at IdP ($entityID) to send LogoutResponse.");
604 annotateException(&ex, role); // throws it
608 encoder = m_encoders.begin()->second;
612 auto_ptr<LogoutResponse> logout(LogoutResponseBuilder::buildLogoutResponse());
613 logout->setInResponseTo(requestID);
615 const XMLCh* loc = ep->getResponseLocation();
617 loc = ep->getLocation();
618 logout->setDestination(loc);
620 Issuer* issuer = IssuerBuilder::buildIssuer();
621 logout->setIssuer(issuer);
622 issuer->setName(application.getXMLString("entityID").second);
623 fillStatus(*logout.get(), code, subcode, msg);
625 auto_ptr_char dest(logout->getDestination());
627 long ret = sendMessage(*encoder, logout.get(), relayState, dest.get(), role, application, httpResponse);
628 logout.release(); // freed by encoder
629 return make_pair(true,ret);