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 # include <saml/signature/ContentReference.h>
44 # include <xmltooling/security/Credential.h>
45 # include <xmltooling/signature/Signature.h>
46 using namespace opensaml::saml2;
47 using namespace opensaml::saml2p;
48 using namespace opensaml::saml2md;
49 using namespace opensaml;
51 # include "lite/SAMLConstants.h"
54 using namespace shibsp;
55 using namespace xmltooling;
60 #if defined (_MSC_VER)
61 #pragma warning( push )
62 #pragma warning( disable : 4250 )
65 class SHIBSP_DLLLOCAL SAML2LogoutInitiator : public AbstractHandler, public LogoutHandler
68 SAML2LogoutInitiator(const DOMElement* e, const char* appId);
69 virtual ~SAML2LogoutInitiator() {
71 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
72 XMLString::release(&m_outgoing);
73 for_each(m_encoders.begin(), m_encoders.end(), cleanup_pair<const XMLCh*,MessageEncoder>());
78 void setParent(const PropertySet* parent);
79 void receive(DDF& in, ostream& out);
80 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
83 const char* getType() const {
84 return "LogoutInitiator";
89 pair<bool,long> doRequest(
90 const Application& application, const HTTPRequest& request, HTTPResponse& httpResponse, Session* session
95 LogoutRequest* buildRequest(
96 const Application& application, const Session& session, const RoleDescriptor& role, const MessageEncoder* encoder=NULL
100 vector<const XMLCh*> m_bindings;
101 map<const XMLCh*,MessageEncoder*> m_encoders;
103 auto_ptr_char m_protocol;
106 #if defined (_MSC_VER)
107 #pragma warning( pop )
110 Handler* SHIBSP_DLLLOCAL SAML2LogoutInitiatorFactory(const pair<const DOMElement*,const char*>& p)
112 return new SAML2LogoutInitiator(p.first, p.second);
116 SAML2LogoutInitiator::SAML2LogoutInitiator(const DOMElement* e, const char* appId)
117 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".LogoutInitiator.SAML2")), m_appId(appId),
121 m_protocol(samlconstants::SAML20P_NS)
124 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
125 // Handle outgoing binding setup.
126 pair<bool,const XMLCh*> outgoing = getXMLString("outgoingBindings");
127 if (outgoing.first) {
128 m_outgoing = XMLString::replicate(outgoing.second);
129 XMLString::trim(m_outgoing);
132 // No override, so we'll install a default binding precedence.
133 string prec = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
134 samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
135 m_outgoing = XMLString::transcode(prec.c_str());
139 XMLCh* start = m_outgoing;
140 while (start && *start) {
141 pos = XMLString::indexOf(start,chSpace);
143 *(start + pos)=chNull;
144 m_bindings.push_back(start);
146 auto_ptr_char b(start);
147 MessageEncoder * encoder =
148 SAMLConfig::getConfig().MessageEncoderManager.newPlugin(b.get(),pair<const DOMElement*,const XMLCh*>(e,NULL));
149 if (encoder->isUserAgentPresent()) {
150 m_encoders[start] = encoder;
151 m_log.debug("supporting outgoing binding (%s)", b.get());
155 m_log.warn("skipping outgoing binding (%s), not a front-channel mechanism", b.get());
158 catch (exception& ex) {
159 m_log.error("error building MessageEncoder: %s", ex.what());
162 start = start + pos + 1;
169 pair<bool,const char*> loc = getString("Location");
171 string address = m_appId + loc.second + "::run::SAML2LI";
172 setAddress(address.c_str());
176 void SAML2LogoutInitiator::setParent(const PropertySet* parent)
178 DOMPropertySet::setParent(parent);
179 pair<bool,const char*> loc = getString("Location");
181 string address = m_appId + loc.second + "::run::SAML2LI";
182 setAddress(address.c_str());
185 m_log.warn("no Location property in SAML2 LogoutInitiator (or parent), can't register as remoted handler");
189 pair<bool,long> SAML2LogoutInitiator::run(SPRequest& request, bool isHandler) const
191 // Defer to base class for front-channel loop first.
192 pair<bool,long> ret = LogoutHandler::run(request, isHandler);
196 // At this point we know the front-channel is handled.
197 // We need the session to do any other work.
199 Session* session = NULL;
201 session = request.getSession(false, true, false); // don't cache it and ignore all checks
203 return make_pair(false,0L);
205 // We only handle SAML 2.0 sessions.
206 if (!XMLString::equals(session->getProtocol(), m_protocol.get())) {
208 return make_pair(false,0L);
211 catch (exception& ex) {
212 m_log.error("error accessing current session: %s", ex.what());
213 return make_pair(false,0L);
216 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
217 // When out of process, we run natively.
218 return doRequest(request.getApplication(), request, request, session);
221 // When not out of process, we remote the request.
223 vector<string> headers(1,"Cookie");
224 DDF out,in = wrap(request,&headers);
225 DDFJanitor jin(in), jout(out);
226 out=request.getServiceProvider().getListenerService()->send(in);
227 return unwrap(request, out);
231 void SAML2LogoutInitiator::receive(DDF& in, ostream& out)
234 // Defer to base class for notifications
235 if (in["notify"].integer() == 1)
236 return LogoutHandler::receive(in, out);
239 const char* aid=in["application_id"].string();
240 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
242 // Something's horribly wrong.
243 m_log.error("couldn't find application (%s) for logout", aid ? aid : "(missing)");
244 throw ConfigurationException("Unable to locate application for logout, deleted?");
247 // Unpack the request.
248 auto_ptr<HTTPRequest> req(getRequest(in));
250 // Set up a response shim.
252 DDFJanitor jout(ret);
253 auto_ptr<HTTPResponse> resp(getResponse(ret));
255 Session* session = NULL;
257 session = app->getServiceProvider().getSessionCache()->find(*app, *req.get(), NULL, NULL);
259 catch (exception& ex) {
260 m_log.error("error accessing current session: %s", ex.what());
263 // With no session, we just skip the request and let it fall through to an empty struct return.
265 if (session->getNameID() && session->getEntityID()) {
266 // Since we're remoted, the result should either be a throw, which we pass on,
267 // a false/0 return, which we just return as an empty structure, or a response/redirect,
268 // which we capture in the facade and send back.
269 doRequest(*app, *req.get(), *resp.get(), session);
272 m_log.error("no NameID or issuing entityID found in session");
274 app->getServiceProvider().getSessionCache()->remove(*app, *req.get(), resp.get());
279 throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
283 pair<bool,long> SAML2LogoutInitiator::doRequest(
284 const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse, Session* session
287 // Do back channel notification.
288 vector<string> sessions(1, session->getID());
289 if (!notifyBackChannel(application, httpRequest.getRequestURL(), sessions, false)) {
291 application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
292 return sendLogoutPage(application, httpRequest, httpResponse, "partial");
296 pair<bool,long> ret = make_pair(false,0L);
298 // With a session in hand, we can create a LogoutRequest message, if we can find a compatible endpoint.
299 MetadataProvider* m = application.getMetadataProvider();
300 Locker metadataLocker(m);
301 MetadataProviderCriteria mc(application, session->getEntityID(), &IDPSSODescriptor::ELEMENT_QNAME, samlconstants::SAML20P_NS);
302 pair<const EntityDescriptor*,const RoleDescriptor*> entity = m->getEntityDescriptor(mc);
304 throw MetadataException(
305 "Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", session->getEntityID())
308 else if (!entity.second) {
309 throw MetadataException(
310 "Unable to locate SAML 2.0 IdP role for identity provider ($entityID).", namedparams(1, "entityID", session->getEntityID())
314 const IDPSSODescriptor* role = dynamic_cast<const IDPSSODescriptor*>(entity.second);
315 const EndpointType* ep=NULL;
316 const MessageEncoder* encoder=NULL;
317 vector<const XMLCh*>::const_iterator b;
318 for (b = m_bindings.begin(); b!=m_bindings.end(); ++b) {
319 if (ep=EndpointManager<SingleLogoutService>(role->getSingleLogoutServices()).getByBinding(*b)) {
320 map<const XMLCh*,MessageEncoder*>::const_iterator enc = m_encoders.find(*b);
321 if (enc!=m_encoders.end())
322 encoder = enc->second;
326 if (!ep || !encoder) {
327 m_log.debug("no compatible front channel SingleLogoutService, trying back channel...");
328 shibsp::SecurityPolicy policy(application);
329 shibsp::SOAPClient soaper(policy);
330 MetadataCredentialCriteria mcc(*role);
332 LogoutResponse* logoutResponse=NULL;
333 auto_ptr_XMLCh binding(samlconstants::SAML20_BINDING_SOAP);
334 const vector<SingleLogoutService*>& endpoints=role->getSingleLogoutServices();
335 for (vector<SingleLogoutService*>::const_iterator epit=endpoints.begin(); !logoutResponse && epit!=endpoints.end(); ++epit) {
337 if (!XMLString::equals((*epit)->getBinding(),binding.get()))
339 LogoutRequest* msg = buildRequest(application, *session, *role);
340 auto_ptr_char dest((*epit)->getLocation());
342 SAML2SOAPClient client(soaper, false);
343 client.sendSAML(msg, application.getId(), mcc, dest.get());
344 StatusResponseType* srt = client.receiveSAML();
345 if (!(logoutResponse = dynamic_cast<LogoutResponse*>(srt))) {
350 catch (exception& ex) {
351 m_log.error("error sending LogoutRequest message: %s", ex.what());
357 if (!logoutResponse) {
358 if (endpoints.empty())
359 m_log.info("IdP doesn't support single logout protocol over a compatible binding");
361 m_log.warn("IdP didn't respond to logout request");
362 ret = sendLogoutPage(application, httpRequest, httpResponse, "partial");
365 // Check the status, looking for non-success or a partial logout code.
366 const StatusCode* sc = logoutResponse->getStatus() ? logoutResponse->getStatus()->getStatusCode() : NULL;
367 bool partial = (!sc || !XMLString::equals(sc->getValue(), StatusCode::SUCCESS));
369 // Success, but still need to check for partial.
370 partial = XMLString::equals(sc->getStatusCode()->getValue(), StatusCode::PARTIAL_LOGOUT);
372 delete logoutResponse;
374 ret = sendLogoutPage(application, httpRequest, httpResponse, "partial");
376 const char* returnloc = httpRequest.getParameter("return");
378 ret.second = httpResponse.sendRedirect(returnloc);
381 ret = sendLogoutPage(application, httpRequest, httpResponse, "global");
387 application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
392 // Save off return location as RelayState.
394 const char* returnloc = httpRequest.getParameter("return");
396 relayState = returnloc;
397 preserveRelayState(application, httpResponse, relayState);
400 auto_ptr<LogoutRequest> msg(buildRequest(application, *session, *role, encoder));
402 msg->setDestination(ep->getLocation());
403 auto_ptr_char dest(ep->getLocation());
404 ret.second = sendMessage(*encoder, msg.get(), relayState.c_str(), dest.get(), role, application, httpResponse);
406 msg.release(); // freed by encoder
408 catch (exception& ex) {
409 m_log.error("error issuing SAML 2.0 logout request: %s", ex.what());
415 application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
421 application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
422 throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
428 LogoutRequest* SAML2LogoutInitiator::buildRequest(
429 const Application& application, const Session& session, const RoleDescriptor& role, const MessageEncoder* encoder
432 const PropertySet* relyingParty = application.getRelyingParty(dynamic_cast<EntityDescriptor*>(role.getParent()));
434 auto_ptr<LogoutRequest> msg(LogoutRequestBuilder::buildLogoutRequest());
435 Issuer* issuer = IssuerBuilder::buildIssuer();
436 msg->setIssuer(issuer);
437 issuer->setName(relyingParty->getXMLString("entityID").second);
438 auto_ptr_XMLCh index(session.getSessionIndex());
439 if (index.get() && *index.get()) {
440 SessionIndex* si = SessionIndexBuilder::buildSessionIndex();
441 msg->getSessionIndexs().push_back(si);
442 si->setSessionIndex(index.get());
445 const NameID* nameid = session.getNameID();
446 pair<bool,const char*> flag = relyingParty->getString("encryption");
448 (!strcmp(flag.second, "true") || (encoder && !strcmp(flag.second, "front")) || (!encoder && !strcmp(flag.second, "back")))) {
449 auto_ptr<EncryptedID> encrypted(EncryptedIDBuilder::buildEncryptedID());
450 MetadataCredentialCriteria mcc(role);
453 *(application.getMetadataProvider()),
455 encoder ? encoder->isCompact() : false,
456 relyingParty->getXMLString("encryptionAlg").second
458 msg->setEncryptedID(encrypted.release());
461 msg->setNameID(nameid->cloneNameID());
465 // No encoder being used, so sign for SOAP client manually.
466 flag = relyingParty->getString("signing");
467 if (flag.first && (!strcmp(flag.second, "true") || !strcmp(flag.second, "back"))) {
468 CredentialResolver* credResolver=application.getCredentialResolver();
470 Locker credLocker(credResolver);
471 // Fill in criteria to use.
472 MetadataCredentialCriteria mcc(role);
473 mcc.setUsage(Credential::SIGNING_CREDENTIAL);
474 pair<bool,const char*> keyName = relyingParty->getString("keyName");
476 mcc.getKeyNames().insert(keyName.second);
477 pair<bool,const XMLCh*> sigalg = relyingParty->getXMLString("signingAlg");
479 mcc.setXMLAlgorithm(sigalg.second);
480 const Credential* cred = credResolver->resolve(&mcc);
482 xmlsignature::Signature* sig = xmlsignature::SignatureBuilder::buildSignature();
483 msg->setSignature(sig);
485 sig->setSignatureAlgorithm(sigalg.second);
486 sigalg = relyingParty->getXMLString("digestAlg");
488 ContentReference* cr = dynamic_cast<ContentReference*>(sig->getContentReference());
490 cr->setDigestAlgorithm(sigalg.second);
493 // Sign response while marshalling.
494 vector<xmlsignature::Signature*> sigs(1,sig);
495 msg->marshall((DOMDocument*)NULL,&sigs,cred);
498 m_log.warn("no signing credential resolved, leaving message unsigned");
502 m_log.warn("no credential resolver installed, leaving message unsigned");
507 return msg.release();