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 "metadata/MetadataProviderCriteria.h"
34 # include <saml/SAMLConfig.h>
35 # include <saml/saml2/core/Protocols.h>
36 # include <saml/saml2/binding/SAML2SOAPClient.h>
37 # include <saml/saml2/metadata/EndpointManager.h>
38 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
39 using namespace opensaml::saml2;
40 using namespace opensaml::saml2p;
41 using namespace opensaml::saml2md;
42 using namespace opensaml;
44 # include "lite/SAMLConstants.h"
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 SAML2LogoutInitiator : public AbstractHandler, public LogoutHandler
61 SAML2LogoutInitiator(const DOMElement* e, const char* appId);
62 virtual ~SAML2LogoutInitiator() {
64 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
65 XMLString::release(&m_outgoing);
66 for_each(m_encoders.begin(), m_encoders.end(), cleanup_pair<const XMLCh*,MessageEncoder>());
71 void setParent(const PropertySet* parent);
72 void receive(DDF& in, ostream& out);
73 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
76 const char* getType() const {
77 return "LogoutInitiator";
82 pair<bool,long> doRequest(
83 const Application& application, const HTTPRequest& request, HTTPResponse& httpResponse, Session* session
88 LogoutRequest* buildRequest(
89 const Application& application, const Session& session, const RoleDescriptor& role, const MessageEncoder* encoder=NULL
93 vector<const XMLCh*> m_bindings;
94 map<const XMLCh*,MessageEncoder*> m_encoders;
96 auto_ptr_char m_protocol;
99 #if defined (_MSC_VER)
100 #pragma warning( pop )
103 Handler* SHIBSP_DLLLOCAL SAML2LogoutInitiatorFactory(const pair<const DOMElement*,const char*>& p)
105 return new SAML2LogoutInitiator(p.first, p.second);
109 SAML2LogoutInitiator::SAML2LogoutInitiator(const DOMElement* e, const char* appId)
110 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".LogoutInitiator.SAML2")), m_appId(appId),
114 m_protocol(samlconstants::SAML20P_NS)
117 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
118 // Handle outgoing binding setup.
119 pair<bool,const XMLCh*> outgoing = getXMLString("outgoingBindings");
120 if (outgoing.first) {
121 m_outgoing = XMLString::replicate(outgoing.second);
122 XMLString::trim(m_outgoing);
125 // No override, so we'll install a default binding precedence.
126 string prec = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
127 samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
128 m_outgoing = XMLString::transcode(prec.c_str());
132 XMLCh* start = m_outgoing;
133 while (start && *start) {
134 pos = XMLString::indexOf(start,chSpace);
136 *(start + pos)=chNull;
137 m_bindings.push_back(start);
139 auto_ptr_char b(start);
140 MessageEncoder * encoder =
141 SAMLConfig::getConfig().MessageEncoderManager.newPlugin(b.get(),pair<const DOMElement*,const XMLCh*>(e,NULL));
142 m_encoders[start] = encoder;
143 m_log.debug("supporting outgoing binding (%s)", b.get());
145 catch (exception& ex) {
146 m_log.error("error building MessageEncoder: %s", ex.what());
149 start = start + pos + 1;
156 pair<bool,const char*> loc = getString("Location");
158 string address = m_appId + loc.second + "::run::SAML2LI";
159 setAddress(address.c_str());
163 void SAML2LogoutInitiator::setParent(const PropertySet* parent)
165 DOMPropertySet::setParent(parent);
166 pair<bool,const char*> loc = getString("Location");
168 string address = m_appId + loc.second + "::run::SAML2LI";
169 setAddress(address.c_str());
172 m_log.warn("no Location property in SAML2 LogoutInitiator (or parent), can't register as remoted handler");
176 pair<bool,long> SAML2LogoutInitiator::run(SPRequest& request, bool isHandler) const
178 // Defer to base class for front-channel loop first.
179 pair<bool,long> ret = LogoutHandler::run(request, isHandler);
183 // At this point we know the front-channel is handled.
184 // We need the session to do any other work.
186 Session* session = NULL;
188 session = request.getSession(false, true, false); // don't cache it and ignore all checks
190 return make_pair(false,0L);
192 // We only handle SAML 2.0 sessions.
193 if (!XMLString::equals(session->getProtocol(), m_protocol.get())) {
195 return make_pair(false,0L);
198 catch (exception& ex) {
199 m_log.error("error accessing current session: %s", ex.what());
200 return make_pair(false,0L);
203 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
204 // When out of process, we run natively.
205 return doRequest(request.getApplication(), request, request, session);
208 // When not out of process, we remote the request.
210 vector<string> headers(1,"Cookie");
211 DDF out,in = wrap(request,&headers);
212 DDFJanitor jin(in), jout(out);
213 out=request.getServiceProvider().getListenerService()->send(in);
214 return unwrap(request, out);
218 void SAML2LogoutInitiator::receive(DDF& in, ostream& out)
221 // Defer to base class for notifications
222 if (in["notify"].integer() == 1)
223 return LogoutHandler::receive(in, out);
226 const char* aid=in["application_id"].string();
227 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
229 // Something's horribly wrong.
230 m_log.error("couldn't find application (%s) for logout", aid ? aid : "(missing)");
231 throw ConfigurationException("Unable to locate application for logout, deleted?");
234 // Unpack the request.
235 auto_ptr<HTTPRequest> req(getRequest(in));
237 // Set up a response shim.
239 DDFJanitor jout(ret);
240 auto_ptr<HTTPResponse> resp(getResponse(ret));
242 Session* session = NULL;
244 session = app->getServiceProvider().getSessionCache()->find(*app, *req.get(), NULL, NULL);
246 catch (exception& ex) {
247 m_log.error("error accessing current session: %s", ex.what());
250 // With no session, we just skip the request and let it fall through to an empty struct return.
252 if (session->getNameID() && session->getEntityID()) {
253 // Since we're remoted, the result should either be a throw, which we pass on,
254 // a false/0 return, which we just return as an empty structure, or a response/redirect,
255 // which we capture in the facade and send back.
256 doRequest(*app, *req.get(), *resp.get(), session);
259 m_log.error("no NameID or issuing entityID found in session");
261 app->getServiceProvider().getSessionCache()->remove(*app, *req.get(), resp.get());
266 throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
270 pair<bool,long> SAML2LogoutInitiator::doRequest(
271 const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse, Session* session
274 // Do back channel notification.
275 vector<string> sessions(1, session->getID());
276 if (!notifyBackChannel(application, httpRequest.getRequestURL(), sessions, false)) {
278 application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
279 return sendLogoutPage(application, httpRequest, httpResponse, true, "Partial logout failure.");
283 pair<bool,long> ret = make_pair(false,0L);
285 // With a session in hand, we can create a LogoutRequest message, if we can find a compatible endpoint.
286 MetadataProvider* m = application.getMetadataProvider();
287 Locker metadataLocker(m);
288 MetadataProviderCriteria mc(application, session->getEntityID(), &IDPSSODescriptor::ELEMENT_QNAME, samlconstants::SAML20P_NS);
289 pair<const EntityDescriptor*,const RoleDescriptor*> entity = m->getEntityDescriptor(mc);
291 throw MetadataException(
292 "Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", session->getEntityID())
295 else if (!entity.second) {
296 throw MetadataException(
297 "Unable to locate SAML 2.0 IdP role for identity provider ($entityID).", namedparams(1, "entityID", session->getEntityID())
301 const IDPSSODescriptor* role = dynamic_cast<const IDPSSODescriptor*>(entity.second);
302 const EndpointType* ep=NULL;
303 const MessageEncoder* encoder=NULL;
304 vector<const XMLCh*>::const_iterator b;
305 for (b = m_bindings.begin(); b!=m_bindings.end(); ++b) {
306 if (ep=EndpointManager<SingleLogoutService>(role->getSingleLogoutServices()).getByBinding(*b)) {
307 map<const XMLCh*,MessageEncoder*>::const_iterator enc = m_encoders.find(*b);
308 if (enc!=m_encoders.end())
309 encoder = enc->second;
313 if (!ep || !encoder) {
314 m_log.warn("no compatible front channel SingleLogoutService, trying back channel...");
315 shibsp::SecurityPolicy policy(application);
316 shibsp::SOAPClient soaper(policy);
317 MetadataCredentialCriteria mcc(*role);
319 LogoutResponse* logoutResponse=NULL;
320 auto_ptr_XMLCh binding(samlconstants::SAML20_BINDING_SOAP);
321 const vector<SingleLogoutService*>& endpoints=role->getSingleLogoutServices();
322 for (vector<SingleLogoutService*>::const_iterator epit=endpoints.begin(); !logoutResponse && epit!=endpoints.end(); ++epit) {
324 if (!XMLString::equals((*epit)->getBinding(),binding.get()))
326 LogoutRequest* msg = buildRequest(application, *session, *role);
327 auto_ptr_char dest((*epit)->getLocation());
329 SAML2SOAPClient client(soaper, false);
330 client.sendSAML(msg, application.getId(), mcc, dest.get());
331 StatusResponseType* srt = client.receiveSAML();
332 if (!(logoutResponse = dynamic_cast<LogoutResponse*>(srt))) {
337 catch (exception& ex) {
338 m_log.error("error sending LogoutRequest message: %s", ex.what());
343 if (!logoutResponse) {
344 ret = sendLogoutPage(
345 application, httpRequest, httpResponse, false,
347 "Identity provider does not support SAML 2 Single Logout protocol." :
348 "Identity provider did not respond to logout request."
351 else if (!logoutResponse->getStatus() || !logoutResponse->getStatus()->getStatusCode() ||
352 !XMLString::equals(logoutResponse->getStatus()->getStatusCode()->getValue(), saml2p::StatusCode::SUCCESS)) {
353 delete logoutResponse;
354 ret = sendLogoutPage(application, httpRequest, httpResponse, false, "Identity provider returned a SAML error in response to logout request.");
357 delete logoutResponse;
358 const char* returnloc = httpRequest.getParameter("return");
360 ret.second = httpResponse.sendRedirect(returnloc);
363 ret = sendLogoutPage(application, httpRequest, httpResponse, false, "Logout completed successfully.");
369 application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
374 // Save off return location as RelayState.
376 const char* returnloc = httpRequest.getParameter("return");
378 relayState = returnloc;
379 preserveRelayState(application, httpResponse, relayState);
382 auto_ptr<LogoutRequest> msg(buildRequest(application, *session, *role, encoder));
384 msg->setDestination(ep->getLocation());
385 auto_ptr_char dest(ep->getLocation());
386 ret.second = sendMessage(*encoder, msg.get(), relayState.c_str(), dest.get(), role, application, httpResponse);
388 msg.release(); // freed by encoder
390 catch (exception& ex) {
391 m_log.error("error issuing SAML 2.0 logout request: %s", ex.what());
397 application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
403 application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
404 throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
410 LogoutRequest* SAML2LogoutInitiator::buildRequest(
411 const Application& application, const Session& session, const RoleDescriptor& role, const MessageEncoder* encoder
414 const PropertySet* relyingParty = application.getRelyingParty(dynamic_cast<EntityDescriptor*>(role.getParent()));
416 auto_ptr<LogoutRequest> msg(LogoutRequestBuilder::buildLogoutRequest());
417 Issuer* issuer = IssuerBuilder::buildIssuer();
418 msg->setIssuer(issuer);
419 issuer->setName(relyingParty->getXMLString("entityID").second);
420 auto_ptr_XMLCh index(session.getSessionIndex());
421 if (index.get() && *index.get()) {
422 SessionIndex* si = SessionIndexBuilder::buildSessionIndex();
423 msg->getSessionIndexs().push_back(si);
424 si->setSessionIndex(index.get());
427 const NameID* nameid = session.getNameID();
428 pair<bool,const char*> flag = relyingParty->getString("encryption");
430 (!strcmp(flag.second, "true") || (encoder && !strcmp(flag.second, "front")) || (!encoder && !strcmp(flag.second, "back")))) {
431 auto_ptr<EncryptedID> encrypted(EncryptedIDBuilder::buildEncryptedID());
432 MetadataCredentialCriteria mcc(role);
435 *(application.getMetadataProvider()),
437 encoder ? encoder->isCompact() : false,
438 relyingParty->getXMLString("encryptionAlg").second
440 msg->setEncryptedID(encrypted.release());
443 msg->setNameID(nameid->cloneNameID());
447 // No encoder being used, so sign for SOAP client manually.
448 flag = relyingParty->getString("signing");
449 if (flag.first && (!strcmp(flag.second, "true") || !strcmp(flag.second, "back"))) {
450 CredentialResolver* credResolver=application.getCredentialResolver();
452 Locker credLocker(credResolver);
453 // Fill in criteria to use.
454 MetadataCredentialCriteria mcc(role);
455 mcc.setUsage(Credential::SIGNING_CREDENTIAL);
456 pair<bool,const char*> keyName = relyingParty->getString("keyName");
458 mcc.getKeyNames().insert(keyName.second);
459 pair<bool,const XMLCh*> sigalg = relyingParty->getXMLString("signingAlg");
461 mcc.setXMLAlgorithm(sigalg.second);
462 const Credential* cred = credResolver->resolve(&mcc);
464 xmlsignature::Signature* sig = xmlsignature::SignatureBuilder::buildSignature();
465 msg->setSignature(sig);
467 sig->setSignatureAlgorithm(sigalg.second);
468 sigalg = relyingParty->getXMLString("digestAlg");
470 ContentReference* cr = dynamic_cast<ContentReference*>(sig->getContentReference());
472 cr->setDigestAlgorithm(sigalg.second);
475 // Sign response while marshalling.
476 vector<xmlsignature::Signature*> sigs(1,sig);
477 msg->marshall((DOMDocument*)NULL,&sigs,cred);
480 m_log.warn("no signing credential resolved, leaving message unsigned");
484 m_log.warn("no credential resolver installed, leaving message unsigned");
489 return msg.release();