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(
150 getString("Binding").second, pair<const DOMElement*,const XMLCh*>(e,shibspconstants::SHIB2SPCONFIG_NS)
152 m_decoder->setArtifactResolver(SPConfig::getConfig().getArtifactResolver());
154 if (m_decoder->isUserAgentPresent()) {
155 // Handle front-channel binding setup.
156 pair<bool,const XMLCh*> outgoing = getXMLString("outgoingBindings", m_configNS.get());
157 if (outgoing.first) {
158 m_outgoing = XMLString::replicate(outgoing.second);
159 XMLString::trim(m_outgoing);
162 // No override, so we'll install a default binding precedence.
163 string prec = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
164 samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
165 m_outgoing = XMLString::transcode(prec.c_str());
169 XMLCh* start = m_outgoing;
170 while (start && *start) {
171 pos = XMLString::indexOf(start,chSpace);
173 *(start + pos)=chNull;
174 m_bindings.push_back(start);
176 auto_ptr_char b(start);
177 MessageEncoder * encoder = conf.MessageEncoderManager.newPlugin(
178 b.get(), pair<const DOMElement*,const XMLCh*>(e,shibspconstants::SHIB2SPCONFIG_NS)
180 m_encoders[start] = encoder;
181 m_log.debug("supporting outgoing front-channel binding (%s)", b.get());
183 catch (exception& ex) {
184 m_log.error("error building MessageEncoder: %s", ex.what());
187 start = start + pos + 1;
193 MessageEncoder* encoder = conf.MessageEncoderManager.newPlugin(
194 getString("Binding").second, pair<const DOMElement*,const XMLCh*>(e,shibspconstants::SHIB2SPCONFIG_NS)
196 m_encoders.insert(pair<const XMLCh*,MessageEncoder*>(NULL, encoder));
201 string address(appId);
202 address += getString("Location").second;
203 setAddress(address.c_str());
206 pair<bool,long> SAML2Logout::run(SPRequest& request, bool isHandler) const
208 // Defer to base class for front-channel loop first.
209 // This won't initiate the loop, only continue/end it.
210 pair<bool,long> ret = LogoutHandler::run(request, isHandler);
214 // Get the session_id in case this is a front-channel LogoutRequest.
215 pair<string,const char*> shib_cookie = request.getApplication().getCookieNameProps("_shibsession_");
216 const char* session_id = request.getCookie(shib_cookie.first.c_str());
218 SPConfig& conf = SPConfig::getConfig();
219 if (conf.isEnabled(SPConfig::OutOfProcess)) {
220 // When out of process, we run natively and directly process the message.
221 return doRequest(request.getApplication(), session_id, request, request);
224 // When not out of process, we remote all the message processing.
225 DDF out,in = wrap(request, NULL, true);
226 DDFJanitor jin(in), jout(out);
228 in.addmember("session_id").string(session_id);
229 out=request.getServiceProvider().getListenerService()->send(in);
230 return unwrap(request, out);
234 void SAML2Logout::receive(DDF& in, ostream& out)
237 const char* aid=in["application_id"].string();
238 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
240 // Something's horribly wrong.
241 m_log.error("couldn't find application (%s) for logout", aid ? aid : "(missing)");
242 throw ConfigurationException("Unable to locate application for logout, deleted?");
245 // Unpack the request.
247 DDFJanitor jout(ret);
248 auto_ptr<HTTPRequest> req(getRequest(in));
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, in["session_id"].string(), *req.get(), *resp.get());
258 pair<bool,long> SAML2Logout::doRequest(
259 const Application& application, const char* session_id, const HTTPRequest& request, HTTPResponse& response
263 SessionCache* cache = application.getServiceProvider().getSessionCache();
264 if (!strcmp(request.getMethod(),"GET") && request.getParameter("notifying")) {
266 // This is returning from a front-channel notification, so we have to do the back-channel and then
267 // respond. To do that, we need state from the original request.
268 if (!request.getParameter("entityID")) {
270 cache->remove(session_id, application);
272 pair<string,const char*> shib_cookie=application.getCookieNameProps("_shibsession_");
273 response.setCookie(shib_cookie.first.c_str(), shib_cookie.second);
275 throw FatalProfileException("Application notification loop did not return entityID for LogoutResponse.");
278 // Best effort on back channel and to remove the user agent's session.
279 bool worked1 = false,worked2 = false;
281 vector<string> sessions(1,session_id);
282 worked1 = notifyBackChannel(application, request.getRequestURL(), sessions, false);
284 cache->remove(session_id, application);
287 catch (exception& ex) {
288 m_log.error("error removing session (%s): %s", session_id, ex.what());
292 pair<string,const char*> shib_cookie=application.getCookieNameProps("_shibsession_");
293 response.setCookie(shib_cookie.first.c_str(), shib_cookie.second);
296 worked1 = worked2 = true;
299 // We need metadata to issue a response.
300 MetadataProvider* m = application.getMetadataProvider();
301 Locker metadataLocker(m);
302 MetadataProvider::Criteria mc(request.getParameter("entityID"), &IDPSSODescriptor::ELEMENT_QNAME, samlconstants::SAML20P_NS);
303 pair<const EntityDescriptor*,const RoleDescriptor*> entity = m->getEntityDescriptor(mc);
305 throw MetadataException(
306 "Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", request.getParameter("entityID"))
309 else if (!entity.second) {
310 throw MetadataException(
311 "Unable to locate SAML 2.0 IdP role for identity provider ($entityID).",
312 namedparams(1, "entityID", request.getParameter("entityID"))
316 auto_ptr_XMLCh reqid(request.getParameter("ID"));
317 if (worked1 && worked2) {
318 // Successful LogoutResponse. Has to be front-channel or we couldn't be here.
320 reqid.get(), StatusCode::SUCCESS, NULL, NULL, request.getParameter("RelayState"), entity.second, application, response, true
326 StatusCode::RESPONDER, NULL, "Unable to fully destroy principal's session.",
327 request.getParameter("RelayState"),
335 // If we get here, it's an external protocol message to decode.
337 // Locate policy key.
338 pair<bool,const char*> policyId = getString("policyId", m_configNS.get()); // namespace-qualified if inside handler element
340 policyId = application.getString("policyId"); // unqualified in Application(s) element
342 // Access policy properties.
343 const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId.second);
344 pair<bool,bool> validate = settings->getBool("validate");
346 // Lock metadata for use by policy.
347 Locker metadataLocker(application.getMetadataProvider());
349 // Create the policy.
350 shibsp::SecurityPolicy policy(application, &m_role, validate.first && validate.second);
352 // Decode the message.
354 auto_ptr<XMLObject> msg(m_decoder->decode(relayState, request, policy));
355 const LogoutRequest* logoutRequest = dynamic_cast<LogoutRequest*>(msg.get());
357 if (!policy.isAuthenticated())
358 throw SecurityPolicyException("Security of LogoutRequest not established.");
360 // Message from IdP to logout one or more sessions.
362 // If this is front-channel, we have to have a session_id to use already.
363 if (m_decoder->isUserAgentPresent() && !session_id) {
364 m_log.error("no active session");
366 logoutRequest->getID(),
367 StatusCode::REQUESTER, StatusCode::UNKNOWN_PRINCIPAL, "No active session found in request.",
369 policy.getIssuerMetadata(),
376 bool ownedName = false;
377 NameID* nameid = logoutRequest->getNameID();
379 // Check for EncryptedID.
380 EncryptedID* encname = logoutRequest->getEncryptedID();
382 CredentialResolver* cr=application.getCredentialResolver();
384 m_log.warn("found encrypted NameID, but no decryption credential was available");
386 Locker credlocker(cr);
387 auto_ptr<MetadataCredentialCriteria> mcc(
388 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
391 auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr,application.getXMLString("entityID").second,mcc.get()));
392 nameid = dynamic_cast<NameID*>(decryptedID.get());
395 decryptedID.release();
398 catch (exception& ex) {
399 m_log.error(ex.what());
405 // No NameID, so must respond with an error.
406 m_log.error("NameID not found in request");
408 logoutRequest->getID(),
409 StatusCode::REQUESTER, StatusCode::UNKNOWN_PRINCIPAL, "NameID not found in request.",
411 policy.getIssuerMetadata(),
414 m_decoder->isUserAgentPresent()
418 auto_ptr<NameID> namewrapper(ownedName ? nameid : NULL);
420 // Suck indexes out of the request for next steps.
422 EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL;
423 const vector<SessionIndex*> sindexes = logoutRequest->getSessionIndexs();
424 for (vector<SessionIndex*>::const_iterator i = sindexes.begin(); i != sindexes.end(); ++i) {
425 auto_ptr_char sindex((*i)->getSessionIndex());
426 indexes.insert(sindex.get());
429 // For a front-channel LogoutRequest, we have to match the information in the request
430 // against the current session.
432 if (!cache->matches(session_id, entity, *nameid, &indexes, application)) {
434 logoutRequest->getID(),
435 StatusCode::REQUESTER, StatusCode::REQUEST_DENIED, "Active sessions did not match logout request.",
437 policy.getIssuerMetadata(),
446 // Now we perform "logout" by finding the matching sessions.
447 vector<string> sessions;
449 time_t expires = logoutRequest->getNotOnOrAfter() ? logoutRequest->getNotOnOrAfterEpoch() : 0;
450 cache->logout(entity, *nameid, &indexes, expires, application, sessions);
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 (session_id && strcmp(sit->c_str(), session_id))
456 cache->remove(sit->c_str(), application);
458 catch (exception& ex) {
459 m_log.error("error while logging out matching sessions: %s", ex.what());
461 logoutRequest->getID(),
462 StatusCode::RESPONDER, NULL, ex.what(),
464 policy.getIssuerMetadata(),
467 m_decoder->isUserAgentPresent()
471 if (m_decoder->isUserAgentPresent()) {
472 // Pass control to the first front channel notification point, if any.
473 map<string,string> parammap;
474 if (!relayState.empty())
475 parammap["RelayState"] = relayState;
476 auto_ptr_char entityID(entity ? entity->getEntityID() : NULL);
478 parammap["entityID"] = entityID.get();
479 auto_ptr_char reqID(logoutRequest->getID());
481 parammap["ID"] = reqID.get();
482 pair<bool,long> result = notifyFrontChannel(application, request, response, ¶mmap);
487 // For back-channel requests, or if no front-channel notification is needed...
488 bool worked1 = false,worked2 = false;
489 worked1 = notifyBackChannel(application, request.getRequestURL(), sessions, false);
491 // One last session to yoink...
493 cache->remove(session_id, application);
496 catch (exception& ex) {
497 m_log.error("error removing active session (%s): %s", session_id, ex.what());
501 pair<string,const char*> shib_cookie=application.getCookieNameProps("_shibsession_");
502 response.setCookie(shib_cookie.first.c_str(), shib_cookie.second);
506 logoutRequest->getID(),
507 (worked1 && worked2) ? StatusCode::SUCCESS : StatusCode::RESPONDER,
508 (worked1 && worked2) ? NULL : StatusCode::PARTIAL_LOGOUT,
511 policy.getIssuerMetadata(),
514 m_decoder->isUserAgentPresent()
518 // A LogoutResponse completes an SP-initiated logout sequence.
519 const LogoutResponse* logoutResponse = dynamic_cast<LogoutResponse*>(msg.get());
520 if (logoutResponse) {
521 if (!policy.isAuthenticated()) {
522 SecurityPolicyException ex("Security of LogoutResponse not established.");
523 if (policy.getIssuerMetadata())
524 annotateException(&ex, policy.getIssuerMetadata()); // throws it
527 checkError(logoutResponse, policy.getIssuerMetadata()); // throws if Status doesn't look good...
529 // Return template for completion of global logout, or redirect to homeURL.
530 return sendLogoutPage(application, response, false, "Global logout completed.");
533 FatalProfileException ex("Incoming message was not a samlp:LogoutRequest or samlp:LogoutResponse.");
534 if (policy.getIssuerMetadata())
535 annotateException(&ex, policy.getIssuerMetadata()); // throws it
537 return make_pair(false,0L); // never happen, satisfies compiler
539 throw ConfigurationException("Cannot process logout message using lite version of shibsp library.");
545 bool SAML2Logout::stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const
547 if (!XMLString::equals(n1.getName(), n2.getName()))
550 const XMLCh* s1 = n1.getFormat();
551 const XMLCh* s2 = n2.getFormat();
553 s1 = saml2::NameID::UNSPECIFIED;
555 s2 = saml2::NameID::UNSPECIFIED;
556 if (!XMLString::equals(s1,s2))
559 s1 = n1.getNameQualifier();
560 s2 = n2.getNameQualifier();
565 if (!XMLString::equals(s1,s2))
568 s1 = n1.getSPNameQualifier();
569 s2 = n2.getSPNameQualifier();
574 if (!XMLString::equals(s1,s2))
580 pair<bool,long> SAML2Logout::sendResponse(
581 const XMLCh* requestID,
583 const XMLCh* subcode,
585 const char* relayState,
586 const RoleDescriptor* role,
587 const Application& application,
588 HTTPResponse& httpResponse,
592 // Get endpoint and encoder to use.
593 const EndpointType* ep = NULL;
594 const MessageEncoder* encoder = NULL;
596 const IDPSSODescriptor* idp = dynamic_cast<const IDPSSODescriptor*>(role);
597 for (vector<const XMLCh*>::const_iterator b = m_bindings.begin(); idp && b!=m_bindings.end(); ++b) {
598 if (ep=EndpointManager<SingleLogoutService>(idp->getSingleLogoutServices()).getByBinding(*b)) {
599 map<const XMLCh*,MessageEncoder*>::const_iterator enc = m_encoders.find(*b);
600 if (enc!=m_encoders.end())
601 encoder = enc->second;
605 if (!ep || !encoder) {
606 auto_ptr_char id(dynamic_cast<EntityDescriptor*>(role->getParent())->getEntityID());
607 m_log.error("unable to locate compatible SLO service for provider (%s)", id.get());
608 MetadataException ex("Unable to locate endpoint at IdP ($entityID) to send LogoutResponse.");
609 annotateException(&ex, role); // throws it
613 encoder = m_encoders.begin()->second;
617 auto_ptr<LogoutResponse> logout(LogoutResponseBuilder::buildLogoutResponse());
618 logout->setInResponseTo(requestID);
620 const XMLCh* loc = ep->getResponseLocation();
622 loc = ep->getLocation();
623 logout->setDestination(loc);
625 Issuer* issuer = IssuerBuilder::buildIssuer();
626 logout->setIssuer(issuer);
627 issuer->setName(application.getXMLString("entityID").second);
628 fillStatus(*logout.get(), code, subcode, msg);
630 auto_ptr_char dest(logout->getDestination());
632 long ret = sendMessage(*encoder, logout.get(), relayState, dest.get(), role, application, httpResponse);
633 logout.release(); // freed by encoder
634 return make_pair(true,ret);