1dc10d6efda1af6f3e8ac65586b3536a77171220
[shibboleth/sp.git] / shibsp / handler / impl / SAML2LogoutInitiator.cpp
1 /*
2  *  Copyright 2001-2010 Internet2
3  *
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
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 /**
18  * SAML2LogoutInitiator.cpp
19  *
20  * Triggers SP-initiated logout for SAML 2.0 sessions.
21  */
22
23 #include "internal.h"
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"
30
31 #ifndef SHIBSP_LITE
32 # include "binding/SOAPClient.h"
33 # include "metadata/MetadataProviderCriteria.h"
34 # include "security/SecurityPolicy.h"
35 # include <saml/exceptions.h>
36 # include <saml/SAMLConfig.h>
37 # include <saml/saml2/core/Protocols.h>
38 # include <saml/saml2/binding/SAML2SOAPClient.h>
39 # include <saml/saml2/metadata/EndpointManager.h>
40 # include <saml/saml2/metadata/Metadata.h>
41 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
42 using namespace opensaml::saml2;
43 using namespace opensaml::saml2p;
44 using namespace opensaml::saml2md;
45 using namespace opensaml;
46 #else
47 # include "lite/SAMLConstants.h"
48 #endif
49
50 using namespace shibsp;
51 using namespace xmltooling;
52 using namespace std;
53
54 namespace shibsp {
55
56 #if defined (_MSC_VER)
57     #pragma warning( push )
58     #pragma warning( disable : 4250 )
59 #endif
60
61     class SHIBSP_DLLLOCAL SAML2LogoutInitiator : public AbstractHandler, public LogoutHandler
62     {
63     public:
64         SAML2LogoutInitiator(const DOMElement* e, const char* appId);
65         virtual ~SAML2LogoutInitiator() {
66 #ifndef SHIBSP_LITE
67             if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
68                 XMLString::release(&m_outgoing);
69                 for_each(m_encoders.begin(), m_encoders.end(), cleanup_pair<const XMLCh*,MessageEncoder>());
70             }
71 #endif
72         }
73
74         void setParent(const PropertySet* parent);
75         void receive(DDF& in, ostream& out);
76         pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
77
78 #ifndef SHIBSP_LITE
79         const char* getType() const {
80             return "LogoutInitiator";
81         }
82 #endif
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         LogoutRequest* buildRequest(
92             const Application& application, const Session& session, const RoleDescriptor& role, const MessageEncoder* encoder=NULL
93             ) const;
94
95         XMLCh* m_outgoing;
96         vector<const XMLCh*> m_bindings;
97         map<const XMLCh*,MessageEncoder*> m_encoders;
98 #endif
99         auto_ptr_char m_protocol;
100     };
101
102 #if defined (_MSC_VER)
103     #pragma warning( pop )
104 #endif
105
106     Handler* SHIBSP_DLLLOCAL SAML2LogoutInitiatorFactory(const pair<const DOMElement*,const char*>& p)
107     {
108         return new SAML2LogoutInitiator(p.first, p.second);
109     }
110 };
111
112 SAML2LogoutInitiator::SAML2LogoutInitiator(const DOMElement* e, const char* appId)
113     : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".LogoutInitiator.SAML2")), m_appId(appId),
114 #ifndef SHIBSP_LITE
115         m_outgoing(NULL),
116 #endif
117         m_protocol(samlconstants::SAML20P_NS)
118 {
119 #ifndef SHIBSP_LITE
120     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
121         // Handle outgoing binding setup.
122         pair<bool,const XMLCh*> outgoing = getXMLString("outgoingBindings");
123         if (outgoing.first) {
124             m_outgoing = XMLString::replicate(outgoing.second);
125             XMLString::trim(m_outgoing);
126         }
127         else {
128             // No override, so we'll install a default binding precedence.
129             string prec = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
130                 samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
131             m_outgoing = XMLString::transcode(prec.c_str());
132         }
133
134         int pos;
135         XMLCh* start = m_outgoing;
136         while (start && *start) {
137             pos = XMLString::indexOf(start,chSpace);
138             if (pos != -1)
139                 *(start + pos)=chNull;
140             m_bindings.push_back(start);
141             try {
142                 auto_ptr_char b(start);
143                 MessageEncoder * encoder =
144                     SAMLConfig::getConfig().MessageEncoderManager.newPlugin(b.get(),pair<const DOMElement*,const XMLCh*>(e,NULL));
145                 if (encoder->isUserAgentPresent()) {
146                     m_encoders[start] = encoder;
147                     m_log.debug("supporting outgoing binding (%s)", b.get());
148                 }
149                 else {
150                     delete encoder;
151                     m_log.warn("skipping outgoing binding (%s), not a front-channel mechanism", b.get());
152                 }
153             }
154             catch (exception& ex) {
155                 m_log.error("error building MessageEncoder: %s", ex.what());
156             }
157             if (pos != -1)
158                 start = start + pos + 1;
159             else
160                 break;
161         }
162     }
163 #endif
164
165     pair<bool,const char*> loc = getString("Location");
166     if (loc.first) {
167         string address = m_appId + loc.second + "::run::SAML2LI";
168         setAddress(address.c_str());
169     }
170 }
171
172 void SAML2LogoutInitiator::setParent(const PropertySet* parent)
173 {
174     DOMPropertySet::setParent(parent);
175     pair<bool,const char*> loc = getString("Location");
176     if (loc.first) {
177         string address = m_appId + loc.second + "::run::SAML2LI";
178         setAddress(address.c_str());
179     }
180     else {
181         m_log.warn("no Location property in SAML2 LogoutInitiator (or parent), can't register as remoted handler");
182     }
183 }
184
185 pair<bool,long> SAML2LogoutInitiator::run(SPRequest& request, bool isHandler) const
186 {
187     // Defer to base class for front-channel loop first.
188     pair<bool,long> ret = LogoutHandler::run(request, isHandler);
189     if (ret.first)
190         return ret;
191
192     // At this point we know the front-channel is handled.
193     // We need the session to do any other work.
194
195     Session* session = NULL;
196     try {
197         session = request.getSession(false, true, false);  // don't cache it and ignore all checks
198         if (!session)
199             return make_pair(false,0L);
200
201         // We only handle SAML 2.0 sessions.
202         if (!XMLString::equals(session->getProtocol(), m_protocol.get())) {
203             session->unlock();
204             return make_pair(false,0L);
205         }
206     }
207     catch (exception& ex) {
208         m_log.error("error accessing current session: %s", ex.what());
209         return make_pair(false,0L);
210     }
211
212     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
213         // When out of process, we run natively.
214         return doRequest(request.getApplication(), request, request, session);
215     }
216     else {
217         // When not out of process, we remote the request.
218         session->unlock();
219         vector<string> headers(1,"Cookie");
220         DDF out,in = wrap(request,&headers);
221         DDFJanitor jin(in), jout(out);
222         out=request.getServiceProvider().getListenerService()->send(in);
223         return unwrap(request, out);
224     }
225 }
226
227 void SAML2LogoutInitiator::receive(DDF& in, ostream& out)
228 {
229 #ifndef SHIBSP_LITE
230     // Defer to base class for notifications
231     if (in["notify"].integer() == 1)
232         return LogoutHandler::receive(in, out);
233
234     // Find application.
235     const char* aid=in["application_id"].string();
236     const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
237     if (!app) {
238         // Something's horribly wrong.
239         m_log.error("couldn't find application (%s) for logout", aid ? aid : "(missing)");
240         throw ConfigurationException("Unable to locate application for logout, deleted?");
241     }
242
243     // Unpack the request.
244     auto_ptr<HTTPRequest> req(getRequest(in));
245
246     // Set up a response shim.
247     DDF ret(NULL);
248     DDFJanitor jout(ret);
249     auto_ptr<HTTPResponse> resp(getResponse(ret));
250
251     Session* session = NULL;
252     try {
253          session = app->getServiceProvider().getSessionCache()->find(*app, *req.get(), NULL, NULL);
254     }
255     catch (exception& ex) {
256         m_log.error("error accessing current session: %s", ex.what());
257     }
258
259     // With no session, we just skip the request and let it fall through to an empty struct return.
260     if (session) {
261         if (session->getNameID() && session->getEntityID()) {
262             // Since we're remoted, the result should either be a throw, which we pass on,
263             // a false/0 return, which we just return as an empty structure, or a response/redirect,
264             // which we capture in the facade and send back.
265             doRequest(*app, *req.get(), *resp.get(), session);
266         }
267         else {
268              m_log.log(getParent() ? Priority::WARN : Priority::ERROR, "bypassing SAML 2.0 logout, no NameID or issuing entityID found in session");
269              session->unlock();
270              app->getServiceProvider().getSessionCache()->remove(*app, *req.get(), resp.get());
271         }
272     }
273     out << ret;
274 #else
275     throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
276 #endif
277 }
278
279 pair<bool,long> SAML2LogoutInitiator::doRequest(
280     const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse, Session* session
281     ) const
282 {
283     // Do back channel notification.
284     vector<string> sessions(1, session->getID());
285     if (!notifyBackChannel(application, httpRequest.getRequestURL(), sessions, false)) {
286         session->unlock();
287         application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
288         return sendLogoutPage(application, httpRequest, httpResponse, "partial");
289     }
290
291 #ifndef SHIBSP_LITE
292     pair<bool,long> ret = make_pair(false,0L);
293     try {
294         // With a session in hand, we can create a LogoutRequest message, if we can find a compatible endpoint.
295         MetadataProvider* m = application.getMetadataProvider();
296         Locker metadataLocker(m);
297         MetadataProviderCriteria mc(application, session->getEntityID(), &IDPSSODescriptor::ELEMENT_QNAME, samlconstants::SAML20P_NS);
298         pair<const EntityDescriptor*,const RoleDescriptor*> entity = m->getEntityDescriptor(mc);
299         if (!entity.first) {
300             throw MetadataException(
301                 "Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", session->getEntityID())
302                 );
303         }
304         else if (!entity.second) {
305             throw MetadataException(
306                 "Unable to locate SAML 2.0 IdP role for identity provider ($entityID).", namedparams(1, "entityID", session->getEntityID())
307                 );
308         }
309
310         const IDPSSODescriptor* role = dynamic_cast<const IDPSSODescriptor*>(entity.second);
311         if (role->getSingleLogoutServices().empty()) {
312             throw MetadataException(
313                 "No SingleLogoutService endpoints in metadata for identity provider ($entityID).", namedparams(1, "entityID", session->getEntityID())
314                 );
315         }
316
317         const EndpointType* ep=NULL;
318         const MessageEncoder* encoder=NULL;
319         vector<const XMLCh*>::const_iterator b;
320         for (b = m_bindings.begin(); b!=m_bindings.end(); ++b) {
321             if (ep=EndpointManager<SingleLogoutService>(role->getSingleLogoutServices()).getByBinding(*b)) {
322                 map<const XMLCh*,MessageEncoder*>::const_iterator enc = m_encoders.find(*b);
323                 if (enc!=m_encoders.end())
324                     encoder = enc->second;
325                 break;
326             }
327         }
328         if (!ep || !encoder) {
329             m_log.debug("no compatible front channel SingleLogoutService, trying back channel...");
330             shibsp::SecurityPolicy policy(application);
331             shibsp::SOAPClient soaper(policy);
332             MetadataCredentialCriteria mcc(*role);
333
334             LogoutResponse* logoutResponse=NULL;
335             auto_ptr_XMLCh binding(samlconstants::SAML20_BINDING_SOAP);
336             const vector<SingleLogoutService*>& endpoints=role->getSingleLogoutServices();
337             for (vector<SingleLogoutService*>::const_iterator epit=endpoints.begin(); !logoutResponse && epit!=endpoints.end(); ++epit) {
338                 try {
339                     if (!XMLString::equals((*epit)->getBinding(),binding.get()))
340                         continue;
341                     LogoutRequest* msg = buildRequest(application, *session, *role);
342                     auto_ptr_char dest((*epit)->getLocation());
343
344                     SAML2SOAPClient client(soaper, false);
345                     client.sendSAML(msg, application.getId(), mcc, dest.get());
346                     StatusResponseType* srt = client.receiveSAML();
347                     if (!(logoutResponse = dynamic_cast<LogoutResponse*>(srt))) {
348                         delete srt;
349                         break;
350                     }
351                 }
352                 catch (exception& ex) {
353                     m_log.error("error sending LogoutRequest message: %s", ex.what());
354                     soaper.reset();
355                 }
356             }
357
358             // No answer at all?
359             if (!logoutResponse) {
360                 if (endpoints.empty())
361                     m_log.info("IdP doesn't support single logout protocol over a compatible binding");
362                 else
363                     m_log.warn("IdP didn't respond to logout request");
364                 ret = sendLogoutPage(application, httpRequest, httpResponse, "partial");
365             }
366             else {
367                 // Check the status, looking for non-success or a partial logout code.
368                 const StatusCode* sc = logoutResponse->getStatus() ? logoutResponse->getStatus()->getStatusCode() : NULL;
369                 bool partial = (!sc || !XMLString::equals(sc->getValue(), StatusCode::SUCCESS));
370                 if (!partial && sc->getStatusCode()) {
371                     // Success, but still need to check for partial.
372                     partial = XMLString::equals(sc->getStatusCode()->getValue(), StatusCode::PARTIAL_LOGOUT);
373                 }
374                 delete logoutResponse;
375                 if (partial)
376                     ret = sendLogoutPage(application, httpRequest, httpResponse, "partial");
377                 else {
378                     const char* returnloc = httpRequest.getParameter("return");
379                     if (returnloc) {
380                         ret.second = httpResponse.sendRedirect(returnloc);
381                         ret.first = true;
382                     }
383                     ret = sendLogoutPage(application, httpRequest, httpResponse, "global");
384                 }
385             }
386
387             if (session) {
388                 session->unlock();
389                 session = NULL;
390                 application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
391             }
392
393             return ret;
394         }
395
396         // Save off return location as RelayState.
397         string relayState;
398         const char* returnloc = httpRequest.getParameter("return");
399         if (returnloc) {
400             relayState = returnloc;
401             preserveRelayState(application, httpResponse, relayState);
402         }
403
404         auto_ptr<LogoutRequest> msg(buildRequest(application, *session, *role, encoder));
405
406         msg->setDestination(ep->getLocation());
407         auto_ptr_char dest(ep->getLocation());
408         ret.second = sendMessage(*encoder, msg.get(), relayState.c_str(), dest.get(), role, application, httpResponse);
409         ret.first = true;
410         msg.release();  // freed by encoder
411     }
412     catch (exception& ex) {
413         m_log.error("error issuing SAML 2.0 logout request: %s", ex.what());
414     }
415
416     if (session) {
417         session->unlock();
418         session = NULL;
419         application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
420     }
421
422     return ret;
423 #else
424     session->unlock();
425     application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
426     throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
427 #endif
428 }
429
430 #ifndef SHIBSP_LITE
431
432 LogoutRequest* SAML2LogoutInitiator::buildRequest(
433     const Application& application, const Session& session, const RoleDescriptor& role, const MessageEncoder* encoder
434     ) const
435 {
436     const PropertySet* relyingParty = application.getRelyingParty(dynamic_cast<EntityDescriptor*>(role.getParent()));
437
438     auto_ptr<LogoutRequest> msg(LogoutRequestBuilder::buildLogoutRequest());
439     Issuer* issuer = IssuerBuilder::buildIssuer();
440     msg->setIssuer(issuer);
441     issuer->setName(relyingParty->getXMLString("entityID").second);
442     auto_ptr_XMLCh index(session.getSessionIndex());
443     if (index.get() && *index.get()) {
444         SessionIndex* si = SessionIndexBuilder::buildSessionIndex();
445         msg->getSessionIndexs().push_back(si);
446         si->setSessionIndex(index.get());
447     }
448
449     const NameID* nameid = session.getNameID();
450     pair<bool,const char*> flag = relyingParty->getString("encryption");
451     if (flag.first &&
452         (!strcmp(flag.second, "true") || (encoder && !strcmp(flag.second, "front")) || (!encoder && !strcmp(flag.second, "back")))) {
453         auto_ptr<EncryptedID> encrypted(EncryptedIDBuilder::buildEncryptedID());
454         MetadataCredentialCriteria mcc(role);
455         encrypted->encrypt(
456             *nameid,
457             *(application.getMetadataProvider()),
458             mcc,
459             encoder ? encoder->isCompact() : false,
460             relyingParty->getXMLString("encryptionAlg").second
461             );
462         msg->setEncryptedID(encrypted.release());
463     }
464     else {
465         msg->setNameID(nameid->cloneNameID());
466     }
467
468     return msg.release();
469 }
470
471 #endif