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 MetadataProvider* m = application.getMetadataProvider();
297 Locker metadataLocker(m);
298 MetadataProvider::Criteria mc(request.getParameter("entityID"), &IDPSSODescriptor::ELEMENT_QNAME, samlconstants::SAML20P_NS);
299 pair<const EntityDescriptor*,const RoleDescriptor*> entity = m->getEntityDescriptor(mc);
301 throw MetadataException(
302 "Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", request.getParameter("entityID"))
305 else if (!entity.second) {
306 throw MetadataException(
307 "Unable to locate SAML 2.0 IdP role for identity provider ($entityID).",
308 namedparams(1, "entityID", request.getParameter("entityID"))
312 auto_ptr_XMLCh reqid(request.getParameter("ID"));
313 if (worked1 && worked2) {
314 // Successful LogoutResponse. Has to be front-channel or we couldn't be here.
316 reqid.get(), StatusCode::SUCCESS, NULL, NULL, request.getParameter("RelayState"), entity.second, application, response, true
322 StatusCode::RESPONDER, NULL, "Unable to fully destroy principal's session.",
323 request.getParameter("RelayState"),
331 // If we get here, it's an external protocol message to decode.
333 // Locate policy key.
334 pair<bool,const char*> policyId = getString("policyId", m_configNS.get()); // namespace-qualified if inside handler element
336 policyId = application.getString("policyId"); // unqualified in Application(s) element
338 // Access policy properties.
339 const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId.second);
340 pair<bool,bool> validate = settings->getBool("validate");
342 // Lock metadata for use by policy.
343 Locker metadataLocker(application.getMetadataProvider());
345 // Create the policy.
346 shibsp::SecurityPolicy policy(application, &m_role, validate.first && validate.second);
348 // Decode the message.
350 auto_ptr<XMLObject> msg(m_decoder->decode(relayState, request, policy));
351 const LogoutRequest* logoutRequest = dynamic_cast<LogoutRequest*>(msg.get());
353 if (!policy.isAuthenticated())
354 throw SecurityPolicyException("Security of LogoutRequest not established.");
356 // Message from IdP to logout one or more sessions.
358 // If this is front-channel, we have to have a session_id to use already.
359 if (m_decoder->isUserAgentPresent() && !session_id) {
360 m_log.error("no active session");
362 logoutRequest->getID(),
363 StatusCode::REQUESTER, StatusCode::UNKNOWN_PRINCIPAL, "No active session found in request.",
365 policy.getIssuerMetadata(),
372 bool ownedName = false;
373 NameID* nameid = logoutRequest->getNameID();
375 // Check for EncryptedID.
376 EncryptedID* encname = logoutRequest->getEncryptedID();
378 CredentialResolver* cr=application.getCredentialResolver();
380 m_log.warn("found encrypted NameID, but no decryption credential was available");
382 Locker credlocker(cr);
383 auto_ptr<MetadataCredentialCriteria> mcc(
384 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
387 auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr,application.getXMLString("entityID").second,mcc.get()));
388 nameid = dynamic_cast<NameID*>(decryptedID.get());
391 decryptedID.release();
394 catch (exception& ex) {
395 m_log.error(ex.what());
401 // No NameID, so must respond with an error.
402 m_log.error("NameID not found in request");
404 logoutRequest->getID(),
405 StatusCode::REQUESTER, StatusCode::UNKNOWN_PRINCIPAL, "NameID not found in request.",
407 policy.getIssuerMetadata(),
410 m_decoder->isUserAgentPresent()
414 auto_ptr<NameID> namewrapper(ownedName ? nameid : NULL);
416 // Suck indexes out of the request for next steps.
418 EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL;
419 const vector<SessionIndex*> sindexes = logoutRequest->getSessionIndexs();
420 for (vector<SessionIndex*>::const_iterator i = sindexes.begin(); i != sindexes.end(); ++i) {
421 auto_ptr_char sindex((*i)->getSessionIndex());
422 indexes.insert(sindex.get());
425 // For a front-channel LogoutRequest, we have to match the information in the request
426 // against the current session.
428 if (!cache->matches(session_id, entity, *nameid, &indexes, application)) {
430 logoutRequest->getID(),
431 StatusCode::REQUESTER, StatusCode::REQUEST_DENIED, "Active sessions did not match logout request.",
433 policy.getIssuerMetadata(),
442 // Now we perform "logout" by finding the matching sessions.
443 vector<string> sessions;
445 time_t expires = logoutRequest->getNotOnOrAfter() ? logoutRequest->getNotOnOrAfterEpoch() : 0;
446 cache->logout(entity, *nameid, &indexes, expires, application, sessions);
448 // Now we actually terminate everything except for the active session,
449 // if this is front-channel, for notification purposes.
450 for (vector<string>::const_iterator sit = sessions.begin(); sit != sessions.end(); ++sit)
451 if (session_id && strcmp(sit->c_str(), session_id))
452 cache->remove(sit->c_str(), application);
454 catch (exception& ex) {
455 m_log.error("error while logging out matching sessions: %s", ex.what());
457 logoutRequest->getID(),
458 StatusCode::RESPONDER, NULL, ex.what(),
460 policy.getIssuerMetadata(),
463 m_decoder->isUserAgentPresent()
467 if (m_decoder->isUserAgentPresent()) {
468 // Pass control to the first front channel notification point, if any.
469 map<string,string> parammap;
470 if (!relayState.empty())
471 parammap["RelayState"] = relayState;
472 auto_ptr_char entityID(entity ? entity->getEntityID() : NULL);
474 parammap["entityID"] = entityID.get();
475 auto_ptr_char reqID(logoutRequest->getID());
477 parammap["ID"] = reqID.get();
478 pair<bool,long> result = notifyFrontChannel(application, request, response, ¶mmap);
483 // For back-channel requests, or if no front-channel notification is needed...
484 bool worked1 = false,worked2 = false;
485 worked1 = notifyBackChannel(application, request.getRequestURL(), sessions, false);
487 // One last session to yoink...
489 cache->remove(session_id, application);
492 catch (exception& ex) {
493 m_log.error("error removing active session (%s): %s", session_id, ex.what());
497 pair<string,const char*> shib_cookie=application.getCookieNameProps("_shibsession_");
498 response.setCookie(shib_cookie.first.c_str(), shib_cookie.second);
502 logoutRequest->getID(),
503 (worked1 && worked2) ? StatusCode::SUCCESS : StatusCode::RESPONDER,
504 (worked1 && worked2) ? NULL : StatusCode::PARTIAL_LOGOUT,
507 policy.getIssuerMetadata(),
510 m_decoder->isUserAgentPresent()
514 // A LogoutResponse completes an SP-initiated logout sequence.
515 const LogoutResponse* logoutResponse = dynamic_cast<LogoutResponse*>(msg.get());
516 if (logoutResponse) {
517 if (!policy.isAuthenticated()) {
518 SecurityPolicyException ex("Security of LogoutResponse not established.");
519 if (policy.getIssuerMetadata())
520 annotateException(&ex, policy.getIssuerMetadata()); // throws it
523 checkError(logoutResponse, policy.getIssuerMetadata()); // throws if Status doesn't look good...
525 // Return template for completion of global logout, or redirect to homeURL.
526 return sendLogoutPage(application, response, false, "Global logout completed.");
529 FatalProfileException ex("Incoming message was not a samlp:LogoutRequest or samlp:LogoutResponse.");
530 if (policy.getIssuerMetadata())
531 annotateException(&ex, policy.getIssuerMetadata()); // throws it
533 return make_pair(false,0); // never happen, satisfies compiler
535 throw ConfigurationException("Cannot process logout message using lite version of shibsp library.");
541 bool SAML2Logout::stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const
543 if (!XMLString::equals(n1.getName(), n2.getName()))
546 const XMLCh* s1 = n1.getFormat();
547 const XMLCh* s2 = n2.getFormat();
549 s1 = saml2::NameID::UNSPECIFIED;
551 s2 = saml2::NameID::UNSPECIFIED;
552 if (!XMLString::equals(s1,s2))
555 s1 = n1.getNameQualifier();
556 s2 = n2.getNameQualifier();
561 if (!XMLString::equals(s1,s2))
564 s1 = n1.getSPNameQualifier();
565 s2 = n2.getSPNameQualifier();
570 if (!XMLString::equals(s1,s2))
576 pair<bool,long> SAML2Logout::sendResponse(
577 const XMLCh* requestID,
579 const XMLCh* subcode,
581 const char* relayState,
582 const RoleDescriptor* role,
583 const Application& application,
584 HTTPResponse& httpResponse,
588 // Get endpoint and encoder to use.
589 const EndpointType* ep = NULL;
590 const MessageEncoder* encoder = NULL;
592 const IDPSSODescriptor* idp = dynamic_cast<const IDPSSODescriptor*>(role);
593 for (vector<const XMLCh*>::const_iterator b = m_bindings.begin(); idp && b!=m_bindings.end(); ++b) {
594 if (ep=EndpointManager<SingleLogoutService>(idp->getSingleLogoutServices()).getByBinding(*b)) {
595 map<const XMLCh*,MessageEncoder*>::const_iterator enc = m_encoders.find(*b);
596 if (enc!=m_encoders.end())
597 encoder = enc->second;
601 if (!ep || !encoder) {
602 auto_ptr_char id(dynamic_cast<EntityDescriptor*>(role->getParent())->getEntityID());
603 m_log.error("unable to locate compatible SLO service for provider (%s)", id.get());
604 MetadataException ex("Unable to locate endpoint at IdP ($entityID) to send LogoutResponse.");
605 annotateException(&ex, role); // throws it
609 encoder = m_encoders.begin()->second;
613 auto_ptr<LogoutResponse> logout(LogoutResponseBuilder::buildLogoutResponse());
614 logout->setInResponseTo(requestID);
616 const XMLCh* loc = ep->getResponseLocation();
618 loc = ep->getLocation();
619 logout->setDestination(loc);
621 Issuer* issuer = IssuerBuilder::buildIssuer();
622 logout->setIssuer(issuer);
623 issuer->setName(application.getXMLString("entityID").second);
624 fillStatus(*logout.get(), code, subcode, msg);
626 auto_ptr_char dest(logout->getDestination());
628 long ret = sendMessage(*encoder, logout.get(), relayState, dest.get(), role, application, httpResponse);
629 logout.release(); // freed by encoder
630 return make_pair(true,ret);