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;
49 using namespace log4cpp;
54 #if defined (_MSC_VER)
55 #pragma warning( push )
56 #pragma warning( disable : 4250 )
59 class SHIBSP_DLLLOCAL SAML2Logout : public AbstractHandler, public LogoutHandler
62 SAML2Logout(const DOMElement* e, const char* appId);
63 virtual ~SAML2Logout() {
65 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
67 XMLString::release(&m_outgoing);
68 for_each(m_encoders.begin(), m_encoders.end(), cleanup_pair<const XMLCh*,MessageEncoder>());
73 void receive(DDF& in, ostream& out);
74 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
77 pair<bool,long> doRequest(
78 const Application& application, const char* session_id, const HTTPRequest& httpRequest, HTTPResponse& httpResponse
82 bool stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const;
84 pair<bool,long> sendResponse(
85 const XMLCh* requestID,
89 const char* relayState,
90 const RoleDescriptor* role,
91 const Application& application,
92 HTTPResponse& httpResponse,
97 MessageDecoder* m_decoder;
99 vector<const XMLCh*> m_bindings;
100 map<const XMLCh*,MessageEncoder*> m_encoders;
104 #if defined (_MSC_VER)
105 #pragma warning( pop )
108 Handler* SHIBSP_DLLLOCAL SAML2LogoutFactory(const pair<const DOMElement*,const char*>& p)
110 return new SAML2Logout(p.first, p.second);
114 SAML2Logout::SAML2Logout(const DOMElement* e, const char* appId)
115 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SAML2Logout"))
117 ,m_role(samlconstants::SAML20MD_NS, IDPSSODescriptor::LOCAL_NAME), m_decoder(NULL), m_outgoing(NULL)
122 m_preserve.push_back("ID");
123 m_preserve.push_back("entityID");
124 m_preserve.push_back("RelayState");
126 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
127 SAMLConfig& conf = SAMLConfig::getConfig();
129 // Handle incoming binding.
130 m_decoder = conf.MessageDecoderManager.newPlugin(getString("Binding").second,make_pair(e,shibspconstants::SHIB2SPCONFIG_NS));
131 m_decoder->setArtifactResolver(SPConfig::getConfig().getArtifactResolver());
133 if (m_decoder->isUserAgentPresent()) {
134 // Handle front-channel binding setup.
135 pair<bool,const XMLCh*> outgoing = getXMLString("outgoingBindings", m_configNS.get());
136 if (outgoing.first) {
137 m_outgoing = XMLString::replicate(outgoing.second);
138 XMLString::trim(m_outgoing);
141 // No override, so we'll install a default binding precedence.
142 string prec = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
143 samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
144 m_outgoing = XMLString::transcode(prec.c_str());
148 XMLCh* start = m_outgoing;
149 while (start && *start) {
150 pos = XMLString::indexOf(start,chSpace);
152 *(start + pos)=chNull;
153 m_bindings.push_back(start);
155 auto_ptr_char b(start);
156 MessageEncoder * encoder = conf.MessageEncoderManager.newPlugin(b.get(),make_pair(e,shibspconstants::SHIB2SPCONFIG_NS));
157 m_encoders[start] = encoder;
158 m_log.debug("supporting outgoing front-channel binding (%s)", b.get());
160 catch (exception& ex) {
161 m_log.error("error building MessageEncoder: %s", ex.what());
164 start = start + pos + 1;
170 MessageEncoder* encoder = conf.MessageEncoderManager.newPlugin(
171 getString("Binding").second,make_pair(e,shibspconstants::SHIB2SPCONFIG_NS)
173 m_encoders.insert(pair<const XMLCh*,MessageEncoder*>(NULL, encoder));
178 string address(appId);
179 address += getString("Location").second;
180 setAddress(address.c_str());
183 pair<bool,long> SAML2Logout::run(SPRequest& request, bool isHandler) const
185 // Defer to base class for front-channel loop first.
186 // This won't initiate the loop, only continue/end it.
187 pair<bool,long> ret = LogoutHandler::run(request, isHandler);
191 // Get the session_id in case this is a front-channel LogoutRequest.
192 pair<string,const char*> shib_cookie = request.getApplication().getCookieNameProps("_shibsession_");
193 const char* session_id = request.getCookie(shib_cookie.first.c_str());
195 SPConfig& conf = SPConfig::getConfig();
196 if (conf.isEnabled(SPConfig::OutOfProcess)) {
197 // When out of process, we run natively and directly process the message.
198 return doRequest(request.getApplication(), session_id, request, request);
201 // When not out of process, we remote all the message processing.
202 DDF out,in = wrap(request, NULL, true);
203 DDFJanitor jin(in), jout(out);
205 in.addmember("session_id").string(session_id);
206 out=request.getServiceProvider().getListenerService()->send(in);
207 return unwrap(request, out);
211 void SAML2Logout::receive(DDF& in, ostream& out)
214 const char* aid=in["application_id"].string();
215 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
217 // Something's horribly wrong.
218 m_log.error("couldn't find application (%s) for logout", aid ? aid : "(missing)");
219 throw ConfigurationException("Unable to locate application for logout, deleted?");
222 // Unpack the request.
224 DDFJanitor jout(ret);
225 auto_ptr<HTTPRequest> req(getRequest(in));
226 auto_ptr<HTTPResponse> resp(getResponse(ret));
228 // Since we're remoted, the result should either be a throw, which we pass on,
229 // a false/0 return, which we just return as an empty structure, or a response/redirect,
230 // which we capture in the facade and send back.
231 doRequest(*app, in["session_id"].string(), *req.get(), *resp.get());
235 pair<bool,long> SAML2Logout::doRequest(
236 const Application& application, const char* session_id, const HTTPRequest& request, HTTPResponse& response
240 SessionCache* cache = application.getServiceProvider().getSessionCache();
241 if (!strcmp(request.getMethod(),"GET") && request.getParameter("notifying")) {
243 // This is returning from a front-channel notification, so we have to do the back-channel and then
244 // respond. To do that, we need state from the original request.
245 if (!request.getParameter("entityID")) {
247 cache->remove(session_id, application);
248 throw FatalProfileException("Application notification loop did not return entityID for LogoutResponse.");
251 // Best effort on back channel and to remove the user agent's session.
252 bool worked1 = false,worked2 = false;
254 vector<string> sessions(1,session_id);
255 worked1 = notifyBackChannel(application, sessions);
257 cache->remove(session_id, application);
260 catch (exception& ex) {
261 m_log.error("error removing session (%s): %s", session_id, ex.what());
265 worked1 = worked2 = true;
268 // We need metadata to issue a response.
269 Locker metadataLocker(application.getMetadataProvider());
270 const EntityDescriptor* entity = application.getMetadataProvider()->getEntityDescriptor(request.getParameter("entityID"));
272 throw MetadataException(
273 "Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", request.getParameter("entityID"))
276 const IDPSSODescriptor* idp = entity->getIDPSSODescriptor(samlconstants::SAML20P_NS);
278 throw MetadataException(
279 "Unable to locate SAML 2.0 IdP role for identity provider ($entityID).",
280 namedparams(1, "entityID", request.getParameter("entityID"))
284 auto_ptr_XMLCh reqid(request.getParameter("ID"));
285 if (worked1 && worked2) {
286 // Successful LogoutResponse. Has to be front-channel or we couldn't be here.
288 reqid.get(), StatusCode::SUCCESS, NULL, NULL, request.getParameter("RelayState"), idp, application, response, true
294 StatusCode::RESPONDER, NULL, "Unable to fully destroy principal's session.",
295 request.getParameter("RelayState"),
303 // If we get here, it's an external protocol message to decode.
305 // Locate policy key.
306 pair<bool,const char*> policyId = getString("policyId", m_configNS.get()); // namespace-qualified if inside handler element
308 policyId = application.getString("policyId"); // unqualified in Application(s) element
310 // Access policy properties.
311 const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId.second);
312 pair<bool,bool> validate = settings->getBool("validate");
314 // Lock metadata for use by policy.
315 Locker metadataLocker(application.getMetadataProvider());
317 // Create the policy.
318 shibsp::SecurityPolicy policy(application, &m_role, validate.first && validate.second);
320 // Decode the message.
322 auto_ptr<XMLObject> msg(m_decoder->decode(relayState, request, policy));
323 const LogoutRequest* logoutRequest = dynamic_cast<LogoutRequest*>(msg.get());
325 if (!policy.isSecure())
326 throw SecurityPolicyException("Security of LogoutRequest not established.");
328 // Message from IdP to logout one or more sessions.
330 // If this is front-channel, we have to have a session_id to use already.
331 if (m_decoder->isUserAgentPresent() && !session_id) {
332 m_log.error("no active session");
334 logoutRequest->getID(),
335 StatusCode::REQUESTER, StatusCode::UNKNOWN_PRINCIPAL, "No active session found in request.",
337 policy.getIssuerMetadata(),
344 bool ownedName = false;
345 NameID* nameid = logoutRequest->getNameID();
347 // Check for EncryptedID.
348 EncryptedID* encname = logoutRequest->getEncryptedID();
350 CredentialResolver* cr=application.getCredentialResolver();
352 m_log.warn("found encrypted NameID, but no decryption credential was available");
354 Locker credlocker(cr);
355 auto_ptr<MetadataCredentialCriteria> mcc(
356 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
359 auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr,application.getXMLString("entityID").second,mcc.get()));
360 nameid = dynamic_cast<NameID*>(decryptedID.get());
363 decryptedID.release();
366 catch (exception& ex) {
367 m_log.error(ex.what());
373 // No NameID, so must respond with an error.
374 m_log.error("NameID not found in request");
376 logoutRequest->getID(),
377 StatusCode::REQUESTER, StatusCode::UNKNOWN_PRINCIPAL, "NameID not found in request.",
379 policy.getIssuerMetadata(),
382 m_decoder->isUserAgentPresent()
386 // Suck indexes out of the request for next steps.
388 EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL;
389 const vector<SessionIndex*> sindexes = logoutRequest->getSessionIndexs();
390 for (vector<SessionIndex*>::const_iterator i = sindexes.begin(); i != sindexes.end(); ++i) {
391 auto_ptr_char sindex((*i)->getSessionIndex());
392 indexes.insert(sindex.get());
395 // For a front-channel LogoutRequest, we have to match the information in the request
396 // against the current session.
398 if (!cache->matches(session_id, entity, *nameid, &indexes, application)) {
400 logoutRequest->getID(),
401 StatusCode::REQUESTER, StatusCode::REQUEST_DENIED, "Active sessions did not match logout request.",
403 policy.getIssuerMetadata(),
412 // Now we perform "logout" by finding the matching sessions.
413 vector<string> sessions;
415 time_t expires = logoutRequest->getNotOnOrAfter() ? logoutRequest->getNotOnOrAfterEpoch() : 0;
416 cache->logout(entity, *nameid, &indexes, expires, application, sessions);
418 // Now we actually terminate everything except for the active session,
419 // if this is front-channel, for notification purposes.
420 for (vector<string>::const_iterator sit = sessions.begin(); sit != sessions.end(); ++sit)
421 if (session_id && strcmp(sit->c_str(), session_id))
422 cache->remove(sit->c_str(), application);
424 catch (exception& ex) {
425 m_log.error("error while logging out matching sessions: %s", ex.what());
427 logoutRequest->getID(),
428 StatusCode::RESPONDER, NULL, ex.what(),
430 policy.getIssuerMetadata(),
433 m_decoder->isUserAgentPresent()
437 if (m_decoder->isUserAgentPresent()) {
438 // Pass control to the first front channel notification point, if any.
439 map<string,string> parammap;
440 if (!relayState.empty())
441 parammap["RelayState"] = relayState;
442 auto_ptr_char entityID(entity ? entity->getEntityID() : NULL);
444 parammap["entityID"] = entityID.get();
445 auto_ptr_char reqID(logoutRequest->getID());
447 parammap["ID"] = reqID.get();
448 pair<bool,long> result = notifyFrontChannel(application, request, response, ¶mmap);
453 // For back-channel requests, or if no front-channel notification is needed...
454 bool worked1 = false,worked2 = false;
455 worked1 = notifyBackChannel(application, sessions);
457 // One last session to yoink...
459 cache->remove(session_id, application);
462 catch (exception& ex) {
463 m_log.error("error removing active session (%s): %s", session_id, ex.what());
468 logoutRequest->getID(),
469 (worked1 && worked2) ? StatusCode::SUCCESS : StatusCode::RESPONDER,
470 (worked1 && worked2) ? NULL : StatusCode::PARTIAL_LOGOUT,
473 policy.getIssuerMetadata(),
476 m_decoder->isUserAgentPresent()
480 // A LogoutResponse completes an SP-initiated logout sequence.
481 const LogoutResponse* logoutResponse = dynamic_cast<LogoutResponse*>(msg.get());
482 if (logoutResponse) {
483 if (!policy.isSecure()) {
484 SecurityPolicyException ex("Security of LogoutResponse not established.");
485 if (policy.getIssuerMetadata())
486 annotateException(&ex, policy.getIssuerMetadata()); // throws it
489 checkError(logoutResponse, policy.getIssuerMetadata()); // throws if Status doesn't look good...
491 // Return template for completion of global logout, or redirect to homeURL.
492 return sendLogoutPage(application, response, false, "Global logout completed.");
495 FatalProfileException ex("Incoming message was not a samlp:LogoutRequest or samlp:LogoutResponse.");
496 if (policy.getIssuerMetadata())
497 annotateException(&ex, policy.getIssuerMetadata()); // throws it
499 return make_pair(false,0); // never happen, satisfies compiler
501 throw ConfigurationException("Cannot process logout message using lite version of shibsp library.");
507 bool SAML2Logout::stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const
509 if (!XMLString::equals(n1.getName(), n2.getName()))
512 const XMLCh* s1 = n1.getFormat();
513 const XMLCh* s2 = n2.getFormat();
515 s1 = saml2::NameID::UNSPECIFIED;
517 s2 = saml2::NameID::UNSPECIFIED;
518 if (!XMLString::equals(s1,s2))
521 s1 = n1.getNameQualifier();
522 s2 = n2.getNameQualifier();
527 if (!XMLString::equals(s1,s2))
530 s1 = n1.getSPNameQualifier();
531 s2 = n2.getSPNameQualifier();
536 if (!XMLString::equals(s1,s2))
542 pair<bool,long> SAML2Logout::sendResponse(
543 const XMLCh* requestID,
545 const XMLCh* subcode,
547 const char* relayState,
548 const RoleDescriptor* role,
549 const Application& application,
550 HTTPResponse& httpResponse,
554 // Get endpoint and encoder to use.
555 const EndpointType* ep = NULL;
556 const MessageEncoder* encoder = NULL;
558 const IDPSSODescriptor* idp = dynamic_cast<const IDPSSODescriptor*>(role);
559 for (vector<const XMLCh*>::const_iterator b = m_bindings.begin(); idp && b!=m_bindings.end(); ++b) {
560 if (ep=EndpointManager<SingleLogoutService>(idp->getSingleLogoutServices()).getByBinding(*b)) {
561 map<const XMLCh*,MessageEncoder*>::const_iterator enc = m_encoders.find(*b);
562 if (enc!=m_encoders.end())
563 encoder = enc->second;
567 if (!ep || !encoder) {
568 auto_ptr_char id(dynamic_cast<EntityDescriptor*>(role->getParent())->getEntityID());
569 m_log.error("unable to locate compatible SLO service for provider (%s)", id.get());
570 MetadataException ex("Unable to locate endpoint at IdP ($entityID) to send LogoutResponse.");
571 annotateException(&ex, role); // throws it
575 encoder = m_encoders.begin()->second;
579 auto_ptr<LogoutResponse> logout(LogoutResponseBuilder::buildLogoutResponse());
580 logout->setInResponseTo(requestID);
582 logout->setDestination(ep->getLocation());
583 Issuer* issuer = IssuerBuilder::buildIssuer();
584 logout->setIssuer(issuer);
585 issuer->setName(application.getXMLString("entityID").second);
586 fillStatus(*logout.get(), code, subcode, msg);
588 auto_ptr_char dest(ep ? ep->getLocation() : NULL);
590 long ret = sendMessage(*encoder, logout.get(), relayState, dest.get(), role, application, httpResponse, "signResponses");
591 logout.release(); // freed by encoder
592 return make_pair(true,ret);