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);
92 pair<bool,long> doRequest(
93 const Application& application, const char* session_id, const HTTPRequest& httpRequest, HTTPResponse& httpResponse
97 bool stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const;
99 pair<bool,long> sendResponse(
100 const XMLCh* requestID,
102 const XMLCh* subcode,
104 const char* relayState,
105 const RoleDescriptor* role,
106 const Application& application,
107 HTTPResponse& httpResponse,
112 MessageDecoder* m_decoder;
114 vector<const XMLCh*> m_bindings;
115 map<const XMLCh*,MessageEncoder*> m_encoders;
119 #if defined (_MSC_VER)
120 #pragma warning( pop )
123 Handler* SHIBSP_DLLLOCAL SAML2LogoutFactory(const pair<const DOMElement*,const char*>& p)
125 return new SAML2Logout(p.first, p.second);
129 SAML2Logout::SAML2Logout(const DOMElement* e, const char* appId)
130 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".Logout.SAML2"))
132 ,m_role(samlconstants::SAML20MD_NS, IDPSSODescriptor::LOCAL_NAME), m_decoder(NULL), m_outgoing(NULL)
137 m_preserve.push_back("ID");
138 m_preserve.push_back("entityID");
139 m_preserve.push_back("RelayState");
141 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
142 SAMLConfig& conf = SAMLConfig::getConfig();
144 // Handle incoming binding.
145 m_decoder = conf.MessageDecoderManager.newPlugin(getString("Binding").second,make_pair(e,shibspconstants::SHIB2SPCONFIG_NS));
146 m_decoder->setArtifactResolver(SPConfig::getConfig().getArtifactResolver());
148 if (m_decoder->isUserAgentPresent()) {
149 // Handle front-channel binding setup.
150 pair<bool,const XMLCh*> outgoing = getXMLString("outgoingBindings", m_configNS.get());
151 if (outgoing.first) {
152 m_outgoing = XMLString::replicate(outgoing.second);
153 XMLString::trim(m_outgoing);
156 // No override, so we'll install a default binding precedence.
157 string prec = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
158 samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
159 m_outgoing = XMLString::transcode(prec.c_str());
163 XMLCh* start = m_outgoing;
164 while (start && *start) {
165 pos = XMLString::indexOf(start,chSpace);
167 *(start + pos)=chNull;
168 m_bindings.push_back(start);
170 auto_ptr_char b(start);
171 MessageEncoder * encoder = conf.MessageEncoderManager.newPlugin(b.get(),make_pair(e,shibspconstants::SHIB2SPCONFIG_NS));
172 m_encoders[start] = encoder;
173 m_log.debug("supporting outgoing front-channel binding (%s)", b.get());
175 catch (exception& ex) {
176 m_log.error("error building MessageEncoder: %s", ex.what());
179 start = start + pos + 1;
185 MessageEncoder* encoder = conf.MessageEncoderManager.newPlugin(
186 getString("Binding").second,make_pair(e,shibspconstants::SHIB2SPCONFIG_NS)
188 m_encoders.insert(pair<const XMLCh*,MessageEncoder*>(NULL, encoder));
193 string address(appId);
194 address += getString("Location").second;
195 setAddress(address.c_str());
198 pair<bool,long> SAML2Logout::run(SPRequest& request, bool isHandler) const
200 // Defer to base class for front-channel loop first.
201 // This won't initiate the loop, only continue/end it.
202 pair<bool,long> ret = LogoutHandler::run(request, isHandler);
206 // Get the session_id in case this is a front-channel LogoutRequest.
207 pair<string,const char*> shib_cookie = request.getApplication().getCookieNameProps("_shibsession_");
208 const char* session_id = request.getCookie(shib_cookie.first.c_str());
210 SPConfig& conf = SPConfig::getConfig();
211 if (conf.isEnabled(SPConfig::OutOfProcess)) {
212 // When out of process, we run natively and directly process the message.
213 return doRequest(request.getApplication(), session_id, request, request);
216 // When not out of process, we remote all the message processing.
217 DDF out,in = wrap(request, NULL, true);
218 DDFJanitor jin(in), jout(out);
220 in.addmember("session_id").string(session_id);
221 out=request.getServiceProvider().getListenerService()->send(in);
222 return unwrap(request, out);
226 void SAML2Logout::receive(DDF& in, ostream& out)
229 const char* aid=in["application_id"].string();
230 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
232 // Something's horribly wrong.
233 m_log.error("couldn't find application (%s) for logout", aid ? aid : "(missing)");
234 throw ConfigurationException("Unable to locate application for logout, deleted?");
237 // Unpack the request.
239 DDFJanitor jout(ret);
240 auto_ptr<HTTPRequest> req(getRequest(in));
241 auto_ptr<HTTPResponse> resp(getResponse(ret));
243 // Since we're remoted, the result should either be a throw, which we pass on,
244 // a false/0 return, which we just return as an empty structure, or a response/redirect,
245 // which we capture in the facade and send back.
246 doRequest(*app, in["session_id"].string(), *req.get(), *resp.get());
250 pair<bool,long> SAML2Logout::doRequest(
251 const Application& application, const char* session_id, const HTTPRequest& request, HTTPResponse& response
255 SessionCache* cache = application.getServiceProvider().getSessionCache();
256 if (!strcmp(request.getMethod(),"GET") && request.getParameter("notifying")) {
258 // This is returning from a front-channel notification, so we have to do the back-channel and then
259 // respond. To do that, we need state from the original request.
260 if (!request.getParameter("entityID")) {
262 cache->remove(session_id, application);
264 pair<string,const char*> shib_cookie=application.getCookieNameProps("_shibsession_");
265 response.setCookie(shib_cookie.first.c_str(), shib_cookie.second);
267 throw FatalProfileException("Application notification loop did not return entityID for LogoutResponse.");
270 // Best effort on back channel and to remove the user agent's session.
271 bool worked1 = false,worked2 = false;
273 vector<string> sessions(1,session_id);
274 worked1 = notifyBackChannel(application, request.getRequestURL(), sessions, false);
276 cache->remove(session_id, application);
279 catch (exception& ex) {
280 m_log.error("error removing session (%s): %s", session_id, ex.what());
284 pair<string,const char*> shib_cookie=application.getCookieNameProps("_shibsession_");
285 response.setCookie(shib_cookie.first.c_str(), shib_cookie.second);
288 worked1 = worked2 = true;
291 // We need metadata to issue a response.
292 Locker metadataLocker(application.getMetadataProvider());
293 const EntityDescriptor* entity = application.getMetadataProvider()->getEntityDescriptor(request.getParameter("entityID"));
295 throw MetadataException(
296 "Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", request.getParameter("entityID"))
299 const IDPSSODescriptor* idp = entity->getIDPSSODescriptor(samlconstants::SAML20P_NS);
301 throw MetadataException(
302 "Unable to locate SAML 2.0 IdP role for identity provider ($entityID).",
303 namedparams(1, "entityID", request.getParameter("entityID"))
307 auto_ptr_XMLCh reqid(request.getParameter("ID"));
308 if (worked1 && worked2) {
309 // Successful LogoutResponse. Has to be front-channel or we couldn't be here.
311 reqid.get(), StatusCode::SUCCESS, NULL, NULL, request.getParameter("RelayState"), idp, application, response, true
317 StatusCode::RESPONDER, NULL, "Unable to fully destroy principal's session.",
318 request.getParameter("RelayState"),
326 // If we get here, it's an external protocol message to decode.
328 // Locate policy key.
329 pair<bool,const char*> policyId = getString("policyId", m_configNS.get()); // namespace-qualified if inside handler element
331 policyId = application.getString("policyId"); // unqualified in Application(s) element
333 // Access policy properties.
334 const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId.second);
335 pair<bool,bool> validate = settings->getBool("validate");
337 // Lock metadata for use by policy.
338 Locker metadataLocker(application.getMetadataProvider());
340 // Create the policy.
341 shibsp::SecurityPolicy policy(application, &m_role, validate.first && validate.second);
343 // Decode the message.
345 auto_ptr<XMLObject> msg(m_decoder->decode(relayState, request, policy));
346 const LogoutRequest* logoutRequest = dynamic_cast<LogoutRequest*>(msg.get());
348 if (!policy.isAuthenticated())
349 throw SecurityPolicyException("Security of LogoutRequest not established.");
351 // Message from IdP to logout one or more sessions.
353 // If this is front-channel, we have to have a session_id to use already.
354 if (m_decoder->isUserAgentPresent() && !session_id) {
355 m_log.error("no active session");
357 logoutRequest->getID(),
358 StatusCode::REQUESTER, StatusCode::UNKNOWN_PRINCIPAL, "No active session found in request.",
360 policy.getIssuerMetadata(),
367 bool ownedName = false;
368 NameID* nameid = logoutRequest->getNameID();
370 // Check for EncryptedID.
371 EncryptedID* encname = logoutRequest->getEncryptedID();
373 CredentialResolver* cr=application.getCredentialResolver();
375 m_log.warn("found encrypted NameID, but no decryption credential was available");
377 Locker credlocker(cr);
378 auto_ptr<MetadataCredentialCriteria> mcc(
379 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
382 auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr,application.getXMLString("entityID").second,mcc.get()));
383 nameid = dynamic_cast<NameID*>(decryptedID.get());
386 decryptedID.release();
389 catch (exception& ex) {
390 m_log.error(ex.what());
396 // No NameID, so must respond with an error.
397 m_log.error("NameID not found in request");
399 logoutRequest->getID(),
400 StatusCode::REQUESTER, StatusCode::UNKNOWN_PRINCIPAL, "NameID not found in request.",
402 policy.getIssuerMetadata(),
405 m_decoder->isUserAgentPresent()
409 auto_ptr<NameID> namewrapper(ownedName ? nameid : NULL);
411 // Suck indexes out of the request for next steps.
413 EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL;
414 const vector<SessionIndex*> sindexes = logoutRequest->getSessionIndexs();
415 for (vector<SessionIndex*>::const_iterator i = sindexes.begin(); i != sindexes.end(); ++i) {
416 auto_ptr_char sindex((*i)->getSessionIndex());
417 indexes.insert(sindex.get());
420 // For a front-channel LogoutRequest, we have to match the information in the request
421 // against the current session.
423 if (!cache->matches(session_id, entity, *nameid, &indexes, application)) {
425 logoutRequest->getID(),
426 StatusCode::REQUESTER, StatusCode::REQUEST_DENIED, "Active sessions did not match logout request.",
428 policy.getIssuerMetadata(),
437 // Now we perform "logout" by finding the matching sessions.
438 vector<string> sessions;
440 time_t expires = logoutRequest->getNotOnOrAfter() ? logoutRequest->getNotOnOrAfterEpoch() : 0;
441 cache->logout(entity, *nameid, &indexes, expires, application, sessions);
443 // Now we actually terminate everything except for the active session,
444 // if this is front-channel, for notification purposes.
445 for (vector<string>::const_iterator sit = sessions.begin(); sit != sessions.end(); ++sit)
446 if (session_id && strcmp(sit->c_str(), session_id))
447 cache->remove(sit->c_str(), application);
449 catch (exception& ex) {
450 m_log.error("error while logging out matching sessions: %s", ex.what());
452 logoutRequest->getID(),
453 StatusCode::RESPONDER, NULL, ex.what(),
455 policy.getIssuerMetadata(),
458 m_decoder->isUserAgentPresent()
462 if (m_decoder->isUserAgentPresent()) {
463 // Pass control to the first front channel notification point, if any.
464 map<string,string> parammap;
465 if (!relayState.empty())
466 parammap["RelayState"] = relayState;
467 auto_ptr_char entityID(entity ? entity->getEntityID() : NULL);
469 parammap["entityID"] = entityID.get();
470 auto_ptr_char reqID(logoutRequest->getID());
472 parammap["ID"] = reqID.get();
473 pair<bool,long> result = notifyFrontChannel(application, request, response, ¶mmap);
478 // For back-channel requests, or if no front-channel notification is needed...
479 bool worked1 = false,worked2 = false;
480 worked1 = notifyBackChannel(application, request.getRequestURL(), sessions, false);
482 // One last session to yoink...
484 cache->remove(session_id, application);
487 catch (exception& ex) {
488 m_log.error("error removing active session (%s): %s", session_id, ex.what());
492 pair<string,const char*> shib_cookie=application.getCookieNameProps("_shibsession_");
493 response.setCookie(shib_cookie.first.c_str(), shib_cookie.second);
497 logoutRequest->getID(),
498 (worked1 && worked2) ? StatusCode::SUCCESS : StatusCode::RESPONDER,
499 (worked1 && worked2) ? NULL : StatusCode::PARTIAL_LOGOUT,
502 policy.getIssuerMetadata(),
505 m_decoder->isUserAgentPresent()
509 // A LogoutResponse completes an SP-initiated logout sequence.
510 const LogoutResponse* logoutResponse = dynamic_cast<LogoutResponse*>(msg.get());
511 if (logoutResponse) {
512 if (!policy.isAuthenticated()) {
513 SecurityPolicyException ex("Security of LogoutResponse not established.");
514 if (policy.getIssuerMetadata())
515 annotateException(&ex, policy.getIssuerMetadata()); // throws it
518 checkError(logoutResponse, policy.getIssuerMetadata()); // throws if Status doesn't look good...
520 // Return template for completion of global logout, or redirect to homeURL.
521 return sendLogoutPage(application, response, false, "Global logout completed.");
524 FatalProfileException ex("Incoming message was not a samlp:LogoutRequest or samlp:LogoutResponse.");
525 if (policy.getIssuerMetadata())
526 annotateException(&ex, policy.getIssuerMetadata()); // throws it
528 return make_pair(false,0); // never happen, satisfies compiler
530 throw ConfigurationException("Cannot process logout message using lite version of shibsp library.");
536 bool SAML2Logout::stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const
538 if (!XMLString::equals(n1.getName(), n2.getName()))
541 const XMLCh* s1 = n1.getFormat();
542 const XMLCh* s2 = n2.getFormat();
544 s1 = saml2::NameID::UNSPECIFIED;
546 s2 = saml2::NameID::UNSPECIFIED;
547 if (!XMLString::equals(s1,s2))
550 s1 = n1.getNameQualifier();
551 s2 = n2.getNameQualifier();
556 if (!XMLString::equals(s1,s2))
559 s1 = n1.getSPNameQualifier();
560 s2 = n2.getSPNameQualifier();
565 if (!XMLString::equals(s1,s2))
571 pair<bool,long> SAML2Logout::sendResponse(
572 const XMLCh* requestID,
574 const XMLCh* subcode,
576 const char* relayState,
577 const RoleDescriptor* role,
578 const Application& application,
579 HTTPResponse& httpResponse,
583 // Get endpoint and encoder to use.
584 const EndpointType* ep = NULL;
585 const MessageEncoder* encoder = NULL;
587 const IDPSSODescriptor* idp = dynamic_cast<const IDPSSODescriptor*>(role);
588 for (vector<const XMLCh*>::const_iterator b = m_bindings.begin(); idp && b!=m_bindings.end(); ++b) {
589 if (ep=EndpointManager<SingleLogoutService>(idp->getSingleLogoutServices()).getByBinding(*b)) {
590 map<const XMLCh*,MessageEncoder*>::const_iterator enc = m_encoders.find(*b);
591 if (enc!=m_encoders.end())
592 encoder = enc->second;
596 if (!ep || !encoder) {
597 auto_ptr_char id(dynamic_cast<EntityDescriptor*>(role->getParent())->getEntityID());
598 m_log.error("unable to locate compatible SLO service for provider (%s)", id.get());
599 MetadataException ex("Unable to locate endpoint at IdP ($entityID) to send LogoutResponse.");
600 annotateException(&ex, role); // throws it
604 encoder = m_encoders.begin()->second;
608 auto_ptr<LogoutResponse> logout(LogoutResponseBuilder::buildLogoutResponse());
609 logout->setInResponseTo(requestID);
611 const XMLCh* loc = ep->getResponseLocation();
613 loc = ep->getLocation();
614 logout->setDestination(loc);
616 Issuer* issuer = IssuerBuilder::buildIssuer();
617 logout->setIssuer(issuer);
618 issuer->setName(application.getXMLString("entityID").second);
619 fillStatus(*logout.get(), code, subcode, msg);
621 auto_ptr_char dest(logout->getDestination());
623 long ret = sendMessage(*encoder, logout.get(), relayState, dest.get(), role, application, httpResponse);
624 logout.release(); // freed by encoder
625 return make_pair(true,ret);