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);
247 throw FatalProfileException("Application notification loop did not return entityID for LogoutResponse.");
250 // Best effort on back channel and to remove the user agent's session.
251 bool worked1 = false,worked2 = false;
253 vector<string> sessions(1,session_id);
254 worked1 = notifyBackChannel(application, request.getRequestURL(), sessions, false);
256 cache->remove(session_id, application);
259 catch (exception& ex) {
260 m_log.error("error removing session (%s): %s", session_id, ex.what());
264 worked1 = worked2 = true;
267 // We need metadata to issue a response.
268 Locker metadataLocker(application.getMetadataProvider());
269 const EntityDescriptor* entity = application.getMetadataProvider()->getEntityDescriptor(request.getParameter("entityID"));
271 throw MetadataException(
272 "Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", request.getParameter("entityID"))
275 const IDPSSODescriptor* idp = entity->getIDPSSODescriptor(samlconstants::SAML20P_NS);
277 throw MetadataException(
278 "Unable to locate SAML 2.0 IdP role for identity provider ($entityID).",
279 namedparams(1, "entityID", request.getParameter("entityID"))
283 auto_ptr_XMLCh reqid(request.getParameter("ID"));
284 if (worked1 && worked2) {
285 // Successful LogoutResponse. Has to be front-channel or we couldn't be here.
287 reqid.get(), StatusCode::SUCCESS, NULL, NULL, request.getParameter("RelayState"), idp, application, response, true
293 StatusCode::RESPONDER, NULL, "Unable to fully destroy principal's session.",
294 request.getParameter("RelayState"),
302 // If we get here, it's an external protocol message to decode.
304 // Locate policy key.
305 pair<bool,const char*> policyId = getString("policyId", m_configNS.get()); // namespace-qualified if inside handler element
307 policyId = application.getString("policyId"); // unqualified in Application(s) element
309 // Access policy properties.
310 const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId.second);
311 pair<bool,bool> validate = settings->getBool("validate");
313 // Lock metadata for use by policy.
314 Locker metadataLocker(application.getMetadataProvider());
316 // Create the policy.
317 shibsp::SecurityPolicy policy(application, &m_role, validate.first && validate.second);
319 // Decode the message.
321 auto_ptr<XMLObject> msg(m_decoder->decode(relayState, request, policy));
322 const LogoutRequest* logoutRequest = dynamic_cast<LogoutRequest*>(msg.get());
324 if (!policy.isSecure())
325 throw SecurityPolicyException("Security of LogoutRequest not established.");
327 // Message from IdP to logout one or more sessions.
329 // If this is front-channel, we have to have a session_id to use already.
330 if (m_decoder->isUserAgentPresent() && !session_id) {
331 m_log.error("no active session");
333 logoutRequest->getID(),
334 StatusCode::REQUESTER, StatusCode::UNKNOWN_PRINCIPAL, "No active session found in request.",
336 policy.getIssuerMetadata(),
343 bool ownedName = false;
344 NameID* nameid = logoutRequest->getNameID();
346 // Check for EncryptedID.
347 EncryptedID* encname = logoutRequest->getEncryptedID();
349 CredentialResolver* cr=application.getCredentialResolver();
351 m_log.warn("found encrypted NameID, but no decryption credential was available");
353 Locker credlocker(cr);
354 auto_ptr<MetadataCredentialCriteria> mcc(
355 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
358 auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr,application.getXMLString("entityID").second,mcc.get()));
359 nameid = dynamic_cast<NameID*>(decryptedID.get());
362 decryptedID.release();
365 catch (exception& ex) {
366 m_log.error(ex.what());
372 // No NameID, so must respond with an error.
373 m_log.error("NameID not found in request");
375 logoutRequest->getID(),
376 StatusCode::REQUESTER, StatusCode::UNKNOWN_PRINCIPAL, "NameID not found in request.",
378 policy.getIssuerMetadata(),
381 m_decoder->isUserAgentPresent()
385 // Suck indexes out of the request for next steps.
387 EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL;
388 const vector<SessionIndex*> sindexes = logoutRequest->getSessionIndexs();
389 for (vector<SessionIndex*>::const_iterator i = sindexes.begin(); i != sindexes.end(); ++i) {
390 auto_ptr_char sindex((*i)->getSessionIndex());
391 indexes.insert(sindex.get());
394 // For a front-channel LogoutRequest, we have to match the information in the request
395 // against the current session.
397 if (!cache->matches(session_id, entity, *nameid, &indexes, application)) {
399 logoutRequest->getID(),
400 StatusCode::REQUESTER, StatusCode::REQUEST_DENIED, "Active sessions did not match logout request.",
402 policy.getIssuerMetadata(),
411 // Now we perform "logout" by finding the matching sessions.
412 vector<string> sessions;
414 time_t expires = logoutRequest->getNotOnOrAfter() ? logoutRequest->getNotOnOrAfterEpoch() : 0;
415 cache->logout(entity, *nameid, &indexes, expires, application, sessions);
417 // Now we actually terminate everything except for the active session,
418 // if this is front-channel, for notification purposes.
419 for (vector<string>::const_iterator sit = sessions.begin(); sit != sessions.end(); ++sit)
420 if (session_id && strcmp(sit->c_str(), session_id))
421 cache->remove(sit->c_str(), application);
423 catch (exception& ex) {
424 m_log.error("error while logging out matching sessions: %s", ex.what());
426 logoutRequest->getID(),
427 StatusCode::RESPONDER, NULL, ex.what(),
429 policy.getIssuerMetadata(),
432 m_decoder->isUserAgentPresent()
436 if (m_decoder->isUserAgentPresent()) {
437 // Pass control to the first front channel notification point, if any.
438 map<string,string> parammap;
439 if (!relayState.empty())
440 parammap["RelayState"] = relayState;
441 auto_ptr_char entityID(entity ? entity->getEntityID() : NULL);
443 parammap["entityID"] = entityID.get();
444 auto_ptr_char reqID(logoutRequest->getID());
446 parammap["ID"] = reqID.get();
447 pair<bool,long> result = notifyFrontChannel(application, request, response, ¶mmap);
452 // For back-channel requests, or if no front-channel notification is needed...
453 bool worked1 = false,worked2 = false;
454 worked1 = notifyBackChannel(application, request.getRequestURL(), sessions, false);
456 // One last session to yoink...
458 cache->remove(session_id, application);
461 catch (exception& ex) {
462 m_log.error("error removing active session (%s): %s", session_id, ex.what());
467 logoutRequest->getID(),
468 (worked1 && worked2) ? StatusCode::SUCCESS : StatusCode::RESPONDER,
469 (worked1 && worked2) ? NULL : StatusCode::PARTIAL_LOGOUT,
472 policy.getIssuerMetadata(),
475 m_decoder->isUserAgentPresent()
479 // A LogoutResponse completes an SP-initiated logout sequence.
480 const LogoutResponse* logoutResponse = dynamic_cast<LogoutResponse*>(msg.get());
481 if (logoutResponse) {
482 if (!policy.isSecure()) {
483 SecurityPolicyException ex("Security of LogoutResponse not established.");
484 if (policy.getIssuerMetadata())
485 annotateException(&ex, policy.getIssuerMetadata()); // throws it
488 checkError(logoutResponse, policy.getIssuerMetadata()); // throws if Status doesn't look good...
490 // Return template for completion of global logout, or redirect to homeURL.
491 return sendLogoutPage(application, response, false, "Global logout completed.");
494 FatalProfileException ex("Incoming message was not a samlp:LogoutRequest or samlp:LogoutResponse.");
495 if (policy.getIssuerMetadata())
496 annotateException(&ex, policy.getIssuerMetadata()); // throws it
498 return make_pair(false,0); // never happen, satisfies compiler
500 throw ConfigurationException("Cannot process logout message using lite version of shibsp library.");
506 bool SAML2Logout::stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const
508 if (!XMLString::equals(n1.getName(), n2.getName()))
511 const XMLCh* s1 = n1.getFormat();
512 const XMLCh* s2 = n2.getFormat();
514 s1 = saml2::NameID::UNSPECIFIED;
516 s2 = saml2::NameID::UNSPECIFIED;
517 if (!XMLString::equals(s1,s2))
520 s1 = n1.getNameQualifier();
521 s2 = n2.getNameQualifier();
526 if (!XMLString::equals(s1,s2))
529 s1 = n1.getSPNameQualifier();
530 s2 = n2.getSPNameQualifier();
535 if (!XMLString::equals(s1,s2))
541 pair<bool,long> SAML2Logout::sendResponse(
542 const XMLCh* requestID,
544 const XMLCh* subcode,
546 const char* relayState,
547 const RoleDescriptor* role,
548 const Application& application,
549 HTTPResponse& httpResponse,
553 // Get endpoint and encoder to use.
554 const EndpointType* ep = NULL;
555 const MessageEncoder* encoder = NULL;
557 const IDPSSODescriptor* idp = dynamic_cast<const IDPSSODescriptor*>(role);
558 for (vector<const XMLCh*>::const_iterator b = m_bindings.begin(); idp && b!=m_bindings.end(); ++b) {
559 if (ep=EndpointManager<SingleLogoutService>(idp->getSingleLogoutServices()).getByBinding(*b)) {
560 map<const XMLCh*,MessageEncoder*>::const_iterator enc = m_encoders.find(*b);
561 if (enc!=m_encoders.end())
562 encoder = enc->second;
566 if (!ep || !encoder) {
567 auto_ptr_char id(dynamic_cast<EntityDescriptor*>(role->getParent())->getEntityID());
568 m_log.error("unable to locate compatible SLO service for provider (%s)", id.get());
569 MetadataException ex("Unable to locate endpoint at IdP ($entityID) to send LogoutResponse.");
570 annotateException(&ex, role); // throws it
574 encoder = m_encoders.begin()->second;
578 auto_ptr<LogoutResponse> logout(LogoutResponseBuilder::buildLogoutResponse());
579 logout->setInResponseTo(requestID);
581 logout->setDestination(ep->getLocation());
582 Issuer* issuer = IssuerBuilder::buildIssuer();
583 logout->setIssuer(issuer);
584 issuer->setName(application.getXMLString("entityID").second);
585 fillStatus(*logout.get(), code, subcode, msg);
587 auto_ptr_char dest(ep ? ep->getLocation() : NULL);
589 long ret = sendMessage(*encoder, logout.get(), relayState, dest.get(), role, application, httpResponse, "signResponses");
590 logout.release(); // freed by encoder
591 return make_pair(true,ret);