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 "SessionCacheEx.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);
90 const char* getType() const {
91 return "SingleLogoutService";
96 pair<bool,long> doRequest(const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse) 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(
146 getString("Binding").second, pair<const DOMElement*,const XMLCh*>(e,shibspconstants::SHIB2SPCONFIG_NS)
148 m_decoder->setArtifactResolver(SPConfig::getConfig().getArtifactResolver());
150 if (m_decoder->isUserAgentPresent()) {
151 // Handle front-channel binding setup.
152 pair<bool,const XMLCh*> outgoing = getXMLString("outgoingBindings", m_configNS.get());
153 if (outgoing.first) {
154 m_outgoing = XMLString::replicate(outgoing.second);
155 XMLString::trim(m_outgoing);
158 // No override, so we'll install a default binding precedence.
159 string prec = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
160 samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
161 m_outgoing = XMLString::transcode(prec.c_str());
165 XMLCh* start = m_outgoing;
166 while (start && *start) {
167 pos = XMLString::indexOf(start,chSpace);
169 *(start + pos)=chNull;
170 m_bindings.push_back(start);
172 auto_ptr_char b(start);
173 MessageEncoder * encoder = conf.MessageEncoderManager.newPlugin(
174 b.get(), pair<const DOMElement*,const XMLCh*>(e,shibspconstants::SHIB2SPCONFIG_NS)
176 m_encoders[start] = encoder;
177 m_log.debug("supporting outgoing front-channel binding (%s)", b.get());
179 catch (exception& ex) {
180 m_log.error("error building MessageEncoder: %s", ex.what());
183 start = start + pos + 1;
189 MessageEncoder* encoder = conf.MessageEncoderManager.newPlugin(
190 getString("Binding").second, pair<const DOMElement*,const XMLCh*>(e,shibspconstants::SHIB2SPCONFIG_NS)
192 m_encoders.insert(pair<const XMLCh*,MessageEncoder*>(NULL, encoder));
197 string address(appId);
198 address += getString("Location").second;
199 setAddress(address.c_str());
202 pair<bool,long> SAML2Logout::run(SPRequest& request, bool isHandler) const
204 // Defer to base class for front-channel loop first.
205 // This won't initiate the loop, only continue/end it.
206 pair<bool,long> ret = LogoutHandler::run(request, isHandler);
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(), request, request);
216 // When not out of process, we remote all the message processing.
217 vector<string> headers(1,"Cookie");
218 DDF out,in = wrap(request, &headers, true);
219 DDFJanitor jin(in), jout(out);
220 out=request.getServiceProvider().getListenerService()->send(in);
221 return unwrap(request, out);
225 void SAML2Logout::receive(DDF& in, ostream& out)
228 const char* aid=in["application_id"].string();
229 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
231 // Something's horribly wrong.
232 m_log.error("couldn't find application (%s) for logout", aid ? aid : "(missing)");
233 throw ConfigurationException("Unable to locate application for logout, deleted?");
236 // Unpack the request.
237 auto_ptr<HTTPRequest> req(getRequest(in));
239 // Wrap a response shim.
241 DDFJanitor jout(ret);
242 auto_ptr<HTTPResponse> resp(getResponse(ret));
244 // Since we're remoted, the result should either be a throw, which we pass on,
245 // a false/0 return, which we just return as an empty structure, or a response/redirect,
246 // which we capture in the facade and send back.
247 doRequest(*app, *req.get(), *resp.get());
251 pair<bool,long> SAML2Logout::doRequest(const Application& application, const HTTPRequest& request, HTTPResponse& response) const
254 // First capture the active session ID.
255 SessionCache* cache = application.getServiceProvider().getSessionCache();
256 SessionCacheEx* cacheex = dynamic_cast<SessionCacheEx*>(cache);
257 string session_id = cache->active(application, request);
259 if (!strcmp(request.getMethod(),"GET") && request.getParameter("notifying")) {
260 // This is returning from a front-channel notification, so we have to do the back-channel and then
261 // respond. To do that, we need state from the original request.
262 if (!request.getParameter("entityID")) {
263 cache->remove(application, request, &response);
264 throw FatalProfileException("Application notification loop did not return entityID for LogoutResponse.");
267 // Best effort on back channel and to remove the user agent's session.
268 bool worked1 = false,worked2 = false;
269 if (!session_id.empty()) {
270 vector<string> sessions(1,session_id);
271 worked1 = notifyBackChannel(application, request.getRequestURL(), sessions, false);
273 cache->remove(application, request, &response);
276 catch (exception& ex) {
277 m_log.error("error removing session (%s): %s", session_id, ex.what());
281 worked1 = worked2 = true;
284 // We need metadata to issue a response.
285 MetadataProvider* m = application.getMetadataProvider();
286 Locker metadataLocker(m);
287 MetadataProvider::Criteria mc(request.getParameter("entityID"), &IDPSSODescriptor::ELEMENT_QNAME, samlconstants::SAML20P_NS);
288 pair<const EntityDescriptor*,const RoleDescriptor*> entity = m->getEntityDescriptor(mc);
290 throw MetadataException(
291 "Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", request.getParameter("entityID"))
294 else if (!entity.second) {
295 throw MetadataException(
296 "Unable to locate SAML 2.0 IdP role for identity provider ($entityID).",
297 namedparams(1, "entityID", request.getParameter("entityID"))
301 auto_ptr_XMLCh reqid(request.getParameter("ID"));
302 if (worked1 && worked2) {
303 // Successful LogoutResponse. Has to be front-channel or we couldn't be here.
305 reqid.get(), StatusCode::SUCCESS, NULL, NULL, request.getParameter("RelayState"), entity.second, application, response, true
311 StatusCode::RESPONDER, NULL, "Unable to fully destroy principal's session.",
312 request.getParameter("RelayState"),
320 // If we get here, it's an external protocol message to decode.
322 // Locate policy key.
323 pair<bool,const char*> policyId = getString("policyId", m_configNS.get()); // namespace-qualified if inside handler element
325 policyId = application.getString("policyId"); // unqualified in Application(s) element
327 // Access policy properties.
328 const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId.second);
329 pair<bool,bool> validate = settings->getBool("validate");
331 // Lock metadata for use by policy.
332 Locker metadataLocker(application.getMetadataProvider());
334 // Create the policy.
335 shibsp::SecurityPolicy policy(application, &m_role, validate.first && validate.second);
337 // Decode the message.
339 auto_ptr<XMLObject> msg(m_decoder->decode(relayState, request, policy));
340 const LogoutRequest* logoutRequest = dynamic_cast<LogoutRequest*>(msg.get());
342 if (!policy.isAuthenticated())
343 throw SecurityPolicyException("Security of LogoutRequest not established.");
345 // Message from IdP to logout one or more sessions.
347 // If this is front-channel, we have to have a session_id to use already.
348 if (m_decoder->isUserAgentPresent() && session_id.empty()) {
349 m_log.error("no active session");
351 logoutRequest->getID(),
352 StatusCode::REQUESTER, StatusCode::UNKNOWN_PRINCIPAL, "No active session found in request.",
354 policy.getIssuerMetadata(),
361 bool ownedName = false;
362 NameID* nameid = logoutRequest->getNameID();
364 // Check for EncryptedID.
365 EncryptedID* encname = logoutRequest->getEncryptedID();
367 CredentialResolver* cr=application.getCredentialResolver();
369 m_log.warn("found encrypted NameID, but no decryption credential was available");
371 Locker credlocker(cr);
372 auto_ptr<MetadataCredentialCriteria> mcc(
373 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
376 auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr,application.getXMLString("entityID").second,mcc.get()));
377 nameid = dynamic_cast<NameID*>(decryptedID.get());
380 decryptedID.release();
383 catch (exception& ex) {
384 m_log.error(ex.what());
390 // No NameID, so must respond with an error.
391 m_log.error("NameID not found in request");
393 logoutRequest->getID(),
394 StatusCode::REQUESTER, StatusCode::UNKNOWN_PRINCIPAL, "NameID not found in request.",
396 policy.getIssuerMetadata(),
399 m_decoder->isUserAgentPresent()
403 auto_ptr<NameID> namewrapper(ownedName ? nameid : NULL);
405 // Suck indexes out of the request for next steps.
407 EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL;
408 const vector<SessionIndex*> sindexes = logoutRequest->getSessionIndexs();
409 for (vector<SessionIndex*>::const_iterator i = sindexes.begin(); i != sindexes.end(); ++i) {
410 auto_ptr_char sindex((*i)->getSessionIndex());
411 indexes.insert(sindex.get());
414 // For a front-channel LogoutRequest, we have to match the information in the request
415 // against the current session.
416 if (!session_id.empty()) {
417 if (!cache->matches(application, request, entity, *nameid, &indexes)) {
419 logoutRequest->getID(),
420 StatusCode::REQUESTER, StatusCode::REQUEST_DENIED, "Active session did not match logout request.",
422 policy.getIssuerMetadata(),
431 // Now we perform "logout" by finding the matching sessions.
432 vector<string> sessions;
435 time_t expires = logoutRequest->getNotOnOrAfter() ? logoutRequest->getNotOnOrAfterEpoch() : 0;
436 cacheex->logout(application, entity, *nameid, &indexes, expires, sessions);
438 // Now we actually terminate everything except for the active session,
439 // if this is front-channel, for notification purposes.
440 for (vector<string>::const_iterator sit = sessions.begin(); sit != sessions.end(); ++sit)
441 if (*sit != session_id)
442 cacheex->remove(application, sit->c_str()); // using the ID-based removal operation
445 m_log.warn("session cache does not support extended API, can't implement indirect logout of sessions");
446 if (!session_id.empty())
447 sessions.push_back(session_id);
450 catch (exception& ex) {
451 m_log.error("error while logging out matching sessions: %s", ex.what());
453 logoutRequest->getID(),
454 StatusCode::RESPONDER, NULL, ex.what(),
456 policy.getIssuerMetadata(),
459 m_decoder->isUserAgentPresent()
463 if (m_decoder->isUserAgentPresent()) {
464 // Pass control to the first front channel notification point, if any.
465 map<string,string> parammap;
466 if (!relayState.empty())
467 parammap["RelayState"] = relayState;
468 auto_ptr_char entityID(entity ? entity->getEntityID() : NULL);
470 parammap["entityID"] = entityID.get();
471 auto_ptr_char reqID(logoutRequest->getID());
473 parammap["ID"] = reqID.get();
474 pair<bool,long> result = notifyFrontChannel(application, request, response, ¶mmap);
479 // For back-channel requests, or if no front-channel notification is needed...
480 bool worked1 = false,worked2 = false;
481 worked1 = notifyBackChannel(application, request.getRequestURL(), sessions, false);
482 if (!session_id.empty()) {
483 // One last session to yoink...
485 cache->remove(application, request, &response);
488 catch (exception& ex) {
489 m_log.error("error removing active session (%s): %s", session_id.c_str(), ex.what());
494 logoutRequest->getID(),
495 (worked1 && worked2) ? StatusCode::SUCCESS : StatusCode::RESPONDER,
496 (worked1 && worked2) ? NULL : StatusCode::PARTIAL_LOGOUT,
499 policy.getIssuerMetadata(),
502 m_decoder->isUserAgentPresent()
506 // A LogoutResponse completes an SP-initiated logout sequence.
507 const LogoutResponse* logoutResponse = dynamic_cast<LogoutResponse*>(msg.get());
508 if (logoutResponse) {
509 if (!policy.isAuthenticated()) {
510 SecurityPolicyException ex("Security of LogoutResponse not established.");
511 if (policy.getIssuerMetadata())
512 annotateException(&ex, policy.getIssuerMetadata()); // throws it
515 checkError(logoutResponse, policy.getIssuerMetadata()); // throws if Status doesn't look good...
517 // Return template for completion of global logout, or redirect to homeURL.
518 return sendLogoutPage(application, request, response, false, "Global logout completed.");
521 FatalProfileException ex("Incoming message was not a samlp:LogoutRequest or samlp:LogoutResponse.");
522 if (policy.getIssuerMetadata())
523 annotateException(&ex, policy.getIssuerMetadata()); // throws it
525 return make_pair(false,0L); // never happen, satisfies compiler
527 throw ConfigurationException("Cannot process logout message using lite version of shibsp library.");
533 pair<bool,long> SAML2Logout::sendResponse(
534 const XMLCh* requestID,
536 const XMLCh* subcode,
538 const char* relayState,
539 const RoleDescriptor* role,
540 const Application& application,
541 HTTPResponse& httpResponse,
545 // Get endpoint and encoder to use.
546 const EndpointType* ep = NULL;
547 const MessageEncoder* encoder = NULL;
549 const IDPSSODescriptor* idp = dynamic_cast<const IDPSSODescriptor*>(role);
550 for (vector<const XMLCh*>::const_iterator b = m_bindings.begin(); idp && b!=m_bindings.end(); ++b) {
551 if (ep=EndpointManager<SingleLogoutService>(idp->getSingleLogoutServices()).getByBinding(*b)) {
552 map<const XMLCh*,MessageEncoder*>::const_iterator enc = m_encoders.find(*b);
553 if (enc!=m_encoders.end())
554 encoder = enc->second;
558 if (!ep || !encoder) {
559 auto_ptr_char id(dynamic_cast<EntityDescriptor*>(role->getParent())->getEntityID());
560 m_log.error("unable to locate compatible SLO service for provider (%s)", id.get());
561 MetadataException ex("Unable to locate endpoint at IdP ($entityID) to send LogoutResponse.");
562 annotateException(&ex, role); // throws it
566 encoder = m_encoders.begin()->second;
570 auto_ptr<LogoutResponse> logout(LogoutResponseBuilder::buildLogoutResponse());
571 logout->setInResponseTo(requestID);
573 const XMLCh* loc = ep->getResponseLocation();
575 loc = ep->getLocation();
576 logout->setDestination(loc);
578 Issuer* issuer = IssuerBuilder::buildIssuer();
579 logout->setIssuer(issuer);
580 issuer->setName(application.getXMLString("entityID").second);
581 fillStatus(*logout.get(), code, subcode, msg);
583 auto_ptr_char dest(logout->getDestination());
585 long ret = sendMessage(*encoder, logout.get(), relayState, dest.get(), role, application, httpResponse);
586 logout.release(); // freed by encoder
587 return make_pair(true,ret);