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 pair<bool,long> doRequest(
77 const Application& application, const char* session_id, const HTTPRequest& httpRequest, HTTPResponse& httpResponse
81 bool stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const;
83 pair<bool,long> sendResponse(
84 const XMLCh* requestID,
88 const char* relayState,
89 const RoleDescriptor* role,
90 const Application& application,
91 HTTPResponse& httpResponse,
96 MessageDecoder* m_decoder;
98 vector<const XMLCh*> m_bindings;
99 map<const XMLCh*,MessageEncoder*> m_encoders;
103 #if defined (_MSC_VER)
104 #pragma warning( pop )
107 Handler* SHIBSP_DLLLOCAL SAML2LogoutFactory(const pair<const DOMElement*,const char*>& p)
109 return new SAML2Logout(p.first, p.second);
113 SAML2Logout::SAML2Logout(const DOMElement* e, const char* appId)
114 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".Logout.SAML2"))
116 ,m_role(samlconstants::SAML20MD_NS, IDPSSODescriptor::LOCAL_NAME), m_decoder(NULL), m_outgoing(NULL)
121 m_preserve.push_back("ID");
122 m_preserve.push_back("entityID");
123 m_preserve.push_back("RelayState");
125 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
126 SAMLConfig& conf = SAMLConfig::getConfig();
128 // Handle incoming binding.
129 m_decoder = conf.MessageDecoderManager.newPlugin(getString("Binding").second,make_pair(e,shibspconstants::SHIB2SPCONFIG_NS));
130 m_decoder->setArtifactResolver(SPConfig::getConfig().getArtifactResolver());
132 if (m_decoder->isUserAgentPresent()) {
133 // Handle front-channel binding setup.
134 pair<bool,const XMLCh*> outgoing = getXMLString("outgoingBindings", m_configNS.get());
135 if (outgoing.first) {
136 m_outgoing = XMLString::replicate(outgoing.second);
137 XMLString::trim(m_outgoing);
140 // No override, so we'll install a default binding precedence.
141 string prec = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
142 samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
143 m_outgoing = XMLString::transcode(prec.c_str());
147 XMLCh* start = m_outgoing;
148 while (start && *start) {
149 pos = XMLString::indexOf(start,chSpace);
151 *(start + pos)=chNull;
152 m_bindings.push_back(start);
154 auto_ptr_char b(start);
155 MessageEncoder * encoder = conf.MessageEncoderManager.newPlugin(b.get(),make_pair(e,shibspconstants::SHIB2SPCONFIG_NS));
156 m_encoders[start] = encoder;
157 m_log.debug("supporting outgoing front-channel binding (%s)", b.get());
159 catch (exception& ex) {
160 m_log.error("error building MessageEncoder: %s", ex.what());
163 start = start + pos + 1;
169 MessageEncoder* encoder = conf.MessageEncoderManager.newPlugin(
170 getString("Binding").second,make_pair(e,shibspconstants::SHIB2SPCONFIG_NS)
172 m_encoders.insert(pair<const XMLCh*,MessageEncoder*>(NULL, encoder));
177 string address(appId);
178 address += getString("Location").second;
179 setAddress(address.c_str());
182 pair<bool,long> SAML2Logout::run(SPRequest& request, bool isHandler) const
184 // Defer to base class for front-channel loop first.
185 // This won't initiate the loop, only continue/end it.
186 pair<bool,long> ret = LogoutHandler::run(request, isHandler);
190 // Get the session_id in case this is a front-channel LogoutRequest.
191 pair<string,const char*> shib_cookie = request.getApplication().getCookieNameProps("_shibsession_");
192 const char* session_id = request.getCookie(shib_cookie.first.c_str());
194 SPConfig& conf = SPConfig::getConfig();
195 if (conf.isEnabled(SPConfig::OutOfProcess)) {
196 // When out of process, we run natively and directly process the message.
197 return doRequest(request.getApplication(), session_id, request, request);
200 // When not out of process, we remote all the message processing.
201 DDF out,in = wrap(request, NULL, true);
202 DDFJanitor jin(in), jout(out);
204 in.addmember("session_id").string(session_id);
205 out=request.getServiceProvider().getListenerService()->send(in);
206 return unwrap(request, out);
210 void SAML2Logout::receive(DDF& in, ostream& out)
213 const char* aid=in["application_id"].string();
214 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
216 // Something's horribly wrong.
217 m_log.error("couldn't find application (%s) for logout", aid ? aid : "(missing)");
218 throw ConfigurationException("Unable to locate application for logout, deleted?");
221 // Unpack the request.
223 DDFJanitor jout(ret);
224 auto_ptr<HTTPRequest> req(getRequest(in));
225 auto_ptr<HTTPResponse> resp(getResponse(ret));
227 // Since we're remoted, the result should either be a throw, which we pass on,
228 // a false/0 return, which we just return as an empty structure, or a response/redirect,
229 // which we capture in the facade and send back.
230 doRequest(*app, in["session_id"].string(), *req.get(), *resp.get());
234 pair<bool,long> SAML2Logout::doRequest(
235 const Application& application, const char* session_id, const HTTPRequest& request, HTTPResponse& response
239 SessionCache* cache = application.getServiceProvider().getSessionCache();
240 if (!strcmp(request.getMethod(),"GET") && request.getParameter("notifying")) {
242 // This is returning from a front-channel notification, so we have to do the back-channel and then
243 // respond. To do that, we need state from the original request.
244 if (!request.getParameter("entityID")) {
246 cache->remove(session_id, application);
248 pair<string,const char*> shib_cookie=application.getCookieNameProps("_shibsession_");
249 response.setCookie(shib_cookie.first.c_str(), shib_cookie.second);
251 throw FatalProfileException("Application notification loop did not return entityID for LogoutResponse.");
254 // Best effort on back channel and to remove the user agent's session.
255 bool worked1 = false,worked2 = false;
257 vector<string> sessions(1,session_id);
258 worked1 = notifyBackChannel(application, request.getRequestURL(), sessions, false);
260 cache->remove(session_id, application);
263 catch (exception& ex) {
264 m_log.error("error removing session (%s): %s", session_id, ex.what());
268 pair<string,const char*> shib_cookie=application.getCookieNameProps("_shibsession_");
269 response.setCookie(shib_cookie.first.c_str(), shib_cookie.second);
272 worked1 = worked2 = true;
275 // We need metadata to issue a response.
276 Locker metadataLocker(application.getMetadataProvider());
277 const EntityDescriptor* entity = application.getMetadataProvider()->getEntityDescriptor(request.getParameter("entityID"));
279 throw MetadataException(
280 "Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", request.getParameter("entityID"))
283 const IDPSSODescriptor* idp = entity->getIDPSSODescriptor(samlconstants::SAML20P_NS);
285 throw MetadataException(
286 "Unable to locate SAML 2.0 IdP role for identity provider ($entityID).",
287 namedparams(1, "entityID", request.getParameter("entityID"))
291 auto_ptr_XMLCh reqid(request.getParameter("ID"));
292 if (worked1 && worked2) {
293 // Successful LogoutResponse. Has to be front-channel or we couldn't be here.
295 reqid.get(), StatusCode::SUCCESS, NULL, NULL, request.getParameter("RelayState"), idp, application, response, true
301 StatusCode::RESPONDER, NULL, "Unable to fully destroy principal's session.",
302 request.getParameter("RelayState"),
310 // If we get here, it's an external protocol message to decode.
312 // Locate policy key.
313 pair<bool,const char*> policyId = getString("policyId", m_configNS.get()); // namespace-qualified if inside handler element
315 policyId = application.getString("policyId"); // unqualified in Application(s) element
317 // Access policy properties.
318 const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId.second);
319 pair<bool,bool> validate = settings->getBool("validate");
321 // Lock metadata for use by policy.
322 Locker metadataLocker(application.getMetadataProvider());
324 // Create the policy.
325 shibsp::SecurityPolicy policy(application, &m_role, validate.first && validate.second);
327 // Decode the message.
329 auto_ptr<XMLObject> msg(m_decoder->decode(relayState, request, policy));
330 const LogoutRequest* logoutRequest = dynamic_cast<LogoutRequest*>(msg.get());
332 if (!policy.isSecure())
333 throw SecurityPolicyException("Security of LogoutRequest not established.");
335 // Message from IdP to logout one or more sessions.
337 // If this is front-channel, we have to have a session_id to use already.
338 if (m_decoder->isUserAgentPresent() && !session_id) {
339 m_log.error("no active session");
341 logoutRequest->getID(),
342 StatusCode::REQUESTER, StatusCode::UNKNOWN_PRINCIPAL, "No active session found in request.",
344 policy.getIssuerMetadata(),
351 bool ownedName = false;
352 NameID* nameid = logoutRequest->getNameID();
354 // Check for EncryptedID.
355 EncryptedID* encname = logoutRequest->getEncryptedID();
357 CredentialResolver* cr=application.getCredentialResolver();
359 m_log.warn("found encrypted NameID, but no decryption credential was available");
361 Locker credlocker(cr);
362 auto_ptr<MetadataCredentialCriteria> mcc(
363 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
366 auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr,application.getXMLString("entityID").second,mcc.get()));
367 nameid = dynamic_cast<NameID*>(decryptedID.get());
370 decryptedID.release();
373 catch (exception& ex) {
374 m_log.error(ex.what());
380 // No NameID, so must respond with an error.
381 m_log.error("NameID not found in request");
383 logoutRequest->getID(),
384 StatusCode::REQUESTER, StatusCode::UNKNOWN_PRINCIPAL, "NameID not found in request.",
386 policy.getIssuerMetadata(),
389 m_decoder->isUserAgentPresent()
393 // Suck indexes out of the request for next steps.
395 EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL;
396 const vector<SessionIndex*> sindexes = logoutRequest->getSessionIndexs();
397 for (vector<SessionIndex*>::const_iterator i = sindexes.begin(); i != sindexes.end(); ++i) {
398 auto_ptr_char sindex((*i)->getSessionIndex());
399 indexes.insert(sindex.get());
402 // For a front-channel LogoutRequest, we have to match the information in the request
403 // against the current session.
405 if (!cache->matches(session_id, entity, *nameid, &indexes, application)) {
407 logoutRequest->getID(),
408 StatusCode::REQUESTER, StatusCode::REQUEST_DENIED, "Active sessions did not match logout request.",
410 policy.getIssuerMetadata(),
419 // Now we perform "logout" by finding the matching sessions.
420 vector<string> sessions;
422 time_t expires = logoutRequest->getNotOnOrAfter() ? logoutRequest->getNotOnOrAfterEpoch() : 0;
423 cache->logout(entity, *nameid, &indexes, expires, application, sessions);
425 // Now we actually terminate everything except for the active session,
426 // if this is front-channel, for notification purposes.
427 for (vector<string>::const_iterator sit = sessions.begin(); sit != sessions.end(); ++sit)
428 if (session_id && strcmp(sit->c_str(), session_id))
429 cache->remove(sit->c_str(), application);
431 catch (exception& ex) {
432 m_log.error("error while logging out matching sessions: %s", ex.what());
434 logoutRequest->getID(),
435 StatusCode::RESPONDER, NULL, ex.what(),
437 policy.getIssuerMetadata(),
440 m_decoder->isUserAgentPresent()
444 if (m_decoder->isUserAgentPresent()) {
445 // Pass control to the first front channel notification point, if any.
446 map<string,string> parammap;
447 if (!relayState.empty())
448 parammap["RelayState"] = relayState;
449 auto_ptr_char entityID(entity ? entity->getEntityID() : NULL);
451 parammap["entityID"] = entityID.get();
452 auto_ptr_char reqID(logoutRequest->getID());
454 parammap["ID"] = reqID.get();
455 pair<bool,long> result = notifyFrontChannel(application, request, response, ¶mmap);
460 // For back-channel requests, or if no front-channel notification is needed...
461 bool worked1 = false,worked2 = false;
462 worked1 = notifyBackChannel(application, request.getRequestURL(), sessions, false);
464 // One last session to yoink...
466 cache->remove(session_id, application);
469 catch (exception& ex) {
470 m_log.error("error removing active session (%s): %s", session_id, ex.what());
474 pair<string,const char*> shib_cookie=application.getCookieNameProps("_shibsession_");
475 response.setCookie(shib_cookie.first.c_str(), shib_cookie.second);
479 logoutRequest->getID(),
480 (worked1 && worked2) ? StatusCode::SUCCESS : StatusCode::RESPONDER,
481 (worked1 && worked2) ? NULL : StatusCode::PARTIAL_LOGOUT,
484 policy.getIssuerMetadata(),
487 m_decoder->isUserAgentPresent()
491 // A LogoutResponse completes an SP-initiated logout sequence.
492 const LogoutResponse* logoutResponse = dynamic_cast<LogoutResponse*>(msg.get());
493 if (logoutResponse) {
494 if (!policy.isSecure()) {
495 SecurityPolicyException ex("Security of LogoutResponse not established.");
496 if (policy.getIssuerMetadata())
497 annotateException(&ex, policy.getIssuerMetadata()); // throws it
500 checkError(logoutResponse, policy.getIssuerMetadata()); // throws if Status doesn't look good...
502 // Return template for completion of global logout, or redirect to homeURL.
503 return sendLogoutPage(application, response, false, "Global logout completed.");
506 FatalProfileException ex("Incoming message was not a samlp:LogoutRequest or samlp:LogoutResponse.");
507 if (policy.getIssuerMetadata())
508 annotateException(&ex, policy.getIssuerMetadata()); // throws it
510 return make_pair(false,0); // never happen, satisfies compiler
512 throw ConfigurationException("Cannot process logout message using lite version of shibsp library.");
518 bool SAML2Logout::stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const
520 if (!XMLString::equals(n1.getName(), n2.getName()))
523 const XMLCh* s1 = n1.getFormat();
524 const XMLCh* s2 = n2.getFormat();
526 s1 = saml2::NameID::UNSPECIFIED;
528 s2 = saml2::NameID::UNSPECIFIED;
529 if (!XMLString::equals(s1,s2))
532 s1 = n1.getNameQualifier();
533 s2 = n2.getNameQualifier();
538 if (!XMLString::equals(s1,s2))
541 s1 = n1.getSPNameQualifier();
542 s2 = n2.getSPNameQualifier();
547 if (!XMLString::equals(s1,s2))
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 logout->setDestination(ep->getLocation());
594 Issuer* issuer = IssuerBuilder::buildIssuer();
595 logout->setIssuer(issuer);
596 issuer->setName(application.getXMLString("entityID").second);
597 fillStatus(*logout.get(), code, subcode, msg);
599 auto_ptr_char dest(ep ? ep->getLocation() : NULL);
601 long ret = sendMessage(*encoder, logout.get(), relayState, dest.get(), role, application, httpResponse, "signResponses");
602 logout.release(); // freed by encoder
603 return make_pair(true,ret);