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.
18 * SAML2LogoutInitiator.cpp
20 * Triggers SP-initiated logout for SAML 2.0 sessions.
24 #include "exceptions.h"
25 #include "Application.h"
26 #include "ServiceProvider.h"
27 #include "SessionCache.h"
28 #include "SPRequest.h"
29 #include "handler/AbstractHandler.h"
30 #include "handler/LogoutHandler.h"
33 # include "binding/SOAPClient.h"
34 # include "metadata/MetadataProviderCriteria.h"
35 # include "security/SecurityPolicy.h"
36 # include <saml/exceptions.h>
37 # include <saml/SAMLConfig.h>
38 # include <saml/saml2/core/Protocols.h>
39 # include <saml/saml2/binding/SAML2SOAPClient.h>
40 # include <saml/saml2/metadata/EndpointManager.h>
41 # include <saml/saml2/metadata/Metadata.h>
42 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
43 using namespace opensaml::saml2;
44 using namespace opensaml::saml2p;
45 using namespace opensaml::saml2md;
46 using namespace opensaml;
48 # include "lite/SAMLConstants.h"
51 using namespace shibsp;
52 using namespace xmltooling;
57 #if defined (_MSC_VER)
58 #pragma warning( push )
59 #pragma warning( disable : 4250 )
62 class SHIBSP_DLLLOCAL SAML2LogoutInitiator : public AbstractHandler, public LogoutHandler
65 SAML2LogoutInitiator(const DOMElement* e, const char* appId);
66 virtual ~SAML2LogoutInitiator() {
68 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
69 XMLString::release(&m_outgoing);
70 for_each(m_encoders.begin(), m_encoders.end(), cleanup_pair<const XMLCh*,MessageEncoder>());
75 void setParent(const PropertySet* parent);
76 void receive(DDF& in, ostream& out);
77 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
80 const char* getType() const {
81 return "LogoutInitiator";
86 pair<bool,long> doRequest(
87 const Application& application, const HTTPRequest& request, HTTPResponse& httpResponse, Session* session
92 LogoutRequest* buildRequest(
93 const Application& application, const Session& session, const RoleDescriptor& role, const MessageEncoder* encoder=NULL
97 vector<const XMLCh*> m_bindings;
98 map<const XMLCh*,MessageEncoder*> m_encoders;
100 auto_ptr_char m_protocol;
103 #if defined (_MSC_VER)
104 #pragma warning( pop )
107 Handler* SHIBSP_DLLLOCAL SAML2LogoutInitiatorFactory(const pair<const DOMElement*,const char*>& p)
109 return new SAML2LogoutInitiator(p.first, p.second);
113 SAML2LogoutInitiator::SAML2LogoutInitiator(const DOMElement* e, const char* appId)
114 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".LogoutInitiator.SAML2")), m_appId(appId),
118 m_protocol(samlconstants::SAML20P_NS)
121 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
122 // Handle outgoing binding setup.
123 pair<bool,const XMLCh*> outgoing = getXMLString("outgoingBindings");
124 if (outgoing.first) {
125 m_outgoing = XMLString::replicate(outgoing.second);
126 XMLString::trim(m_outgoing);
129 // No override, so we'll install a default binding precedence.
130 string prec = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
131 samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
132 m_outgoing = XMLString::transcode(prec.c_str());
136 XMLCh* start = m_outgoing;
137 while (start && *start) {
138 pos = XMLString::indexOf(start,chSpace);
140 *(start + pos)=chNull;
141 m_bindings.push_back(start);
143 auto_ptr_char b(start);
144 MessageEncoder * encoder =
145 SAMLConfig::getConfig().MessageEncoderManager.newPlugin(b.get(),pair<const DOMElement*,const XMLCh*>(e,NULL));
146 if (encoder->isUserAgentPresent()) {
147 m_encoders[start] = encoder;
148 m_log.debug("supporting outgoing binding (%s)", b.get());
152 m_log.warn("skipping outgoing binding (%s), not a front-channel mechanism", b.get());
155 catch (exception& ex) {
156 m_log.error("error building MessageEncoder: %s", ex.what());
159 start = start + pos + 1;
166 pair<bool,const char*> loc = getString("Location");
168 string address = m_appId + loc.second + "::run::SAML2LI";
169 setAddress(address.c_str());
173 void SAML2LogoutInitiator::setParent(const PropertySet* parent)
175 DOMPropertySet::setParent(parent);
176 pair<bool,const char*> loc = getString("Location");
178 string address = m_appId + loc.second + "::run::SAML2LI";
179 setAddress(address.c_str());
182 m_log.warn("no Location property in SAML2 LogoutInitiator (or parent), can't register as remoted handler");
186 pair<bool,long> SAML2LogoutInitiator::run(SPRequest& request, bool isHandler) const
188 // Defer to base class for front-channel loop first.
189 pair<bool,long> ret = LogoutHandler::run(request, isHandler);
193 // At this point we know the front-channel is handled.
194 // We need the session to do any other work.
196 Session* session = NULL;
198 session = request.getSession(false, true, false); // don't cache it and ignore all checks
200 return make_pair(false,0L);
202 // We only handle SAML 2.0 sessions.
203 if (!XMLString::equals(session->getProtocol(), m_protocol.get())) {
205 return make_pair(false,0L);
208 catch (exception& ex) {
209 m_log.error("error accessing current session: %s", ex.what());
210 return make_pair(false,0L);
213 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
214 // When out of process, we run natively.
215 return doRequest(request.getApplication(), request, request, session);
218 // When not out of process, we remote the request.
220 vector<string> headers(1,"Cookie");
221 DDF out,in = wrap(request,&headers);
222 DDFJanitor jin(in), jout(out);
223 out=request.getServiceProvider().getListenerService()->send(in);
224 return unwrap(request, out);
228 void SAML2LogoutInitiator::receive(DDF& in, ostream& out)
231 // Defer to base class for notifications
232 if (in["notify"].integer() == 1)
233 return LogoutHandler::receive(in, out);
236 const char* aid=in["application_id"].string();
237 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
239 // Something's horribly wrong.
240 m_log.error("couldn't find application (%s) for logout", aid ? aid : "(missing)");
241 throw ConfigurationException("Unable to locate application for logout, deleted?");
244 // Unpack the request.
245 auto_ptr<HTTPRequest> req(getRequest(in));
247 // Set up a response shim.
249 DDFJanitor jout(ret);
250 auto_ptr<HTTPResponse> resp(getResponse(ret));
252 Session* session = NULL;
254 session = app->getServiceProvider().getSessionCache()->find(*app, *req.get(), NULL, NULL);
256 catch (exception& ex) {
257 m_log.error("error accessing current session: %s", ex.what());
260 // With no session, we just skip the request and let it fall through to an empty struct return.
262 if (session->getNameID() && session->getEntityID()) {
263 // Since we're remoted, the result should either be a throw, which we pass on,
264 // a false/0 return, which we just return as an empty structure, or a response/redirect,
265 // which we capture in the facade and send back.
266 doRequest(*app, *req.get(), *resp.get(), session);
269 m_log.error("no NameID or issuing entityID found in session");
271 app->getServiceProvider().getSessionCache()->remove(*app, *req.get(), resp.get());
276 throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
280 pair<bool,long> SAML2LogoutInitiator::doRequest(
281 const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse, Session* session
284 // Do back channel notification.
285 vector<string> sessions(1, session->getID());
286 if (!notifyBackChannel(application, httpRequest.getRequestURL(), sessions, false)) {
288 application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
289 return sendLogoutPage(application, httpRequest, httpResponse, "partial");
293 pair<bool,long> ret = make_pair(false,0L);
295 // With a session in hand, we can create a LogoutRequest message, if we can find a compatible endpoint.
296 MetadataProvider* m = application.getMetadataProvider();
297 Locker metadataLocker(m);
298 MetadataProviderCriteria mc(application, session->getEntityID(), &IDPSSODescriptor::ELEMENT_QNAME, samlconstants::SAML20P_NS);
299 pair<const EntityDescriptor*,const RoleDescriptor*> entity = m->getEntityDescriptor(mc);
301 throw MetadataException(
302 "Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", session->getEntityID())
305 else if (!entity.second) {
306 throw MetadataException(
307 "Unable to locate SAML 2.0 IdP role for identity provider ($entityID).", namedparams(1, "entityID", session->getEntityID())
311 const IDPSSODescriptor* role = dynamic_cast<const IDPSSODescriptor*>(entity.second);
312 const EndpointType* ep=NULL;
313 const MessageEncoder* encoder=NULL;
314 vector<const XMLCh*>::const_iterator b;
315 for (b = m_bindings.begin(); b!=m_bindings.end(); ++b) {
316 if (ep=EndpointManager<SingleLogoutService>(role->getSingleLogoutServices()).getByBinding(*b)) {
317 map<const XMLCh*,MessageEncoder*>::const_iterator enc = m_encoders.find(*b);
318 if (enc!=m_encoders.end())
319 encoder = enc->second;
323 if (!ep || !encoder) {
324 m_log.debug("no compatible front channel SingleLogoutService, trying back channel...");
325 shibsp::SecurityPolicy policy(application);
326 shibsp::SOAPClient soaper(policy);
327 MetadataCredentialCriteria mcc(*role);
329 LogoutResponse* logoutResponse=NULL;
330 auto_ptr_XMLCh binding(samlconstants::SAML20_BINDING_SOAP);
331 const vector<SingleLogoutService*>& endpoints=role->getSingleLogoutServices();
332 for (vector<SingleLogoutService*>::const_iterator epit=endpoints.begin(); !logoutResponse && epit!=endpoints.end(); ++epit) {
334 if (!XMLString::equals((*epit)->getBinding(),binding.get()))
336 LogoutRequest* msg = buildRequest(application, *session, *role);
337 auto_ptr_char dest((*epit)->getLocation());
339 SAML2SOAPClient client(soaper, false);
340 client.sendSAML(msg, application.getId(), mcc, dest.get());
341 StatusResponseType* srt = client.receiveSAML();
342 if (!(logoutResponse = dynamic_cast<LogoutResponse*>(srt))) {
347 catch (exception& ex) {
348 m_log.error("error sending LogoutRequest message: %s", ex.what());
354 if (!logoutResponse) {
355 if (endpoints.empty())
356 m_log.info("IdP doesn't support single logout protocol over a compatible binding");
358 m_log.warn("IdP didn't respond to logout request");
359 ret = sendLogoutPage(application, httpRequest, httpResponse, "partial");
362 // Check the status, looking for non-success or a partial logout code.
363 const StatusCode* sc = logoutResponse->getStatus() ? logoutResponse->getStatus()->getStatusCode() : NULL;
364 bool partial = (!sc || !XMLString::equals(sc->getValue(), StatusCode::SUCCESS));
365 if (!partial && sc->getStatusCode()) {
366 // Success, but still need to check for partial.
367 partial = XMLString::equals(sc->getStatusCode()->getValue(), StatusCode::PARTIAL_LOGOUT);
369 delete logoutResponse;
371 ret = sendLogoutPage(application, httpRequest, httpResponse, "partial");
373 const char* returnloc = httpRequest.getParameter("return");
375 ret.second = httpResponse.sendRedirect(returnloc);
378 ret = sendLogoutPage(application, httpRequest, httpResponse, "global");
385 application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
391 // Save off return location as RelayState.
393 const char* returnloc = httpRequest.getParameter("return");
395 relayState = returnloc;
396 preserveRelayState(application, httpResponse, relayState);
399 auto_ptr<LogoutRequest> msg(buildRequest(application, *session, *role, encoder));
401 msg->setDestination(ep->getLocation());
402 auto_ptr_char dest(ep->getLocation());
403 ret.second = sendMessage(*encoder, msg.get(), relayState.c_str(), dest.get(), role, application, httpResponse);
405 msg.release(); // freed by encoder
407 catch (exception& ex) {
408 m_log.error("error issuing SAML 2.0 logout request: %s", ex.what());
414 application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
420 application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
421 throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
427 LogoutRequest* SAML2LogoutInitiator::buildRequest(
428 const Application& application, const Session& session, const RoleDescriptor& role, const MessageEncoder* encoder
431 const PropertySet* relyingParty = application.getRelyingParty(dynamic_cast<EntityDescriptor*>(role.getParent()));
433 auto_ptr<LogoutRequest> msg(LogoutRequestBuilder::buildLogoutRequest());
434 Issuer* issuer = IssuerBuilder::buildIssuer();
435 msg->setIssuer(issuer);
436 issuer->setName(relyingParty->getXMLString("entityID").second);
437 auto_ptr_XMLCh index(session.getSessionIndex());
438 if (index.get() && *index.get()) {
439 SessionIndex* si = SessionIndexBuilder::buildSessionIndex();
440 msg->getSessionIndexs().push_back(si);
441 si->setSessionIndex(index.get());
444 const NameID* nameid = session.getNameID();
445 pair<bool,const char*> flag = relyingParty->getString("encryption");
447 (!strcmp(flag.second, "true") || (encoder && !strcmp(flag.second, "front")) || (!encoder && !strcmp(flag.second, "back")))) {
448 auto_ptr<EncryptedID> encrypted(EncryptedIDBuilder::buildEncryptedID());
449 MetadataCredentialCriteria mcc(role);
452 *(application.getMetadataProvider()),
454 encoder ? encoder->isCompact() : false,
455 relyingParty->getXMLString("encryptionAlg").second
457 msg->setEncryptedID(encrypted.release());
460 msg->setNameID(nameid->cloneNameID());
463 return msg.release();