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.
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 <saml/SAMLConfig.h>
34 # include <saml/saml2/core/Protocols.h>
35 # include <saml/saml2/binding/SAML2SOAPClient.h>
36 # include <saml/saml2/metadata/EndpointManager.h>
37 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
38 using namespace opensaml::saml2;
39 using namespace opensaml::saml2p;
40 using namespace opensaml::saml2md;
41 using namespace opensaml;
43 # include "lite/SAMLConstants.h"
46 using namespace shibsp;
47 using namespace xmltooling;
52 #if defined (_MSC_VER)
53 #pragma warning( push )
54 #pragma warning( disable : 4250 )
57 class SHIBSP_DLLLOCAL SAML2LogoutInitiator : public AbstractHandler, public LogoutHandler
60 SAML2LogoutInitiator(const DOMElement* e, const char* appId);
61 virtual ~SAML2LogoutInitiator() {
63 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
64 XMLString::release(&m_outgoing);
65 for_each(m_encoders.begin(), m_encoders.end(), cleanup_pair<const XMLCh*,MessageEncoder>());
70 void setParent(const PropertySet* parent);
71 void receive(DDF& in, ostream& out);
72 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
75 const char* getType() const {
76 return "LogoutInitiator";
81 pair<bool,long> doRequest(const Application& application, const char* requestURL, Session* session, HTTPResponse& httpResponse) const;
85 LogoutRequest* buildRequest(
86 const Application& application, const Session& session, const IDPSSODescriptor& role, const MessageEncoder* encoder=NULL
90 vector<const XMLCh*> m_bindings;
91 map<const XMLCh*,MessageEncoder*> m_encoders;
93 auto_ptr_char m_protocol;
96 #if defined (_MSC_VER)
97 #pragma warning( pop )
100 Handler* SHIBSP_DLLLOCAL SAML2LogoutInitiatorFactory(const pair<const DOMElement*,const char*>& p)
102 return new SAML2LogoutInitiator(p.first, p.second);
106 SAML2LogoutInitiator::SAML2LogoutInitiator(const DOMElement* e, const char* appId)
107 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".LogoutInitiator.SAML2")), m_appId(appId),
111 m_protocol(samlconstants::SAML20P_NS)
114 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
115 // Handle outgoing binding setup.
116 pair<bool,const XMLCh*> outgoing = getXMLString("outgoingBindings");
117 if (outgoing.first) {
118 m_outgoing = XMLString::replicate(outgoing.second);
119 XMLString::trim(m_outgoing);
122 // No override, so we'll install a default binding precedence.
123 string prec = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
124 samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
125 m_outgoing = XMLString::transcode(prec.c_str());
129 XMLCh* start = m_outgoing;
130 while (start && *start) {
131 pos = XMLString::indexOf(start,chSpace);
133 *(start + pos)=chNull;
134 m_bindings.push_back(start);
136 auto_ptr_char b(start);
137 MessageEncoder * encoder =
138 SAMLConfig::getConfig().MessageEncoderManager.newPlugin(b.get(),pair<const DOMElement*,const XMLCh*>(e,NULL));
139 m_encoders[start] = encoder;
140 m_log.debug("supporting outgoing binding (%s)", b.get());
142 catch (exception& ex) {
143 m_log.error("error building MessageEncoder: %s", ex.what());
146 start = start + pos + 1;
153 pair<bool,const char*> loc = getString("Location");
155 string address = m_appId + loc.second + "::run::SAML2LI";
156 setAddress(address.c_str());
160 void SAML2LogoutInitiator::setParent(const PropertySet* parent)
162 DOMPropertySet::setParent(parent);
163 pair<bool,const char*> loc = getString("Location");
165 string address = m_appId + loc.second + "::run::SAML2LI";
166 setAddress(address.c_str());
169 m_log.warn("no Location property in SAML2 LogoutInitiator (or parent), can't register as remoted handler");
173 pair<bool,long> SAML2LogoutInitiator::run(SPRequest& request, bool isHandler) const
175 // Defer to base class for front-channel loop first.
176 pair<bool,long> ret = LogoutHandler::run(request, isHandler);
180 // At this point we know the front-channel is handled.
181 // We need the session to do any other work.
183 Session* session = NULL;
185 session = request.getSession(false, true, false); // don't cache it and ignore all checks
187 return make_pair(false,0);
189 // We only handle SAML 2.0 sessions.
190 if (!XMLString::equals(session->getProtocol(), m_protocol.get())) {
192 return make_pair(false,0);
195 catch (exception& ex) {
196 m_log.error("error accessing current session: %s", ex.what());
197 return make_pair(false,0);
200 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
201 // When out of process, we run natively.
202 return doRequest(request.getApplication(), request.getRequestURL(), session, request);
205 // When not out of process, we remote the request.
206 Locker locker(session, false);
207 DDF out,in(m_address.c_str());
208 DDFJanitor jin(in), jout(out);
209 in.addmember("application_id").string(request.getApplication().getId());
210 in.addmember("session_id").string(session->getID());
211 in.addmember("url").string(request.getRequestURL());
212 out=request.getServiceProvider().getListenerService()->send(in);
213 return unwrap(request, out);
217 void SAML2LogoutInitiator::receive(DDF& in, ostream& out)
220 // Defer to base class for notifications
221 if (in["notify"].integer() == 1)
222 return LogoutHandler::receive(in, out);
225 const char* aid=in["application_id"].string();
226 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
228 // Something's horribly wrong.
229 m_log.error("couldn't find application (%s) for logout", aid ? aid : "(missing)");
230 throw ConfigurationException("Unable to locate application for logout, deleted?");
233 // Set up a response shim.
235 DDFJanitor jout(ret);
236 auto_ptr<HTTPResponse> resp(getResponse(ret));
238 Session* session = NULL;
240 session = app->getServiceProvider().getSessionCache()->find(in["session_id"].string(), *app, NULL, NULL);
242 catch (exception& ex) {
243 m_log.error("error accessing current session: %s", ex.what());
246 // With no session, we just skip the request and let it fall through to an empty struct return.
248 if (session->getNameID() && session->getEntityID()) {
249 // Since we're remoted, the result should either be a throw, which we pass on,
250 // a false/0 return, which we just return as an empty structure, or a response/redirect,
251 // which we capture in the facade and send back.
252 doRequest(*app, in["url"].string(), session, *resp.get());
255 m_log.error("no NameID or issuing entityID found in session");
257 app->getServiceProvider().getSessionCache()->remove(in["session_id"].string(), *app);
260 pair<string,const char*> shib_cookie=app->getCookieNameProps("_shibsession_");
261 resp->setCookie(shib_cookie.first.c_str(), shib_cookie.second);
266 throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
270 pair<bool,long> SAML2LogoutInitiator::doRequest(
271 const Application& application, const char* requestURL, Session* session, HTTPResponse& response
275 pair<string,const char*> shib_cookie=application.getCookieNameProps("_shibsession_");
276 response.setCookie(shib_cookie.first.c_str(), shib_cookie.second);
278 // Do back channel notification.
279 vector<string> sessions(1, session->getID());
280 if (!notifyBackChannel(application, requestURL, sessions, false)) {
282 application.getServiceProvider().getSessionCache()->remove(sessions.front().c_str(), application);
283 return sendLogoutPage(application, response, true, "Partial logout failure.");
287 pair<bool,long> ret = make_pair(false,0);
289 // With a session in hand, we can create a LogoutRequest message, if we can find a compatible endpoint.
290 Locker metadataLocker(application.getMetadataProvider());
291 const EntityDescriptor* entity = application.getMetadataProvider()->getEntityDescriptor(session->getEntityID());
293 throw MetadataException(
294 "Unable to locate metadata for identity provider ($entityID)",
295 namedparams(1, "entityID", session->getEntityID())
298 const IDPSSODescriptor* role = find_if(entity->getIDPSSODescriptors(), isValidForProtocol(samlconstants::SAML20P_NS));
300 throw MetadataException(
301 "Unable to locate SAML 2.0 IdP role for identity provider ($entityID).",
302 namedparams(1, "entityID", session->getEntityID())
306 const EndpointType* ep=NULL;
307 const MessageEncoder* encoder=NULL;
308 vector<const XMLCh*>::const_iterator b;
309 for (b = m_bindings.begin(); b!=m_bindings.end(); ++b) {
310 if (ep=EndpointManager<SingleLogoutService>(role->getSingleLogoutServices()).getByBinding(*b)) {
311 map<const XMLCh*,MessageEncoder*>::const_iterator enc = m_encoders.find(*b);
312 if (enc!=m_encoders.end())
313 encoder = enc->second;
317 if (!ep || !encoder) {
318 m_log.warn("no compatible front channel SingleLogoutService, trying back channel...");
319 shibsp::SecurityPolicy policy(application);
320 shibsp::SOAPClient soaper(policy);
321 MetadataCredentialCriteria mcc(*role);
323 LogoutResponse* logoutResponse=NULL;
324 auto_ptr_XMLCh binding(samlconstants::SAML20_BINDING_SOAP);
325 const vector<SingleLogoutService*>& endpoints=role->getSingleLogoutServices();
326 for (vector<SingleLogoutService*>::const_iterator epit=endpoints.begin(); !logoutResponse && epit!=endpoints.end(); ++epit) {
328 if (!XMLString::equals((*epit)->getBinding(),binding.get()))
330 LogoutRequest* msg = buildRequest(application, *session, *role);
331 auto_ptr_char dest((*epit)->getLocation());
333 SAML2SOAPClient client(soaper, false);
334 client.sendSAML(msg, application.getId(), mcc, dest.get());
335 StatusResponseType* srt = client.receiveSAML();
336 if (!(logoutResponse = dynamic_cast<LogoutResponse*>(srt))) {
341 catch (exception& ex) {
342 m_log.error("error sending LogoutRequest message: %s", ex.what());
348 ret = sendLogoutPage(application, response, false, "Identity provider did not respond to logout request.");
349 else if (!logoutResponse->getStatus() || !logoutResponse->getStatus()->getStatusCode() ||
350 !XMLString::equals(logoutResponse->getStatus()->getStatusCode()->getValue(), saml2p::StatusCode::SUCCESS)) {
351 delete logoutResponse;
352 ret = sendLogoutPage(application, response, false, "Identity provider returned a SAML error in response to logout request.");
355 delete logoutResponse;
356 ret = sendLogoutPage(application, response, false, "Logout completed successfully.");
360 string session_id = session->getID();
363 application.getServiceProvider().getSessionCache()->remove(session_id.c_str(), application);
368 auto_ptr<LogoutRequest> msg(buildRequest(application, *session, *role, encoder));
370 msg->setDestination(ep->getLocation());
371 auto_ptr_char dest(ep->getLocation());
372 ret.second = sendMessage(*encoder, msg.get(), NULL, dest.get(), role, application, response);
374 msg.release(); // freed by encoder
376 catch (exception& ex) {
377 m_log.error("error issuing SAML 2.0 logout request: %s", ex.what());
381 string session_id = session->getID();
384 application.getServiceProvider().getSessionCache()->remove(session_id.c_str(), application);
389 string session_id = session->getID();
391 application.getServiceProvider().getSessionCache()->remove(session_id.c_str(), application);
392 throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
398 LogoutRequest* SAML2LogoutInitiator::buildRequest(
399 const Application& application, const Session& session, const IDPSSODescriptor& role, const MessageEncoder* encoder
402 auto_ptr<LogoutRequest> msg(LogoutRequestBuilder::buildLogoutRequest());
403 Issuer* issuer = IssuerBuilder::buildIssuer();
404 msg->setIssuer(issuer);
405 issuer->setName(application.getXMLString("entityID").second);
406 auto_ptr_XMLCh index(session.getSessionIndex());
407 if (index.get() && *index.get()) {
408 SessionIndex* si = SessionIndexBuilder::buildSessionIndex();
409 msg->getSessionIndexs().push_back(si);
410 si->setSessionIndex(index.get());
413 const NameID* nameid = session.getNameID();
414 const PropertySet* relyingParty = application.getRelyingParty(dynamic_cast<EntityDescriptor*>(role.getParent()));
415 pair<bool,const char*> flag = relyingParty->getString("encryption");
417 (!strcmp(flag.second, "true") || (encoder && !strcmp(flag.second, "front")) || (!encoder && !strcmp(flag.second, "back")))) {
418 auto_ptr<EncryptedID> encrypted(EncryptedIDBuilder::buildEncryptedID());
419 MetadataCredentialCriteria mcc(role);
422 *(application.getMetadataProvider()),
424 encoder ? encoder->isCompact() : false,
425 relyingParty->getXMLString("encryptionAlg").second
427 msg->setEncryptedID(encrypted.release());
431 // No encoder being used, so sign for SOAP client manually.
432 flag = relyingParty->getString("signing");
433 if (flag.first && (!strcmp(flag.second, "true") || !strcmp(flag.second, "back"))) {
434 CredentialResolver* credResolver=application.getCredentialResolver();
436 Locker credLocker(credResolver);
437 // Fill in criteria to use.
438 MetadataCredentialCriteria mcc(role);
439 mcc.setUsage(Credential::SIGNING_CREDENTIAL);
440 pair<bool,const char*> keyName = relyingParty->getString("keyName");
442 mcc.getKeyNames().insert(keyName.second);
443 pair<bool,const XMLCh*> sigalg = relyingParty->getXMLString("signingAlg");
445 mcc.setXMLAlgorithm(sigalg.second);
446 const Credential* cred = credResolver->resolve(&mcc);
448 xmlsignature::Signature* sig = xmlsignature::SignatureBuilder::buildSignature();
449 msg->setSignature(sig);
451 sig->setSignatureAlgorithm(sigalg.second);
452 sigalg = relyingParty->getXMLString("digestAlg");
454 ContentReference* cr = dynamic_cast<ContentReference*>(sig->getContentReference());
456 cr->setDigestAlgorithm(sigalg.second);
459 // Sign response while marshalling.
460 vector<xmlsignature::Signature*> sigs(1,sig);
461 msg->marshall((DOMDocument*)NULL,&sigs,cred);
464 m_log.warn("no signing credential resolved, leaving message unsigned");
468 m_log.warn("no credential resolver installed, leaving message unsigned");
473 return msg.release();