2 * Copyright 2001-2009 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 "SessionCacheEx.h"
33 # include "security/SecurityPolicy.h"
34 # include "metadata/MetadataProviderCriteria.h"
35 # include "util/TemplateParameters.h"
37 # include <saml/SAMLConfig.h>
38 # include <saml/saml2/core/Protocols.h>
39 # include <saml/saml2/metadata/EndpointManager.h>
40 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
41 # include <xmltooling/util/URLEncoder.h>
42 using namespace opensaml::saml2;
43 using namespace opensaml::saml2p;
44 using namespace opensaml::saml2md;
45 using namespace opensaml;
48 using namespace shibsp;
49 using namespace xmltooling;
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 void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
78 const char* loc = getString("Location").second;
79 string hurl(handlerURL);
83 auto_ptr_XMLCh widen(hurl.c_str());
84 SingleLogoutService* ep = SingleLogoutServiceBuilder::buildSingleLogoutService();
85 ep->setLocation(widen.get());
86 ep->setBinding(getXMLString("Binding").second);
87 role.getSingleLogoutServices().push_back(ep);
88 role.addSupport(samlconstants::SAML20P_NS);
91 const char* getType() const {
92 return "SingleLogoutService";
97 pair<bool,long> doRequest(const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse) const;
100 pair<bool,long> sendResponse(
101 const XMLCh* requestID,
103 const XMLCh* subcode,
105 const char* relayState,
106 const RoleDescriptor* role,
107 const Application& application,
108 HTTPResponse& httpResponse,
112 xmltooling::QName m_role;
113 MessageDecoder* m_decoder;
115 vector<const XMLCh*> m_bindings;
116 map<const XMLCh*,MessageEncoder*> m_encoders;
120 #if defined (_MSC_VER)
121 #pragma warning( pop )
124 Handler* SHIBSP_DLLLOCAL SAML2LogoutFactory(const pair<const DOMElement*,const char*>& p)
126 return new SAML2Logout(p.first, p.second);
130 SAML2Logout::SAML2Logout(const DOMElement* e, const char* appId)
131 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".Logout.SAML2"))
133 ,m_role(samlconstants::SAML20MD_NS, IDPSSODescriptor::LOCAL_NAME), m_decoder(NULL), m_outgoing(NULL)
138 m_preserve.push_back("ID");
139 m_preserve.push_back("entityID");
140 m_preserve.push_back("RelayState");
142 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
143 SAMLConfig& conf = SAMLConfig::getConfig();
145 // Handle incoming binding.
146 m_decoder = conf.MessageDecoderManager.newPlugin(
147 getString("Binding").second, pair<const DOMElement*,const XMLCh*>(e,shibspconstants::SHIB2SPCONFIG_NS)
149 m_decoder->setArtifactResolver(SPConfig::getConfig().getArtifactResolver());
151 if (m_decoder->isUserAgentPresent()) {
152 // Handle front-channel binding setup.
153 pair<bool,const XMLCh*> outgoing = getXMLString("outgoingBindings", m_configNS.get());
154 if (outgoing.first) {
155 m_outgoing = XMLString::replicate(outgoing.second);
156 XMLString::trim(m_outgoing);
159 // No override, so we'll install a default binding precedence.
160 string prec = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
161 samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
162 m_outgoing = XMLString::transcode(prec.c_str());
166 XMLCh* start = m_outgoing;
167 while (start && *start) {
168 pos = XMLString::indexOf(start,chSpace);
170 *(start + pos)=chNull;
171 m_bindings.push_back(start);
173 auto_ptr_char b(start);
174 MessageEncoder * encoder = conf.MessageEncoderManager.newPlugin(
175 b.get(), pair<const DOMElement*,const XMLCh*>(e,shibspconstants::SHIB2SPCONFIG_NS)
177 m_encoders[start] = encoder;
178 m_log.debug("supporting outgoing front-channel binding (%s)", b.get());
180 catch (exception& ex) {
181 m_log.error("error building MessageEncoder: %s", ex.what());
184 start = start + pos + 1;
190 MessageEncoder* encoder = conf.MessageEncoderManager.newPlugin(
191 getString("Binding").second, pair<const DOMElement*,const XMLCh*>(e,shibspconstants::SHIB2SPCONFIG_NS)
193 m_encoders.insert(pair<const XMLCh*,MessageEncoder*>(NULL, encoder));
198 string address(appId);
199 address += getString("Location").second;
200 setAddress(address.c_str());
203 pair<bool,long> SAML2Logout::run(SPRequest& request, bool isHandler) const
205 // Defer to base class for front-channel loop first.
206 // This won't initiate the loop, only continue/end it.
207 pair<bool,long> ret = LogoutHandler::run(request, isHandler);
211 SPConfig& conf = SPConfig::getConfig();
212 if (conf.isEnabled(SPConfig::OutOfProcess)) {
213 // When out of process, we run natively and directly process the message.
214 return doRequest(request.getApplication(), request, request);
217 // When not out of process, we remote all the message processing.
218 vector<string> headers(1,"Cookie");
219 DDF out,in = wrap(request, &headers, true);
220 DDFJanitor jin(in), jout(out);
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.
238 auto_ptr<HTTPRequest> req(getRequest(in));
240 // Wrap a response shim.
242 DDFJanitor jout(ret);
243 auto_ptr<HTTPResponse> resp(getResponse(ret));
245 // Since we're remoted, the result should either be a throw, which we pass on,
246 // a false/0 return, which we just return as an empty structure, or a response/redirect,
247 // which we capture in the facade and send back.
248 doRequest(*app, *req.get(), *resp.get());
252 pair<bool,long> SAML2Logout::doRequest(const Application& application, const HTTPRequest& request, HTTPResponse& response) const
255 // First capture the active session ID.
256 SessionCache* cache = application.getServiceProvider().getSessionCache();
257 SessionCacheEx* cacheex = dynamic_cast<SessionCacheEx*>(cache);
258 string session_id = cache->active(application, request);
260 if (!strcmp(request.getMethod(),"GET") && request.getParameter("notifying")) {
261 // This is returning from a front-channel notification, so we have to do the back-channel and then
262 // respond. To do that, we need state from the original request.
263 if (!request.getParameter("entityID")) {
264 cache->remove(application, request, &response);
265 throw FatalProfileException("Application notification loop did not return entityID for LogoutResponse.");
268 // Best effort on back channel and to remove the user agent's session.
269 bool worked1 = false,worked2 = false;
270 if (!session_id.empty()) {
271 vector<string> sessions(1,session_id);
272 worked1 = notifyBackChannel(application, request.getRequestURL(), sessions, false);
274 cache->remove(application, request, &response);
277 catch (exception& ex) {
278 m_log.error("error removing session (%s): %s", session_id, ex.what());
282 worked1 = worked2 = true;
285 // We need metadata to issue a response.
286 MetadataProvider* m = application.getMetadataProvider();
287 Locker metadataLocker(m);
288 MetadataProviderCriteria mc(application, request.getParameter("entityID"), &IDPSSODescriptor::ELEMENT_QNAME, samlconstants::SAML20P_NS);
289 pair<const EntityDescriptor*,const RoleDescriptor*> entity = m->getEntityDescriptor(mc);
291 throw MetadataException(
292 "Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", request.getParameter("entityID"))
295 else if (!entity.second) {
296 throw MetadataException(
297 "Unable to locate SAML 2.0 IdP role for identity provider ($entityID).",
298 namedparams(1, "entityID", request.getParameter("entityID"))
302 auto_ptr_XMLCh reqid(request.getParameter("ID"));
303 if (worked1 && worked2) {
304 // Successful LogoutResponse. Has to be front-channel or we couldn't be here.
306 reqid.get(), StatusCode::SUCCESS, NULL, NULL, request.getParameter("RelayState"), entity.second, application, response, true
312 StatusCode::RESPONDER, NULL, "Unable to fully destroy principal's session.",
313 request.getParameter("RelayState"),
321 // If we get here, it's an external protocol message to decode.
323 // Locate policy key.
324 pair<bool,const char*> policyId = getString("policyId", m_configNS.get()); // namespace-qualified if inside handler element
326 policyId = application.getString("policyId"); // unqualified in Application(s) element
328 // Access policy properties.
329 const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId.second);
330 pair<bool,bool> validate = settings->getBool("validate");
332 // Lock metadata for use by policy.
333 Locker metadataLocker(application.getMetadataProvider());
335 // Create the policy.
336 shibsp::SecurityPolicy policy(application, &m_role, validate.first && validate.second);
338 // Decode the message.
340 auto_ptr<XMLObject> msg(m_decoder->decode(relayState, request, policy));
341 const LogoutRequest* logoutRequest = dynamic_cast<LogoutRequest*>(msg.get());
343 if (!policy.isAuthenticated())
344 throw SecurityPolicyException("Security of LogoutRequest not established.");
346 // Message from IdP to logout one or more sessions.
348 // If this is front-channel, we have to have a session_id to use already.
349 if (m_decoder->isUserAgentPresent() && session_id.empty()) {
350 m_log.error("no active session");
352 logoutRequest->getID(),
353 StatusCode::REQUESTER, StatusCode::UNKNOWN_PRINCIPAL, "No active session found in request.",
355 policy.getIssuerMetadata(),
362 bool ownedName = false;
363 NameID* nameid = logoutRequest->getNameID();
365 // Check for EncryptedID.
366 EncryptedID* encname = logoutRequest->getEncryptedID();
368 CredentialResolver* cr=application.getCredentialResolver();
370 m_log.warn("found encrypted NameID, but no decryption credential was available");
372 Locker credlocker(cr);
373 auto_ptr<MetadataCredentialCriteria> mcc(
374 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
377 auto_ptr<XMLObject> decryptedID(
380 application.getRelyingParty(policy.getIssuerMetadata() ? dynamic_cast<EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL)->getXMLString("entityID").second,
384 nameid = dynamic_cast<NameID*>(decryptedID.get());
387 decryptedID.release();
390 catch (exception& ex) {
391 m_log.error(ex.what());
397 // No NameID, so must respond with an error.
398 m_log.error("NameID not found in request");
400 logoutRequest->getID(),
401 StatusCode::REQUESTER, StatusCode::UNKNOWN_PRINCIPAL, "NameID not found in request.",
403 policy.getIssuerMetadata(),
406 m_decoder->isUserAgentPresent()
410 auto_ptr<NameID> namewrapper(ownedName ? nameid : NULL);
412 // Suck indexes out of the request for next steps.
414 EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL;
415 const vector<SessionIndex*> sindexes = logoutRequest->getSessionIndexs();
416 for (vector<SessionIndex*>::const_iterator i = sindexes.begin(); i != sindexes.end(); ++i) {
417 auto_ptr_char sindex((*i)->getSessionIndex());
418 indexes.insert(sindex.get());
421 // For a front-channel LogoutRequest, we have to match the information in the request
422 // against the current session.
423 if (!session_id.empty()) {
424 if (!cache->matches(application, request, entity, *nameid, &indexes)) {
426 logoutRequest->getID(),
427 StatusCode::REQUESTER, StatusCode::REQUEST_DENIED, "Active session did not match logout request.",
429 policy.getIssuerMetadata(),
438 // Now we perform "logout" by finding the matching sessions.
439 vector<string> sessions;
442 time_t expires = logoutRequest->getNotOnOrAfter() ? logoutRequest->getNotOnOrAfterEpoch() : 0;
443 cacheex->logout(application, entity, *nameid, &indexes, expires, sessions);
444 m_log.debug("session cache returned %d sessions bound to NameID in logout request", sessions.size());
446 // Now we actually terminate everything except for the active session,
447 // if this is front-channel, for notification purposes.
448 for (vector<string>::const_iterator sit = sessions.begin(); sit != sessions.end(); ++sit)
449 if (*sit != session_id)
450 cacheex->remove(application, sit->c_str()); // using the ID-based removal operation
453 m_log.warn("session cache does not support extended API, can't implement indirect logout of sessions");
454 if (!session_id.empty())
455 sessions.push_back(session_id);
458 catch (exception& ex) {
459 m_log.error("error while logging out matching sessions: %s", ex.what());
461 logoutRequest->getID(),
462 StatusCode::RESPONDER, NULL, ex.what(),
464 policy.getIssuerMetadata(),
467 m_decoder->isUserAgentPresent()
471 if (m_decoder->isUserAgentPresent()) {
472 // Pass control to the first front channel notification point, if any.
473 map<string,string> parammap;
474 if (!relayState.empty())
475 parammap["RelayState"] = relayState;
476 auto_ptr_char entityID(entity ? entity->getEntityID() : NULL);
478 parammap["entityID"] = entityID.get();
479 auto_ptr_char reqID(logoutRequest->getID());
481 parammap["ID"] = reqID.get();
482 pair<bool,long> result = notifyFrontChannel(application, request, response, ¶mmap);
487 // For back-channel requests, or if no front-channel notification is needed...
488 bool worked1 = false,worked2 = false;
489 worked1 = notifyBackChannel(application, request.getRequestURL(), sessions, false);
490 if (!session_id.empty()) {
491 // One last session to yoink...
493 cache->remove(application, request, &response);
496 catch (exception& ex) {
497 m_log.error("error removing active session (%s): %s", session_id.c_str(), ex.what());
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 // If relay state is set, recover the original return URL.
526 if (!relayState.empty())
527 recoverRelayState(application, request, response, relayState);
528 if (!relayState.empty())
529 return make_pair(true, response.sendRedirect(relayState.c_str()));
531 // Return template for completion of global logout, or redirect to homeURL.
532 return sendLogoutPage(application, request, response, false, "Global logout completed.");
535 FatalProfileException ex("Incoming message was not a samlp:LogoutRequest or samlp:LogoutResponse.");
536 if (policy.getIssuerMetadata())
537 annotateException(&ex, policy.getIssuerMetadata()); // throws it
539 return make_pair(false,0L); // never happen, satisfies compiler
541 throw ConfigurationException("Cannot process logout message using lite version of shibsp library.");
547 pair<bool,long> SAML2Logout::sendResponse(
548 const XMLCh* requestID,
550 const XMLCh* subcode,
552 const char* relayState,
553 const RoleDescriptor* role,
554 const Application& application,
555 HTTPResponse& httpResponse,
559 // Get endpoint and encoder to use.
560 const EndpointType* ep = NULL;
561 const MessageEncoder* encoder = NULL;
563 const IDPSSODescriptor* idp = dynamic_cast<const IDPSSODescriptor*>(role);
564 for (vector<const XMLCh*>::const_iterator b = m_bindings.begin(); idp && b!=m_bindings.end(); ++b) {
565 if (ep=EndpointManager<SingleLogoutService>(idp->getSingleLogoutServices()).getByBinding(*b)) {
566 map<const XMLCh*,MessageEncoder*>::const_iterator enc = m_encoders.find(*b);
567 if (enc!=m_encoders.end())
568 encoder = enc->second;
572 if (!ep || !encoder) {
573 auto_ptr_char id(dynamic_cast<EntityDescriptor*>(role->getParent())->getEntityID());
574 m_log.error("unable to locate compatible SLO service for provider (%s)", id.get());
575 MetadataException ex("Unable to locate endpoint at IdP ($entityID) to send LogoutResponse.");
576 annotateException(&ex, role); // throws it
580 encoder = m_encoders.begin()->second;
584 auto_ptr<LogoutResponse> logout(LogoutResponseBuilder::buildLogoutResponse());
585 logout->setInResponseTo(requestID);
587 const XMLCh* loc = ep->getResponseLocation();
589 loc = ep->getLocation();
590 logout->setDestination(loc);
592 Issuer* issuer = IssuerBuilder::buildIssuer();
593 logout->setIssuer(issuer);
594 issuer->setName(application.getRelyingParty(dynamic_cast<EntityDescriptor*>(role->getParent()))->getXMLString("entityID").second);
595 fillStatus(*logout.get(), code, subcode, msg);
597 auto_ptr_char dest(logout->getDestination());
599 long ret = sendMessage(*encoder, logout.get(), relayState, dest.get(), role, application, httpResponse);
600 logout.release(); // freed by encoder
601 return make_pair(true,ret);