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(
82 const Application& application, const HTTPRequest& request, HTTPResponse& httpResponse, Session* session
87 LogoutRequest* buildRequest(
88 const Application& application, const Session& session, const RoleDescriptor& role, const MessageEncoder* encoder=NULL
92 vector<const XMLCh*> m_bindings;
93 map<const XMLCh*,MessageEncoder*> m_encoders;
95 auto_ptr_char m_protocol;
98 #if defined (_MSC_VER)
99 #pragma warning( pop )
102 Handler* SHIBSP_DLLLOCAL SAML2LogoutInitiatorFactory(const pair<const DOMElement*,const char*>& p)
104 return new SAML2LogoutInitiator(p.first, p.second);
108 SAML2LogoutInitiator::SAML2LogoutInitiator(const DOMElement* e, const char* appId)
109 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".LogoutInitiator.SAML2")), m_appId(appId),
113 m_protocol(samlconstants::SAML20P_NS)
116 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
117 // Handle outgoing binding setup.
118 pair<bool,const XMLCh*> outgoing = getXMLString("outgoingBindings");
119 if (outgoing.first) {
120 m_outgoing = XMLString::replicate(outgoing.second);
121 XMLString::trim(m_outgoing);
124 // No override, so we'll install a default binding precedence.
125 string prec = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
126 samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
127 m_outgoing = XMLString::transcode(prec.c_str());
131 XMLCh* start = m_outgoing;
132 while (start && *start) {
133 pos = XMLString::indexOf(start,chSpace);
135 *(start + pos)=chNull;
136 m_bindings.push_back(start);
138 auto_ptr_char b(start);
139 MessageEncoder * encoder =
140 SAMLConfig::getConfig().MessageEncoderManager.newPlugin(b.get(),pair<const DOMElement*,const XMLCh*>(e,NULL));
141 m_encoders[start] = encoder;
142 m_log.debug("supporting outgoing binding (%s)", b.get());
144 catch (exception& ex) {
145 m_log.error("error building MessageEncoder: %s", ex.what());
148 start = start + pos + 1;
155 pair<bool,const char*> loc = getString("Location");
157 string address = m_appId + loc.second + "::run::SAML2LI";
158 setAddress(address.c_str());
162 void SAML2LogoutInitiator::setParent(const PropertySet* parent)
164 DOMPropertySet::setParent(parent);
165 pair<bool,const char*> loc = getString("Location");
167 string address = m_appId + loc.second + "::run::SAML2LI";
168 setAddress(address.c_str());
171 m_log.warn("no Location property in SAML2 LogoutInitiator (or parent), can't register as remoted handler");
175 pair<bool,long> SAML2LogoutInitiator::run(SPRequest& request, bool isHandler) const
177 // Defer to base class for front-channel loop first.
178 pair<bool,long> ret = LogoutHandler::run(request, isHandler);
182 // At this point we know the front-channel is handled.
183 // We need the session to do any other work.
185 Session* session = NULL;
187 session = request.getSession(false, true, false); // don't cache it and ignore all checks
189 return make_pair(false,0L);
191 // We only handle SAML 2.0 sessions.
192 if (!XMLString::equals(session->getProtocol(), m_protocol.get())) {
194 return make_pair(false,0L);
197 catch (exception& ex) {
198 m_log.error("error accessing current session: %s", ex.what());
199 return make_pair(false,0L);
202 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
203 // When out of process, we run natively.
204 return doRequest(request.getApplication(), request, request, session);
207 // When not out of process, we remote the request.
209 vector<string> headers(1,"Cookie");
210 DDF out,in = wrap(request,&headers);
211 DDFJanitor jin(in), jout(out);
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 // Unpack the request.
234 auto_ptr<HTTPRequest> req(getRequest(in));
236 // Set up a response shim.
238 DDFJanitor jout(ret);
239 auto_ptr<HTTPResponse> resp(getResponse(ret));
241 Session* session = NULL;
243 session = app->getServiceProvider().getSessionCache()->find(*app, *req.get(), NULL, NULL);
245 catch (exception& ex) {
246 m_log.error("error accessing current session: %s", ex.what());
249 // With no session, we just skip the request and let it fall through to an empty struct return.
251 if (session->getNameID() && session->getEntityID()) {
252 // Since we're remoted, the result should either be a throw, which we pass on,
253 // a false/0 return, which we just return as an empty structure, or a response/redirect,
254 // which we capture in the facade and send back.
255 doRequest(*app, *req.get(), *resp.get(), session);
258 m_log.error("no NameID or issuing entityID found in session");
260 app->getServiceProvider().getSessionCache()->remove(*app, *req.get(), resp.get());
265 throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
269 pair<bool,long> SAML2LogoutInitiator::doRequest(
270 const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse, Session* session
273 // Do back channel notification.
274 vector<string> sessions(1, session->getID());
275 if (!notifyBackChannel(application, httpRequest.getRequestURL(), sessions, false)) {
277 application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
278 return sendLogoutPage(application, httpRequest, httpResponse, true, "Partial logout failure.");
282 pair<bool,long> ret = make_pair(false,0L);
284 // With a session in hand, we can create a LogoutRequest message, if we can find a compatible endpoint.
285 MetadataProvider* m = application.getMetadataProvider();
286 Locker metadataLocker(m);
287 MetadataProvider::Criteria mc(session->getEntityID(), &IDPSSODescriptor::ELEMENT_QNAME, samlconstants::SAML20P_NS);
288 pair<const EntityDescriptor*,const RoleDescriptor*> entity = m->getEntityDescriptor(mc);
290 throw MetadataException(
291 "Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", session->getEntityID())
294 else if (!entity.second) {
295 throw MetadataException(
296 "Unable to locate SAML 2.0 IdP role for identity provider ($entityID).", namedparams(1, "entityID", session->getEntityID())
300 const IDPSSODescriptor* role = dynamic_cast<const IDPSSODescriptor*>(entity.second);
301 const EndpointType* ep=NULL;
302 const MessageEncoder* encoder=NULL;
303 vector<const XMLCh*>::const_iterator b;
304 for (b = m_bindings.begin(); b!=m_bindings.end(); ++b) {
305 if (ep=EndpointManager<SingleLogoutService>(role->getSingleLogoutServices()).getByBinding(*b)) {
306 map<const XMLCh*,MessageEncoder*>::const_iterator enc = m_encoders.find(*b);
307 if (enc!=m_encoders.end())
308 encoder = enc->second;
312 if (!ep || !encoder) {
313 m_log.warn("no compatible front channel SingleLogoutService, trying back channel...");
314 shibsp::SecurityPolicy policy(application);
315 shibsp::SOAPClient soaper(policy);
316 MetadataCredentialCriteria mcc(*role);
318 LogoutResponse* logoutResponse=NULL;
319 auto_ptr_XMLCh binding(samlconstants::SAML20_BINDING_SOAP);
320 const vector<SingleLogoutService*>& endpoints=role->getSingleLogoutServices();
321 for (vector<SingleLogoutService*>::const_iterator epit=endpoints.begin(); !logoutResponse && epit!=endpoints.end(); ++epit) {
323 if (!XMLString::equals((*epit)->getBinding(),binding.get()))
325 LogoutRequest* msg = buildRequest(application, *session, *role);
326 auto_ptr_char dest((*epit)->getLocation());
328 SAML2SOAPClient client(soaper, false);
329 client.sendSAML(msg, application.getId(), mcc, dest.get());
330 StatusResponseType* srt = client.receiveSAML();
331 if (!(logoutResponse = dynamic_cast<LogoutResponse*>(srt))) {
336 catch (exception& ex) {
337 m_log.error("error sending LogoutRequest message: %s", ex.what());
343 ret = sendLogoutPage(application, httpRequest, httpResponse, false, "Identity provider did not respond to logout request.");
344 else if (!logoutResponse->getStatus() || !logoutResponse->getStatus()->getStatusCode() ||
345 !XMLString::equals(logoutResponse->getStatus()->getStatusCode()->getValue(), saml2p::StatusCode::SUCCESS)) {
346 delete logoutResponse;
347 ret = sendLogoutPage(application, httpRequest, httpResponse, false, "Identity provider returned a SAML error in response to logout request.");
350 delete logoutResponse;
351 const char* returnloc = httpRequest.getParameter("return");
353 ret.second = httpResponse.sendRedirect(returnloc);
356 ret = sendLogoutPage(application, httpRequest, httpResponse, false, "Logout completed successfully.");
362 application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
367 // Save off return location as RelayState.
369 const char* returnloc = httpRequest.getParameter("return");
371 relayState = returnloc;
372 preserveRelayState(application, httpResponse, relayState);
375 auto_ptr<LogoutRequest> msg(buildRequest(application, *session, *role, encoder));
377 msg->setDestination(ep->getLocation());
378 auto_ptr_char dest(ep->getLocation());
379 ret.second = sendMessage(*encoder, msg.get(), relayState.c_str(), dest.get(), role, application, httpResponse);
381 msg.release(); // freed by encoder
383 catch (exception& ex) {
384 m_log.error("error issuing SAML 2.0 logout request: %s", ex.what());
390 application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
396 application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
397 throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
403 LogoutRequest* SAML2LogoutInitiator::buildRequest(
404 const Application& application, const Session& session, const RoleDescriptor& role, const MessageEncoder* encoder
407 const PropertySet* relyingParty = application.getRelyingParty(dynamic_cast<EntityDescriptor*>(role.getParent()));
409 auto_ptr<LogoutRequest> msg(LogoutRequestBuilder::buildLogoutRequest());
410 Issuer* issuer = IssuerBuilder::buildIssuer();
411 msg->setIssuer(issuer);
412 issuer->setName(relyingParty->getXMLString("entityID").second);
413 auto_ptr_XMLCh index(session.getSessionIndex());
414 if (index.get() && *index.get()) {
415 SessionIndex* si = SessionIndexBuilder::buildSessionIndex();
416 msg->getSessionIndexs().push_back(si);
417 si->setSessionIndex(index.get());
420 const NameID* nameid = session.getNameID();
421 pair<bool,const char*> flag = relyingParty->getString("encryption");
423 (!strcmp(flag.second, "true") || (encoder && !strcmp(flag.second, "front")) || (!encoder && !strcmp(flag.second, "back")))) {
424 auto_ptr<EncryptedID> encrypted(EncryptedIDBuilder::buildEncryptedID());
425 MetadataCredentialCriteria mcc(role);
428 *(application.getMetadataProvider()),
430 encoder ? encoder->isCompact() : false,
431 relyingParty->getXMLString("encryptionAlg").second
433 msg->setEncryptedID(encrypted.release());
437 // No encoder being used, so sign for SOAP client manually.
438 flag = relyingParty->getString("signing");
439 if (flag.first && (!strcmp(flag.second, "true") || !strcmp(flag.second, "back"))) {
440 CredentialResolver* credResolver=application.getCredentialResolver();
442 Locker credLocker(credResolver);
443 // Fill in criteria to use.
444 MetadataCredentialCriteria mcc(role);
445 mcc.setUsage(Credential::SIGNING_CREDENTIAL);
446 pair<bool,const char*> keyName = relyingParty->getString("keyName");
448 mcc.getKeyNames().insert(keyName.second);
449 pair<bool,const XMLCh*> sigalg = relyingParty->getXMLString("signingAlg");
451 mcc.setXMLAlgorithm(sigalg.second);
452 const Credential* cred = credResolver->resolve(&mcc);
454 xmlsignature::Signature* sig = xmlsignature::SignatureBuilder::buildSignature();
455 msg->setSignature(sig);
457 sig->setSignatureAlgorithm(sigalg.second);
458 sigalg = relyingParty->getXMLString("digestAlg");
460 ContentReference* cr = dynamic_cast<ContentReference*>(sig->getContentReference());
462 cr->setDigestAlgorithm(sigalg.second);
465 // Sign response while marshalling.
466 vector<xmlsignature::Signature*> sigs(1,sig);
467 msg->marshall((DOMDocument*)NULL,&sigs,cred);
470 m_log.warn("no signing credential resolved, leaving message unsigned");
474 m_log.warn("no credential resolver installed, leaving message unsigned");
479 return msg.release();