74874eb64650d3af3f33256a0203e3d16c094727
[shibboleth/cpp-sp.git] / shibsp / handler / impl / SAML2LogoutInitiator.cpp
1 /**
2  * Licensed to the University Corporation for Advanced Internet
3  * Development, Inc. (UCAID) under one or more contributor license
4  * agreements. See the NOTICE file distributed with this work for
5  * additional information regarding copyright ownership.
6  *
7  * UCAID licenses this file to you under the Apache License,
8  * Version 2.0 (the "License"); you may not use this file except
9  * in compliance with the License. You may obtain a copy of the
10  * License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing,
15  * software distributed under the License is distributed on an
16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17  * either express or implied. See the License for the specific
18  * language governing permissions and limitations under the License.
19  */
20
21 /**
22  * SAML2LogoutInitiator.cpp
23  *
24  * Triggers SP-initiated logout for SAML 2.0 sessions.
25  */
26
27 #include "internal.h"
28 #include "exceptions.h"
29 #include "Application.h"
30 #include "ServiceProvider.h"
31 #include "SessionCache.h"
32 #include "handler/AbstractHandler.h"
33 #include "handler/LogoutInitiator.h"
34
35 #ifndef SHIBSP_LITE
36 # include "binding/SOAPClient.h"
37 # include "metadata/MetadataProviderCriteria.h"
38 # include "security/SecurityPolicy.h"
39 # include <boost/algorithm/string.hpp>
40 # include <boost/iterator/indirect_iterator.hpp>
41 # include <saml/exceptions.h>
42 # include <saml/SAMLConfig.h>
43 # include <saml/saml2/core/Protocols.h>
44 # include <saml/saml2/binding/SAML2SOAPClient.h>
45 # include <saml/saml2/metadata/EndpointManager.h>
46 # include <saml/saml2/metadata/Metadata.h>
47 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
48 using namespace opensaml::saml2;
49 using namespace opensaml::saml2p;
50 using namespace opensaml::saml2md;
51 using namespace opensaml;
52 #else
53 # include "lite/SAMLConstants.h"
54 #endif
55
56 using namespace shibsp;
57 using namespace xmltooling;
58 using namespace boost;
59 using namespace std;
60
61 namespace shibsp {
62
63 #if defined (_MSC_VER)
64     #pragma warning( push )
65     #pragma warning( disable : 4250 )
66 #endif
67
68     class SHIBSP_DLLLOCAL SAML2LogoutInitiator : public AbstractHandler, public LogoutInitiator
69     {
70     public:
71         SAML2LogoutInitiator(const DOMElement* e, const char* appId);
72         virtual ~SAML2LogoutInitiator() {}
73
74         void init(const char* location);    // encapsulates actions that need to run either in the c'tor or setParent
75
76         void setParent(const PropertySet* parent);
77         void receive(DDF& in, ostream& out);
78         pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
79
80         const XMLCh* getProtocolFamily() const {
81             return samlconstants::SAML20P_NS;
82         }
83
84     private:
85         pair<bool,long> doRequest(
86             const Application& application, const HTTPRequest& request, HTTPResponse& httpResponse, Session* session
87             ) const;
88
89         string m_appId;
90 #ifndef SHIBSP_LITE
91         auto_ptr<LogoutRequest> buildRequest(
92             const Application& application, const Session& session, const RoleDescriptor& role, const MessageEncoder* encoder=nullptr
93             ) const;
94
95         LogoutEvent* newLogoutEvent(
96             const Application& application, const HTTPRequest* request=nullptr, const Session* session=nullptr
97             ) const {
98             LogoutEvent* e = LogoutHandler::newLogoutEvent(application, request, session);
99             if (e)
100                 e->m_protocol = m_protocol.get();
101             return e;
102         }
103
104         bool m_async;
105         vector<string> m_bindings;
106         map< string,boost::shared_ptr<MessageEncoder> > m_encoders;
107 #endif
108         auto_ptr_char m_protocol;
109     };
110
111 #if defined (_MSC_VER)
112     #pragma warning( pop )
113 #endif
114
115     Handler* SHIBSP_DLLLOCAL SAML2LogoutInitiatorFactory(const pair<const DOMElement*,const char*>& p)
116     {
117         return new SAML2LogoutInitiator(p.first, p.second);
118     }
119 };
120
121 SAML2LogoutInitiator::SAML2LogoutInitiator(const DOMElement* e, const char* appId)
122     : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".LogoutInitiator.SAML2")), m_appId(appId), m_protocol(samlconstants::SAML20P_NS)
123 #ifndef SHIBSP_LITE
124         ,m_async(true)
125 #endif
126 {
127     // If Location isn't set, defer initialization until the setParent call.
128     pair<bool,const char*> loc = getString("Location");
129     if (loc.first) {
130         init(loc.second);
131     }
132 }
133
134 void SAML2LogoutInitiator::setParent(const PropertySet* parent)
135 {
136     DOMPropertySet::setParent(parent);
137     pair<bool,const char*> loc = getString("Location");
138     init(loc.second);
139 }
140
141 void SAML2LogoutInitiator::init(const char* location)
142 {
143     if (location) {
144         string address = m_appId + location + "::run::SAML2LI";
145         setAddress(address.c_str());
146     }
147     else {
148         m_log.warn("no Location property in SAML2 LogoutInitiator (or parent), can't register as remoted handler");
149     }
150
151 #ifndef SHIBSP_LITE
152     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
153         pair<bool,bool> async = getBool("asynchronous");
154         m_async = !async.first || async.second;
155
156         string dupBindings;
157         pair<bool,const char*> outgoing = getString("outgoingBindings");
158         if (outgoing.first) {
159             dupBindings = outgoing.second;
160         }
161         else {
162             // No override, so we'll install a default binding precedence.
163             dupBindings = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
164                 samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
165         }
166         split(m_bindings, dupBindings, is_space(), algorithm::token_compress_on);
167         for (vector<string>::const_iterator b = m_bindings.begin(); b != m_bindings.end(); ++b) {
168             try {
169                 boost::shared_ptr<MessageEncoder> encoder(
170                     SAMLConfig::getConfig().MessageEncoderManager.newPlugin(*b, pair<const DOMElement*,const XMLCh*>(getElement(),nullptr))
171                     );
172                 if (encoder->isUserAgentPresent() && XMLString::equals(getProtocolFamily(), encoder->getProtocolFamily())) {
173                     m_encoders[*b] = encoder;
174                     m_log.debug("supporting outgoing binding (%s)", b->c_str());
175                 }
176                 else {
177                     m_log.warn("skipping outgoing binding (%s), not a SAML 2.0 front-channel mechanism", b->c_str());
178                 }
179             }
180             catch (std::exception& ex) {
181                 m_log.error("error building MessageEncoder: %s", ex.what());
182             }
183         }
184     }
185 #endif
186 }
187
188
189 pair<bool,long> SAML2LogoutInitiator::run(SPRequest& request, bool isHandler) const
190 {
191     // Defer to base class for front-channel loop first.
192     pair<bool,long> ret = LogoutHandler::run(request, isHandler);
193     if (ret.first)
194         return ret;
195
196     // At this point we know the front-channel is handled.
197     // We need the session to do any other work.
198
199     Session* session = nullptr;
200     try {
201         session = request.getSession(false, true, false);  // don't cache it and ignore all checks
202         if (!session)
203             return make_pair(false, 0L);
204
205         // We only handle SAML 2.0 sessions.
206         if (!XMLString::equals(session->getProtocol(), m_protocol.get())) {
207             session->unlock();
208             return make_pair(false, 0L);
209         }
210     }
211     catch (std::exception& ex) {
212         m_log.error("error accessing current session: %s", ex.what());
213         return make_pair(false, 0L);
214     }
215
216     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
217         // When out of process, we run natively.
218         return doRequest(request.getApplication(), request, request, session);
219     }
220     else {
221         // When not out of process, we remote the request.
222         session->unlock();
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);
228     }
229 }
230
231 void SAML2LogoutInitiator::receive(DDF& in, ostream& out)
232 {
233 #ifndef SHIBSP_LITE
234     // Defer to base class for notifications
235     if (in["notify"].integer() == 1)
236         return LogoutHandler::receive(in, out);
237
238     // Find application.
239     const char* aid=in["application_id"].string();
240     const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
241     if (!app) {
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?");
245     }
246
247     // Unpack the request.
248     scoped_ptr<HTTPRequest> req(getRequest(in));
249
250     // Set up a response shim.
251     DDF ret(nullptr);
252     DDFJanitor jout(ret);
253     scoped_ptr<HTTPResponse> resp(getResponse(ret));
254
255     Session* session = nullptr;
256     try {
257          session = app->getServiceProvider().getSessionCache()->find(*app, *req, nullptr, nullptr);
258     }
259     catch (std::exception& ex) {
260         m_log.error("error accessing current session: %s", ex.what());
261     }
262
263     // With no session, we just skip the request and let it fall through to an empty struct return.
264     if (session) {
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, *resp, session);
270         }
271         else {
272             session->unlock();
273             m_log.log(getParent() ? Priority::WARN : Priority::ERROR, "bypassing SAML 2.0 logout, no NameID or issuing entityID found in session");
274             app->getServiceProvider().getSessionCache()->remove(*app, *req, resp.get());
275         }
276     }
277     out << ret;
278 #else
279     throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
280 #endif
281 }
282
283 pair<bool,long> SAML2LogoutInitiator::doRequest(
284     const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse, Session* session
285     ) const
286 {
287     Locker sessionLocker(session, false);
288 #ifndef SHIBSP_LITE
289     scoped_ptr<LogoutEvent> logout_event(newLogoutEvent(application, &httpRequest, session));
290 #endif
291
292     // Do back channel notification.
293     vector<string> sessions(1, session->getID());
294     if (!notifyBackChannel(application, httpRequest.getRequestURL(), sessions, false)) {
295 #ifndef SHIBSP_LITE
296         if (logout_event) {
297             logout_event->m_logoutType = LogoutEvent::LOGOUT_EVENT_PARTIAL;
298             application.getServiceProvider().getTransactionLog()->write(*logout_event);
299         }
300 #endif
301         sessionLocker.assign();
302         session = nullptr;
303         application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
304         return sendLogoutPage(application, httpRequest, httpResponse, "partial");
305     }
306
307 #ifndef SHIBSP_LITE
308     pair<bool,long> ret = make_pair(false, 0L);
309     try {
310         // With a session in hand, we can create a LogoutRequest message, if we can find a compatible endpoint.
311         MetadataProvider* m = application.getMetadataProvider();
312         Locker metadataLocker(m);
313         MetadataProviderCriteria mc(application, session->getEntityID(), &IDPSSODescriptor::ELEMENT_QNAME, samlconstants::SAML20P_NS);
314         pair<const EntityDescriptor*,const RoleDescriptor*> entity = m->getEntityDescriptor(mc);
315         if (!entity.first) {
316             throw MetadataException(
317                 "Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", session->getEntityID())
318                 );
319         }
320         else if (!entity.second) {
321             throw MetadataException(
322                 "Unable to locate SAML 2.0 IdP role for identity provider ($entityID).", namedparams(1, "entityID", session->getEntityID())
323                 );
324         }
325
326         const IDPSSODescriptor* role = dynamic_cast<const IDPSSODescriptor*>(entity.second);
327         if (role->getSingleLogoutServices().empty()) {
328             throw MetadataException(
329                 "No SingleLogoutService endpoints in metadata for identity provider ($entityID).", namedparams(1, "entityID", session->getEntityID())
330                 );
331         }
332
333         const EndpointType* ep = nullptr;
334         const MessageEncoder* encoder = nullptr;
335         for (vector<string>::const_iterator b = m_bindings.begin(); b != m_bindings.end(); ++b) {
336             auto_ptr_XMLCh wideb(b->c_str());
337             if (ep = EndpointManager<SingleLogoutService>(role->getSingleLogoutServices()).getByBinding(wideb.get())) {
338                 map< string,boost::shared_ptr<MessageEncoder> >::const_iterator enc = m_encoders.find(*b);
339                 if (enc != m_encoders.end())
340                     encoder = enc->second.get();
341                 break;
342             }
343         }
344         if (!ep || !encoder) {
345             m_log.debug("no compatible front channel SingleLogoutService, trying back channel...");
346             shibsp::SecurityPolicy policy(application);
347             shibsp::SOAPClient soaper(policy);
348             MetadataCredentialCriteria mcc(*role);
349
350             LogoutResponse* logoutResponse = nullptr;
351             scoped_ptr<StatusResponseType> srt;
352             auto_ptr_XMLCh binding(samlconstants::SAML20_BINDING_SOAP);
353             const vector<SingleLogoutService*>& endpoints = role->getSingleLogoutServices();
354             for (indirect_iterator<vector<SingleLogoutService*>::const_iterator> epit = make_indirect_iterator(endpoints.begin());
355                     !logoutResponse && epit != make_indirect_iterator(endpoints.end()); ++epit) {
356                 try {
357                     if (!XMLString::equals(epit->getBinding(), binding.get()))
358                         continue;
359                     auto_ptr<LogoutRequest> msg(buildRequest(application, *session, *role));
360
361                     // Log the request.
362                     if (logout_event) {
363                         logout_event->m_logoutType = LogoutEvent::LOGOUT_EVENT_UNKNOWN;
364                         logout_event->m_saml2Request = msg.get();
365                         application.getServiceProvider().getTransactionLog()->write(*logout_event);
366                         logout_event->m_saml2Request = nullptr;
367                     }
368
369                     auto_ptr_char dest(epit->getLocation());
370                     SAML2SOAPClient client(soaper, false);
371                     client.sendSAML(msg.release(), application.getId(), mcc, dest.get());
372                     srt.reset(client.receiveSAML());
373                     if (!(logoutResponse = dynamic_cast<LogoutResponse*>(srt.get()))) {
374                         break;
375                     }
376                 }
377                 catch (std::exception& ex) {
378                     m_log.error("error sending LogoutRequest message: %s", ex.what());
379                     soaper.reset();
380                 }
381             }
382
383             // No answer at all?
384             if (!logoutResponse) {
385                 if (endpoints.empty())
386                     m_log.info("IdP doesn't support single logout protocol over a compatible binding");
387                 else
388                     m_log.warn("IdP didn't respond to logout request");
389
390                 // Log the end result.
391                 if (logout_event) {
392                     logout_event->m_logoutType = LogoutEvent::LOGOUT_EVENT_PARTIAL;
393                     application.getServiceProvider().getTransactionLog()->write(*logout_event);
394                 }
395
396                 ret = sendLogoutPage(application, httpRequest, httpResponse, "partial");
397             }
398             else {
399                 // Check the status, looking for non-success or a partial logout code.
400                 const StatusCode* sc = logoutResponse->getStatus() ? logoutResponse->getStatus()->getStatusCode() : nullptr;
401                 bool partial = (!sc || !XMLString::equals(sc->getValue(), StatusCode::SUCCESS));
402                 if (!partial && sc->getStatusCode()) {
403                     // Success, but still need to check for partial.
404                     partial = XMLString::equals(sc->getStatusCode()->getValue(), StatusCode::PARTIAL_LOGOUT);
405                 }
406
407                 // Log the end result.
408                 if (logout_event) {
409                     logout_event->m_logoutType = partial ? LogoutEvent::LOGOUT_EVENT_PARTIAL : LogoutEvent::LOGOUT_EVENT_GLOBAL;
410                     logout_event->m_saml2Response = logoutResponse;
411                     application.getServiceProvider().getTransactionLog()->write(*logout_event);
412                 }
413
414                 if (partial)
415                     ret = sendLogoutPage(application, httpRequest, httpResponse, "partial");
416                 else {
417                     const char* returnloc = httpRequest.getParameter("return");
418                     if (returnloc) {
419                         // Relative URLs get promoted, absolutes get validated.
420                         if (*returnloc == '/') {
421                             string loc(returnloc);
422                             httpRequest.absolutize(loc);
423                             ret.second = httpResponse.sendRedirect(loc.c_str());
424                         }
425                         else {
426                             application.limitRedirect(httpRequest, returnloc);
427                             ret.second = httpResponse.sendRedirect(returnloc);
428                         }
429                         ret.first = true;
430                     }
431                     else {
432                         ret = sendLogoutPage(application, httpRequest, httpResponse, "global");
433                     }
434                 }
435             }
436
437             if (session) {
438                 sessionLocker.assign();
439                 session = nullptr;
440                 application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
441             }
442
443             return ret;
444         }
445
446         // Save off return location as RelayState.
447         string relayState;
448         const char* returnloc = httpRequest.getParameter("return");
449         if (returnloc) {
450             application.limitRedirect(httpRequest, returnloc);
451             relayState = returnloc;
452             httpRequest.absolutize(relayState);
453             cleanRelayState(application, httpRequest, httpResponse);
454             preserveRelayState(application, httpResponse, relayState);
455         }
456
457         auto_ptr<LogoutRequest> msg(buildRequest(application, *session, *role, encoder));
458         msg->setDestination(ep->getLocation());
459
460         // Log the request.
461         if (logout_event) {
462             logout_event->m_logoutType = LogoutEvent::LOGOUT_EVENT_UNKNOWN;
463             logout_event->m_saml2Request = msg.get();
464             application.getServiceProvider().getTransactionLog()->write(*logout_event);
465         }
466
467         auto_ptr_char dest(ep->getLocation());
468         ret.second = sendMessage(*encoder, msg.get(), relayState.c_str(), dest.get(), role, application, httpResponse, true);
469         ret.first = true;
470         msg.release();  // freed by encoder
471
472         if (session) {
473             sessionLocker.assign();
474             session = nullptr;
475             application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
476         }
477     }
478     catch (MetadataException& mex) {
479         // Less noise for IdPs that don't support logout (i.e. most)
480         m_log.info("unable to issue SAML 2.0 logout request: %s", mex.what());
481     }
482     catch (std::exception& ex) {
483         m_log.error("error issuing SAML 2.0 logout request: %s", ex.what());
484     }
485
486     return ret;
487 #else
488     throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
489 #endif
490 }
491
492 #ifndef SHIBSP_LITE
493
494 auto_ptr<LogoutRequest> SAML2LogoutInitiator::buildRequest(
495     const Application& application, const Session& session, const RoleDescriptor& role, const MessageEncoder* encoder
496     ) const
497 {
498     const PropertySet* relyingParty = application.getRelyingParty(dynamic_cast<EntityDescriptor*>(role.getParent()));
499
500     auto_ptr<LogoutRequest> msg(LogoutRequestBuilder::buildLogoutRequest());
501     Issuer* issuer = IssuerBuilder::buildIssuer();
502     msg->setIssuer(issuer);
503     issuer->setName(relyingParty->getXMLString("entityID").second);
504     auto_ptr_XMLCh index(session.getSessionIndex());
505     if (index.get() && *index.get()) {
506         SessionIndex* si = SessionIndexBuilder::buildSessionIndex();
507         msg->getSessionIndexs().push_back(si);
508         si->setSessionIndex(index.get());
509     }
510
511     const NameID* nameid = session.getNameID();
512     pair<bool,const char*> flag = relyingParty->getString("encryption");
513     if (flag.first &&
514         (!strcmp(flag.second, "true") || (encoder && !strcmp(flag.second, "front")) || (!encoder && !strcmp(flag.second, "back")))) {
515         auto_ptr<EncryptedID> encrypted(EncryptedIDBuilder::buildEncryptedID());
516         MetadataCredentialCriteria mcc(role);
517         encrypted->encrypt(
518             *nameid,
519             *(application.getMetadataProvider()),
520             mcc,
521             encoder ? encoder->isCompact() : false,
522             relyingParty->getXMLString("encryptionAlg").second
523             );
524         msg->setEncryptedID(encrypted.get());
525         encrypted.release();
526     }
527     else {
528         msg->setNameID(nameid->cloneNameID());
529     }
530
531     XMLCh* msgid = SAMLConfig::getConfig().generateIdentifier();
532     msg->setID(msgid);
533     XMLString::release(&msgid);
534     msg->setIssueInstant(time(nullptr));
535
536     if (m_async && encoder) {
537         msg->setExtensions(saml2p::ExtensionsBuilder::buildExtensions());
538         msg->getExtensions()->getUnknownXMLObjects().push_back(AsynchronousBuilder::buildAsynchronous());
539     }
540
541     return msg;
542 }
543
544 #endif