https://issues.shibboleth.net/jira/browse/SSPCPP-444
[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         vector<string> m_bindings;
105         map< string,boost::shared_ptr<MessageEncoder> > m_encoders;
106 #endif
107         auto_ptr_char m_protocol;
108     };
109
110 #if defined (_MSC_VER)
111     #pragma warning( pop )
112 #endif
113
114     Handler* SHIBSP_DLLLOCAL SAML2LogoutInitiatorFactory(const pair<const DOMElement*,const char*>& p)
115     {
116         return new SAML2LogoutInitiator(p.first, p.second);
117     }
118 };
119
120 SAML2LogoutInitiator::SAML2LogoutInitiator(const DOMElement* e, const char* appId)
121     : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".LogoutInitiator.SAML2")), m_appId(appId), m_protocol(samlconstants::SAML20P_NS)
122 {
123     // If Location isn't set, defer initialization until the setParent call.
124     pair<bool,const char*> loc = getString("Location");
125     if (loc.first) {
126         init(loc.second);
127     }
128 }
129
130 void SAML2LogoutInitiator::setParent(const PropertySet* parent)
131 {
132     DOMPropertySet::setParent(parent);
133     pair<bool,const char*> loc = getString("Location");
134     init(loc.second);
135 }
136
137 void SAML2LogoutInitiator::init(const char* location)
138 {
139     if (location) {
140         string address = m_appId + location + "::run::SAML2LI";
141         setAddress(address.c_str());
142     }
143     else {
144         m_log.warn("no Location property in SAML2 LogoutInitiator (or parent), can't register as remoted handler");
145     }
146
147 #ifndef SHIBSP_LITE
148     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
149         string dupBindings;
150         pair<bool,const char*> outgoing = getString("outgoingBindings");
151         if (outgoing.first) {
152             dupBindings = outgoing.second;
153         }
154         else {
155             // No override, so we'll install a default binding precedence.
156             dupBindings = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
157                 samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
158         }
159         split(m_bindings, dupBindings, is_space(), algorithm::token_compress_on);
160         for (vector<string>::const_iterator b = m_bindings.begin(); b != m_bindings.end(); ++b) {
161             try {
162                 boost::shared_ptr<MessageEncoder> encoder(
163                     SAMLConfig::getConfig().MessageEncoderManager.newPlugin(*b, pair<const DOMElement*,const XMLCh*>(getElement(),nullptr))
164                     );
165                 if (encoder->isUserAgentPresent() && XMLString::equals(getProtocolFamily(), encoder->getProtocolFamily())) {
166                     m_encoders[*b] = encoder;
167                     m_log.debug("supporting outgoing binding (%s)", b->c_str());
168                 }
169                 else {
170                     m_log.warn("skipping outgoing binding (%s), not a SAML 2.0 front-channel mechanism", b->c_str());
171                 }
172             }
173             catch (std::exception& ex) {
174                 m_log.error("error building MessageEncoder: %s", ex.what());
175             }
176         }
177     }
178 #endif
179 }
180
181
182 pair<bool,long> SAML2LogoutInitiator::run(SPRequest& request, bool isHandler) const
183 {
184     // Defer to base class for front-channel loop first.
185     pair<bool,long> ret = LogoutHandler::run(request, isHandler);
186     if (ret.first)
187         return ret;
188
189     // At this point we know the front-channel is handled.
190     // We need the session to do any other work.
191
192     Session* session = nullptr;
193     try {
194         session = request.getSession(false, true, false);  // don't cache it and ignore all checks
195         if (!session)
196             return make_pair(false, 0L);
197
198         // We only handle SAML 2.0 sessions.
199         if (!XMLString::equals(session->getProtocol(), m_protocol.get())) {
200             session->unlock();
201             return make_pair(false, 0L);
202         }
203     }
204     catch (std::exception& ex) {
205         m_log.error("error accessing current session: %s", ex.what());
206         return make_pair(false, 0L);
207     }
208
209     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
210         // When out of process, we run natively.
211         return doRequest(request.getApplication(), request, request, session);
212     }
213     else {
214         // When not out of process, we remote the request.
215         session->unlock();
216         vector<string> headers(1,"Cookie");
217         DDF out,in = wrap(request,&headers);
218         DDFJanitor jin(in), jout(out);
219         out=request.getServiceProvider().getListenerService()->send(in);
220         return unwrap(request, out);
221     }
222 }
223
224 void SAML2LogoutInitiator::receive(DDF& in, ostream& out)
225 {
226 #ifndef SHIBSP_LITE
227     // Defer to base class for notifications
228     if (in["notify"].integer() == 1)
229         return LogoutHandler::receive(in, out);
230
231     // Find application.
232     const char* aid=in["application_id"].string();
233     const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
234     if (!app) {
235         // Something's horribly wrong.
236         m_log.error("couldn't find application (%s) for logout", aid ? aid : "(missing)");
237         throw ConfigurationException("Unable to locate application for logout, deleted?");
238     }
239
240     // Unpack the request.
241     scoped_ptr<HTTPRequest> req(getRequest(in));
242
243     // Set up a response shim.
244     DDF ret(nullptr);
245     DDFJanitor jout(ret);
246     scoped_ptr<HTTPResponse> resp(getResponse(ret));
247
248     Session* session = nullptr;
249     try {
250          session = app->getServiceProvider().getSessionCache()->find(*app, *req, nullptr, nullptr);
251     }
252     catch (std::exception& ex) {
253         m_log.error("error accessing current session: %s", ex.what());
254     }
255
256     // With no session, we just skip the request and let it fall through to an empty struct return.
257     if (session) {
258         if (session->getNameID() && session->getEntityID()) {
259             // Since we're remoted, the result should either be a throw, which we pass on,
260             // a false/0 return, which we just return as an empty structure, or a response/redirect,
261             // which we capture in the facade and send back.
262             doRequest(*app, *req, *resp, session);
263         }
264         else {
265             session->unlock();
266             m_log.log(getParent() ? Priority::WARN : Priority::ERROR, "bypassing SAML 2.0 logout, no NameID or issuing entityID found in session");
267             app->getServiceProvider().getSessionCache()->remove(*app, *req, resp.get());
268         }
269     }
270     out << ret;
271 #else
272     throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
273 #endif
274 }
275
276 pair<bool,long> SAML2LogoutInitiator::doRequest(
277     const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse, Session* session
278     ) const
279 {
280     Locker sessionLocker(session, false);
281 #ifndef SHIBSP_LITE
282     scoped_ptr<LogoutEvent> logout_event(newLogoutEvent(application, &httpRequest, session));
283 #endif
284
285     // Do back channel notification.
286     vector<string> sessions(1, session->getID());
287     if (!notifyBackChannel(application, httpRequest.getRequestURL(), sessions, false)) {
288 #ifndef SHIBSP_LITE
289         if (logout_event) {
290             logout_event->m_logoutType = LogoutEvent::LOGOUT_EVENT_PARTIAL;
291             application.getServiceProvider().getTransactionLog()->write(*logout_event);
292         }
293 #endif
294         sessionLocker.assign();
295         session = nullptr;
296         application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
297         return sendLogoutPage(application, httpRequest, httpResponse, "partial");
298     }
299
300 #ifndef SHIBSP_LITE
301     pair<bool,long> ret = make_pair(false, 0L);
302     try {
303         // With a session in hand, we can create a LogoutRequest message, if we can find a compatible endpoint.
304         MetadataProvider* m = application.getMetadataProvider();
305         Locker metadataLocker(m);
306         MetadataProviderCriteria mc(application, session->getEntityID(), &IDPSSODescriptor::ELEMENT_QNAME, samlconstants::SAML20P_NS);
307         pair<const EntityDescriptor*,const RoleDescriptor*> entity = m->getEntityDescriptor(mc);
308         if (!entity.first) {
309             throw MetadataException(
310                 "Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", session->getEntityID())
311                 );
312         }
313         else if (!entity.second) {
314             throw MetadataException(
315                 "Unable to locate SAML 2.0 IdP role for identity provider ($entityID).", namedparams(1, "entityID", session->getEntityID())
316                 );
317         }
318
319         const IDPSSODescriptor* role = dynamic_cast<const IDPSSODescriptor*>(entity.second);
320         if (role->getSingleLogoutServices().empty()) {
321             throw MetadataException(
322                 "No SingleLogoutService endpoints in metadata for identity provider ($entityID).", namedparams(1, "entityID", session->getEntityID())
323                 );
324         }
325
326         const EndpointType* ep = nullptr;
327         const MessageEncoder* encoder = nullptr;
328         for (vector<string>::const_iterator b = m_bindings.begin(); b != m_bindings.end(); ++b) {
329             auto_ptr_XMLCh wideb(b->c_str());
330             if (ep = EndpointManager<SingleLogoutService>(role->getSingleLogoutServices()).getByBinding(wideb.get())) {
331                 map< string,boost::shared_ptr<MessageEncoder> >::const_iterator enc = m_encoders.find(*b);
332                 if (enc != m_encoders.end())
333                     encoder = enc->second.get();
334                 break;
335             }
336         }
337         if (!ep || !encoder) {
338             m_log.debug("no compatible front channel SingleLogoutService, trying back channel...");
339             shibsp::SecurityPolicy policy(application);
340             shibsp::SOAPClient soaper(policy);
341             MetadataCredentialCriteria mcc(*role);
342
343             LogoutResponse* logoutResponse = nullptr;
344             scoped_ptr<StatusResponseType> srt;
345             auto_ptr_XMLCh binding(samlconstants::SAML20_BINDING_SOAP);
346             const vector<SingleLogoutService*>& endpoints = role->getSingleLogoutServices();
347             for (indirect_iterator<vector<SingleLogoutService*>::const_iterator> epit = make_indirect_iterator(endpoints.begin());
348                     !logoutResponse && epit != make_indirect_iterator(endpoints.end()); ++epit) {
349                 try {
350                     if (!XMLString::equals(epit->getBinding(), binding.get()))
351                         continue;
352                     auto_ptr<LogoutRequest> msg(buildRequest(application, *session, *role));
353
354                     // Log the request.
355                     if (logout_event) {
356                         logout_event->m_logoutType = LogoutEvent::LOGOUT_EVENT_UNKNOWN;
357                         logout_event->m_saml2Request = msg.get();
358                         application.getServiceProvider().getTransactionLog()->write(*logout_event);
359                     }
360
361                     auto_ptr_char dest(epit->getLocation());
362                     SAML2SOAPClient client(soaper, false);
363                     client.sendSAML(msg.release(), application.getId(), mcc, dest.get());
364                     srt.reset(client.receiveSAML());
365                     if (!(logoutResponse = dynamic_cast<LogoutResponse*>(srt.get()))) {
366                         break;
367                     }
368                 }
369                 catch (std::exception& ex) {
370                     m_log.error("error sending LogoutRequest message: %s", ex.what());
371                     soaper.reset();
372                 }
373             }
374
375             // No answer at all?
376             if (!logoutResponse) {
377                 if (endpoints.empty())
378                     m_log.info("IdP doesn't support single logout protocol over a compatible binding");
379                 else
380                     m_log.warn("IdP didn't respond to logout request");
381
382                 // Log the end result.
383                 if (logout_event) {
384                     logout_event->m_logoutType = LogoutEvent::LOGOUT_EVENT_PARTIAL;
385                     application.getServiceProvider().getTransactionLog()->write(*logout_event);
386                 }
387
388                 ret = sendLogoutPage(application, httpRequest, httpResponse, "partial");
389             }
390             else {
391                 // Check the status, looking for non-success or a partial logout code.
392                 const StatusCode* sc = logoutResponse->getStatus() ? logoutResponse->getStatus()->getStatusCode() : nullptr;
393                 bool partial = (!sc || !XMLString::equals(sc->getValue(), StatusCode::SUCCESS));
394                 if (!partial && sc->getStatusCode()) {
395                     // Success, but still need to check for partial.
396                     partial = XMLString::equals(sc->getStatusCode()->getValue(), StatusCode::PARTIAL_LOGOUT);
397                 }
398
399                 // Log the end result.
400                 if (logout_event) {
401                     logout_event->m_logoutType = partial ? LogoutEvent::LOGOUT_EVENT_PARTIAL : LogoutEvent::LOGOUT_EVENT_GLOBAL;
402                     logout_event->m_saml2Response = logoutResponse;
403                     application.getServiceProvider().getTransactionLog()->write(*logout_event);
404                 }
405
406                 if (partial)
407                     ret = sendLogoutPage(application, httpRequest, httpResponse, "partial");
408                 else {
409                     const char* returnloc = httpRequest.getParameter("return");
410                     if (returnloc) {
411                         // Relative URLs get promoted, absolutes get validated.
412                         if (*returnloc == '/') {
413                             string loc(returnloc);
414                             httpRequest.absolutize(loc);
415                             ret.second = httpResponse.sendRedirect(loc.c_str());
416                         }
417                         else {
418                             application.limitRedirect(httpRequest, returnloc);
419                             ret.second = httpResponse.sendRedirect(returnloc);
420                         }
421                         ret.first = true;
422                     }
423                     else {
424                         ret = sendLogoutPage(application, httpRequest, httpResponse, "global");
425                     }
426                 }
427             }
428
429             if (session) {
430                 sessionLocker.assign();
431                 session = nullptr;
432                 application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
433             }
434
435             return ret;
436         }
437
438         // Save off return location as RelayState.
439         string relayState;
440         const char* returnloc = httpRequest.getParameter("return");
441         if (returnloc) {
442             application.limitRedirect(httpRequest, returnloc);
443             relayState = returnloc;
444             httpRequest.absolutize(relayState);
445             cleanRelayState(application, httpRequest, httpResponse);
446             preserveRelayState(application, httpResponse, relayState);
447         }
448
449         auto_ptr<LogoutRequest> msg(buildRequest(application, *session, *role, encoder));
450         msg->setDestination(ep->getLocation());
451
452         // Log the request.
453         if (logout_event) {
454             logout_event->m_logoutType = LogoutEvent::LOGOUT_EVENT_UNKNOWN;
455             logout_event->m_saml2Request = msg.get();
456             application.getServiceProvider().getTransactionLog()->write(*logout_event);
457         }
458
459         auto_ptr_char dest(ep->getLocation());
460         ret.second = sendMessage(*encoder, msg.get(), relayState.c_str(), dest.get(), role, application, httpResponse, true);
461         ret.first = true;
462         msg.release();  // freed by encoder
463
464         if (session) {
465             sessionLocker.assign();
466             session = nullptr;
467             application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
468         }
469     }
470     catch (MetadataException& mex) {
471         // Less noise for IdPs that don't support logout (i.e. most)
472         m_log.info("unable to issue SAML 2.0 logout request: %s", mex.what());
473     }
474     catch (std::exception& ex) {
475         m_log.error("error issuing SAML 2.0 logout request: %s", ex.what());
476     }
477
478     return ret;
479 #else
480     throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
481 #endif
482 }
483
484 #ifndef SHIBSP_LITE
485
486 auto_ptr<LogoutRequest> SAML2LogoutInitiator::buildRequest(
487     const Application& application, const Session& session, const RoleDescriptor& role, const MessageEncoder* encoder
488     ) const
489 {
490     const PropertySet* relyingParty = application.getRelyingParty(dynamic_cast<EntityDescriptor*>(role.getParent()));
491
492     auto_ptr<LogoutRequest> msg(LogoutRequestBuilder::buildLogoutRequest());
493     Issuer* issuer = IssuerBuilder::buildIssuer();
494     msg->setIssuer(issuer);
495     issuer->setName(relyingParty->getXMLString("entityID").second);
496     auto_ptr_XMLCh index(session.getSessionIndex());
497     if (index.get() && *index.get()) {
498         SessionIndex* si = SessionIndexBuilder::buildSessionIndex();
499         msg->getSessionIndexs().push_back(si);
500         si->setSessionIndex(index.get());
501     }
502
503     const NameID* nameid = session.getNameID();
504     pair<bool,const char*> flag = relyingParty->getString("encryption");
505     if (flag.first &&
506         (!strcmp(flag.second, "true") || (encoder && !strcmp(flag.second, "front")) || (!encoder && !strcmp(flag.second, "back")))) {
507         auto_ptr<EncryptedID> encrypted(EncryptedIDBuilder::buildEncryptedID());
508         MetadataCredentialCriteria mcc(role);
509         encrypted->encrypt(
510             *nameid,
511             *(application.getMetadataProvider()),
512             mcc,
513             encoder ? encoder->isCompact() : false,
514             relyingParty->getXMLString("encryptionAlg").second
515             );
516         msg->setEncryptedID(encrypted.get());
517         encrypted.release();
518     }
519     else {
520         msg->setNameID(nameid->cloneNameID());
521     }
522
523     msg->setID(SAMLConfig::getConfig().generateIdentifier());
524     msg->setIssueInstant(time(nullptr));
525
526     return msg;
527 }
528
529 #endif