2 * Copyright 2001-2010 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 "handler/AbstractHandler.h"
29 #include "handler/LogoutHandler.h"
32 # include "binding/SOAPClient.h"
33 # include "metadata/MetadataProviderCriteria.h"
34 # include "security/SecurityPolicy.h"
35 # include <saml/exceptions.h>
36 # include <saml/SAMLConfig.h>
37 # include <saml/saml2/core/Protocols.h>
38 # include <saml/saml2/binding/SAML2SOAPClient.h>
39 # include <saml/saml2/metadata/EndpointManager.h>
40 # include <saml/saml2/metadata/Metadata.h>
41 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
42 using namespace opensaml::saml2;
43 using namespace opensaml::saml2p;
44 using namespace opensaml::saml2md;
45 using namespace opensaml;
47 # include "lite/SAMLConstants.h"
50 using namespace shibsp;
51 using namespace xmltooling;
56 #if defined (_MSC_VER)
57 #pragma warning( push )
58 #pragma warning( disable : 4250 )
61 class SHIBSP_DLLLOCAL SAML2LogoutInitiator : public AbstractHandler, public LogoutHandler
64 SAML2LogoutInitiator(const DOMElement* e, const char* appId);
65 virtual ~SAML2LogoutInitiator() {
67 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
68 XMLString::release(&m_outgoing);
69 for_each(m_encoders.begin(), m_encoders.end(), cleanup_pair<const XMLCh*,MessageEncoder>());
74 void setParent(const PropertySet* parent);
75 void receive(DDF& in, ostream& out);
76 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
79 const char* getType() const {
80 return "LogoutInitiator";
85 pair<bool,long> doRequest(
86 const Application& application, const HTTPRequest& request, HTTPResponse& httpResponse, Session* session
91 LogoutRequest* buildRequest(
92 const Application& application, const Session& session, const RoleDescriptor& role, const MessageEncoder* encoder=nullptr
96 vector<const XMLCh*> m_bindings;
97 map<const XMLCh*,MessageEncoder*> m_encoders;
99 auto_ptr_char m_protocol;
102 #if defined (_MSC_VER)
103 #pragma warning( pop )
106 Handler* SHIBSP_DLLLOCAL SAML2LogoutInitiatorFactory(const pair<const DOMElement*,const char*>& p)
108 return new SAML2LogoutInitiator(p.first, p.second);
112 SAML2LogoutInitiator::SAML2LogoutInitiator(const DOMElement* e, const char* appId)
113 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".LogoutInitiator.SAML2")), m_appId(appId),
117 m_protocol(samlconstants::SAML20P_NS)
120 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
121 // Handle outgoing binding setup.
122 pair<bool,const XMLCh*> outgoing = getXMLString("outgoingBindings");
123 if (outgoing.first) {
124 m_outgoing = XMLString::replicate(outgoing.second);
125 XMLString::trim(m_outgoing);
128 // No override, so we'll install a default binding precedence.
129 string prec = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
130 samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
131 m_outgoing = XMLString::transcode(prec.c_str());
135 XMLCh* start = m_outgoing;
136 while (start && *start) {
137 pos = XMLString::indexOf(start,chSpace);
139 *(start + pos)=chNull;
140 m_bindings.push_back(start);
142 auto_ptr_char b(start);
143 MessageEncoder * encoder =
144 SAMLConfig::getConfig().MessageEncoderManager.newPlugin(b.get(),pair<const DOMElement*,const XMLCh*>(e,nullptr));
145 if (encoder->isUserAgentPresent()) {
146 m_encoders[start] = encoder;
147 m_log.debug("supporting outgoing binding (%s)", b.get());
151 m_log.warn("skipping outgoing binding (%s), not a front-channel mechanism", b.get());
154 catch (exception& ex) {
155 m_log.error("error building MessageEncoder: %s", ex.what());
158 start = start + pos + 1;
165 pair<bool,const char*> loc = getString("Location");
167 string address = m_appId + loc.second + "::run::SAML2LI";
168 setAddress(address.c_str());
172 void SAML2LogoutInitiator::setParent(const PropertySet* parent)
174 DOMPropertySet::setParent(parent);
175 pair<bool,const char*> loc = getString("Location");
177 string address = m_appId + loc.second + "::run::SAML2LI";
178 setAddress(address.c_str());
181 m_log.warn("no Location property in SAML2 LogoutInitiator (or parent), can't register as remoted handler");
185 pair<bool,long> SAML2LogoutInitiator::run(SPRequest& request, bool isHandler) const
187 // Defer to base class for front-channel loop first.
188 pair<bool,long> ret = LogoutHandler::run(request, isHandler);
192 // At this point we know the front-channel is handled.
193 // We need the session to do any other work.
195 Session* session = nullptr;
197 session = request.getSession(false, true, false); // don't cache it and ignore all checks
199 return make_pair(false,0L);
201 // We only handle SAML 2.0 sessions.
202 if (!XMLString::equals(session->getProtocol(), m_protocol.get())) {
204 return make_pair(false,0L);
207 catch (exception& ex) {
208 m_log.error("error accessing current session: %s", ex.what());
209 return make_pair(false,0L);
212 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
213 // When out of process, we run natively.
214 return doRequest(request.getApplication(), request, request, session);
217 // When not out of process, we remote the request.
219 vector<string> headers(1,"Cookie");
220 DDF out,in = wrap(request,&headers);
221 DDFJanitor jin(in), jout(out);
222 out=request.getServiceProvider().getListenerService()->send(in);
223 return unwrap(request, out);
227 void SAML2LogoutInitiator::receive(DDF& in, ostream& out)
230 // Defer to base class for notifications
231 if (in["notify"].integer() == 1)
232 return LogoutHandler::receive(in, out);
235 const char* aid=in["application_id"].string();
236 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
238 // Something's horribly wrong.
239 m_log.error("couldn't find application (%s) for logout", aid ? aid : "(missing)");
240 throw ConfigurationException("Unable to locate application for logout, deleted?");
243 // Unpack the request.
244 auto_ptr<HTTPRequest> req(getRequest(in));
246 // Set up a response shim.
248 DDFJanitor jout(ret);
249 auto_ptr<HTTPResponse> resp(getResponse(ret));
251 Session* session = nullptr;
253 session = app->getServiceProvider().getSessionCache()->find(*app, *req.get(), nullptr, nullptr);
255 catch (exception& ex) {
256 m_log.error("error accessing current session: %s", ex.what());
259 // With no session, we just skip the request and let it fall through to an empty struct return.
261 if (session->getNameID() && session->getEntityID()) {
262 // Since we're remoted, the result should either be a throw, which we pass on,
263 // a false/0 return, which we just return as an empty structure, or a response/redirect,
264 // which we capture in the facade and send back.
265 doRequest(*app, *req.get(), *resp.get(), session);
268 m_log.log(getParent() ? Priority::WARN : Priority::ERROR, "bypassing SAML 2.0 logout, no NameID or issuing entityID found in session");
270 app->getServiceProvider().getSessionCache()->remove(*app, *req.get(), resp.get());
275 throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
279 pair<bool,long> SAML2LogoutInitiator::doRequest(
280 const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse, Session* session
283 // Do back channel notification.
284 vector<string> sessions(1, session->getID());
285 if (!notifyBackChannel(application, httpRequest.getRequestURL(), sessions, false)) {
287 application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
288 return sendLogoutPage(application, httpRequest, httpResponse, "partial");
292 pair<bool,long> ret = make_pair(false,0L);
294 // With a session in hand, we can create a LogoutRequest message, if we can find a compatible endpoint.
295 MetadataProvider* m = application.getMetadataProvider();
296 Locker metadataLocker(m);
297 MetadataProviderCriteria mc(application, session->getEntityID(), &IDPSSODescriptor::ELEMENT_QNAME, samlconstants::SAML20P_NS);
298 pair<const EntityDescriptor*,const RoleDescriptor*> entity = m->getEntityDescriptor(mc);
300 throw MetadataException(
301 "Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", session->getEntityID())
304 else if (!entity.second) {
305 throw MetadataException(
306 "Unable to locate SAML 2.0 IdP role for identity provider ($entityID).", namedparams(1, "entityID", session->getEntityID())
310 const IDPSSODescriptor* role = dynamic_cast<const IDPSSODescriptor*>(entity.second);
311 if (role->getSingleLogoutServices().empty()) {
312 throw MetadataException(
313 "No SingleLogoutService endpoints in metadata for identity provider ($entityID).", namedparams(1, "entityID", session->getEntityID())
317 const EndpointType* ep=nullptr;
318 const MessageEncoder* encoder=nullptr;
319 vector<const XMLCh*>::const_iterator b;
320 for (b = m_bindings.begin(); b!=m_bindings.end(); ++b) {
321 if (ep=EndpointManager<SingleLogoutService>(role->getSingleLogoutServices()).getByBinding(*b)) {
322 map<const XMLCh*,MessageEncoder*>::const_iterator enc = m_encoders.find(*b);
323 if (enc!=m_encoders.end())
324 encoder = enc->second;
328 if (!ep || !encoder) {
329 m_log.debug("no compatible front channel SingleLogoutService, trying back channel...");
330 shibsp::SecurityPolicy policy(application);
331 shibsp::SOAPClient soaper(policy);
332 MetadataCredentialCriteria mcc(*role);
334 LogoutResponse* logoutResponse=nullptr;
335 auto_ptr_XMLCh binding(samlconstants::SAML20_BINDING_SOAP);
336 const vector<SingleLogoutService*>& endpoints=role->getSingleLogoutServices();
337 for (vector<SingleLogoutService*>::const_iterator epit=endpoints.begin(); !logoutResponse && epit!=endpoints.end(); ++epit) {
339 if (!XMLString::equals((*epit)->getBinding(),binding.get()))
341 LogoutRequest* msg = buildRequest(application, *session, *role);
342 auto_ptr_char dest((*epit)->getLocation());
344 SAML2SOAPClient client(soaper, false);
345 client.sendSAML(msg, application.getId(), mcc, dest.get());
346 StatusResponseType* srt = client.receiveSAML();
347 if (!(logoutResponse = dynamic_cast<LogoutResponse*>(srt))) {
352 catch (exception& ex) {
353 m_log.error("error sending LogoutRequest message: %s", ex.what());
359 if (!logoutResponse) {
360 if (endpoints.empty())
361 m_log.info("IdP doesn't support single logout protocol over a compatible binding");
363 m_log.warn("IdP didn't respond to logout request");
364 ret = sendLogoutPage(application, httpRequest, httpResponse, "partial");
367 // Check the status, looking for non-success or a partial logout code.
368 const StatusCode* sc = logoutResponse->getStatus() ? logoutResponse->getStatus()->getStatusCode() : nullptr;
369 bool partial = (!sc || !XMLString::equals(sc->getValue(), StatusCode::SUCCESS));
370 if (!partial && sc->getStatusCode()) {
371 // Success, but still need to check for partial.
372 partial = XMLString::equals(sc->getStatusCode()->getValue(), StatusCode::PARTIAL_LOGOUT);
374 delete logoutResponse;
376 ret = sendLogoutPage(application, httpRequest, httpResponse, "partial");
378 const char* returnloc = httpRequest.getParameter("return");
380 ret.second = httpResponse.sendRedirect(returnloc);
383 ret = sendLogoutPage(application, httpRequest, httpResponse, "global");
390 application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
396 // Save off return location as RelayState.
398 const char* returnloc = httpRequest.getParameter("return");
400 relayState = returnloc;
401 preserveRelayState(application, httpResponse, relayState);
404 auto_ptr<LogoutRequest> msg(buildRequest(application, *session, *role, encoder));
406 msg->setDestination(ep->getLocation());
407 auto_ptr_char dest(ep->getLocation());
408 ret.second = sendMessage(*encoder, msg.get(), relayState.c_str(), dest.get(), role, application, httpResponse);
410 msg.release(); // freed by encoder
412 catch (exception& ex) {
413 m_log.error("error issuing SAML 2.0 logout request: %s", ex.what());
419 application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
425 application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
426 throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
432 LogoutRequest* SAML2LogoutInitiator::buildRequest(
433 const Application& application, const Session& session, const RoleDescriptor& role, const MessageEncoder* encoder
436 const PropertySet* relyingParty = application.getRelyingParty(dynamic_cast<EntityDescriptor*>(role.getParent()));
438 auto_ptr<LogoutRequest> msg(LogoutRequestBuilder::buildLogoutRequest());
439 Issuer* issuer = IssuerBuilder::buildIssuer();
440 msg->setIssuer(issuer);
441 issuer->setName(relyingParty->getXMLString("entityID").second);
442 auto_ptr_XMLCh index(session.getSessionIndex());
443 if (index.get() && *index.get()) {
444 SessionIndex* si = SessionIndexBuilder::buildSessionIndex();
445 msg->getSessionIndexs().push_back(si);
446 si->setSessionIndex(index.get());
449 const NameID* nameid = session.getNameID();
450 pair<bool,const char*> flag = relyingParty->getString("encryption");
452 (!strcmp(flag.second, "true") || (encoder && !strcmp(flag.second, "front")) || (!encoder && !strcmp(flag.second, "back")))) {
453 auto_ptr<EncryptedID> encrypted(EncryptedIDBuilder::buildEncryptedID());
454 MetadataCredentialCriteria mcc(role);
457 *(application.getMetadataProvider()),
459 encoder ? encoder->isCompact() : false,
460 relyingParty->getXMLString("encryptionAlg").second
462 msg->setEncryptedID(encrypted.release());
465 msg->setNameID(nameid->cloneNameID());
468 return msg.release();