e5a6bbb8279575b6f7ae936143ca8353e59d55b8
[shibboleth/sp.git] / shibsp / handler / impl / SAML2LogoutInitiator.cpp
1 /*
2  *  Copyright 2001-2007 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 <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;
43 #else
44 # include "lite/SAMLConstants.h"
45 #endif
46
47 using namespace shibsp;
48 using namespace xmltooling;
49 using namespace std;
50
51 namespace shibsp {
52
53 #if defined (_MSC_VER)
54     #pragma warning( push )
55     #pragma warning( disable : 4250 )
56 #endif
57
58     class SHIBSP_DLLLOCAL SAML2LogoutInitiator : public AbstractHandler, public LogoutHandler
59     {
60     public:
61         SAML2LogoutInitiator(const DOMElement* e, const char* appId);
62         virtual ~SAML2LogoutInitiator() {
63 #ifndef SHIBSP_LITE
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>());
67             }
68 #endif
69         }
70
71         void setParent(const PropertySet* parent);
72         void receive(DDF& in, ostream& out);
73         pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
74
75 #ifndef SHIBSP_LITE
76         const char* getType() const {
77             return "LogoutInitiator";
78         }
79 #endif
80
81     private:
82         pair<bool,long> doRequest(
83             const Application& application, const HTTPRequest& request, HTTPResponse& httpResponse, Session* session
84             ) const;
85
86         string m_appId;
87 #ifndef SHIBSP_LITE
88         LogoutRequest* buildRequest(
89             const Application& application, const Session& session, const RoleDescriptor& role, const MessageEncoder* encoder=NULL
90             ) const;
91
92         XMLCh* m_outgoing;
93         vector<const XMLCh*> m_bindings;
94         map<const XMLCh*,MessageEncoder*> m_encoders;
95 #endif
96         auto_ptr_char m_protocol;
97     };
98
99 #if defined (_MSC_VER)
100     #pragma warning( pop )
101 #endif
102
103     Handler* SHIBSP_DLLLOCAL SAML2LogoutInitiatorFactory(const pair<const DOMElement*,const char*>& p)
104     {
105         return new SAML2LogoutInitiator(p.first, p.second);
106     }
107 };
108
109 SAML2LogoutInitiator::SAML2LogoutInitiator(const DOMElement* e, const char* appId)
110     : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".LogoutInitiator.SAML2")), m_appId(appId),
111 #ifndef SHIBSP_LITE
112         m_outgoing(NULL),
113 #endif
114         m_protocol(samlconstants::SAML20P_NS)
115 {
116 #ifndef SHIBSP_LITE
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);
123         }
124         else {
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());
129         }
130
131         int pos;
132         XMLCh* start = m_outgoing;
133         while (start && *start) {
134             pos = XMLString::indexOf(start,chSpace);
135             if (pos != -1)
136                 *(start + pos)=chNull;
137             m_bindings.push_back(start);
138             try {
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());
144             }
145             catch (exception& ex) {
146                 m_log.error("error building MessageEncoder: %s", ex.what());
147             }
148             if (pos != -1)
149                 start = start + pos + 1;
150             else
151                 break;
152         }
153     }
154 #endif
155
156     pair<bool,const char*> loc = getString("Location");
157     if (loc.first) {
158         string address = m_appId + loc.second + "::run::SAML2LI";
159         setAddress(address.c_str());
160     }
161 }
162
163 void SAML2LogoutInitiator::setParent(const PropertySet* parent)
164 {
165     DOMPropertySet::setParent(parent);
166     pair<bool,const char*> loc = getString("Location");
167     if (loc.first) {
168         string address = m_appId + loc.second + "::run::SAML2LI";
169         setAddress(address.c_str());
170     }
171     else {
172         m_log.warn("no Location property in SAML2 LogoutInitiator (or parent), can't register as remoted handler");
173     }
174 }
175
176 pair<bool,long> SAML2LogoutInitiator::run(SPRequest& request, bool isHandler) const
177 {
178     // Defer to base class for front-channel loop first.
179     pair<bool,long> ret = LogoutHandler::run(request, isHandler);
180     if (ret.first)
181         return ret;
182
183     // At this point we know the front-channel is handled.
184     // We need the session to do any other work.
185
186     Session* session = NULL;
187     try {
188         session = request.getSession(false, true, false);  // don't cache it and ignore all checks
189         if (!session)
190             return make_pair(false,0L);
191
192         // We only handle SAML 2.0 sessions.
193         if (!XMLString::equals(session->getProtocol(), m_protocol.get())) {
194             session->unlock();
195             return make_pair(false,0L);
196         }
197     }
198     catch (exception& ex) {
199         m_log.error("error accessing current session: %s", ex.what());
200         return make_pair(false,0L);
201     }
202
203     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
204         // When out of process, we run natively.
205         return doRequest(request.getApplication(), request, request, session);
206     }
207     else {
208         // When not out of process, we remote the request.
209         session->unlock();
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);
215     }
216 }
217
218 void SAML2LogoutInitiator::receive(DDF& in, ostream& out)
219 {
220 #ifndef SHIBSP_LITE
221     // Defer to base class for notifications
222     if (in["notify"].integer() == 1)
223         return LogoutHandler::receive(in, out);
224
225     // Find application.
226     const char* aid=in["application_id"].string();
227     const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
228     if (!app) {
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?");
232     }
233
234     // Unpack the request.
235     auto_ptr<HTTPRequest> req(getRequest(in));
236
237     // Set up a response shim.
238     DDF ret(NULL);
239     DDFJanitor jout(ret);
240     auto_ptr<HTTPResponse> resp(getResponse(ret));
241
242     Session* session = NULL;
243     try {
244          session = app->getServiceProvider().getSessionCache()->find(*app, *req.get(), NULL, NULL);
245     }
246     catch (exception& ex) {
247         m_log.error("error accessing current session: %s", ex.what());
248     }
249
250     // With no session, we just skip the request and let it fall through to an empty struct return.
251     if (session) {
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);
257         }
258         else {
259              m_log.error("no NameID or issuing entityID found in session");
260              session->unlock();
261              app->getServiceProvider().getSessionCache()->remove(*app, *req.get(), resp.get());
262         }
263     }
264     out << ret;
265 #else
266     throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
267 #endif
268 }
269
270 pair<bool,long> SAML2LogoutInitiator::doRequest(
271     const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse, Session* session
272     ) const
273 {
274     // Do back channel notification.
275     vector<string> sessions(1, session->getID());
276     if (!notifyBackChannel(application, httpRequest.getRequestURL(), sessions, false)) {
277         session->unlock();
278         application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
279         return sendLogoutPage(application, httpRequest, httpResponse, true, "Partial logout failure.");
280     }
281
282 #ifndef SHIBSP_LITE
283     pair<bool,long> ret = make_pair(false,0L);
284     try {
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);
290         if (!entity.first) {
291             throw MetadataException(
292                 "Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", session->getEntityID())
293                 );
294         }
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())
298                 );
299         }
300
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;
310                 break;
311             }
312         }
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);
318
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) {
323                 try {
324                     if (!XMLString::equals((*epit)->getBinding(),binding.get()))
325                         continue;
326                     LogoutRequest* msg = buildRequest(application, *session, *role);
327                     auto_ptr_char dest((*epit)->getLocation());
328
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))) {
333                         delete srt;
334                         break;
335                     }
336                 }
337                 catch (exception& ex) {
338                     m_log.error("error sending LogoutRequest message: %s", ex.what());
339                     soaper.reset();
340                 }
341             }
342
343             if (!logoutResponse) {
344                 ret = sendLogoutPage(
345                     application, httpRequest, httpResponse, false,
346                     endpoints.empty() ?
347                         "Identity provider does not support SAML 2 Single Logout protocol." :
348                             "Identity provider did not respond to logout request."
349                     );
350             }
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.");
355             }
356             else {
357                 delete logoutResponse;
358                 const char* returnloc = httpRequest.getParameter("return");
359                 if (returnloc) {
360                     ret.second = httpResponse.sendRedirect(returnloc);
361                     ret.first = true;
362                 }
363                 ret = sendLogoutPage(application, httpRequest, httpResponse, false, "Logout completed successfully.");
364             }
365
366             if (session) {
367                 session->unlock();
368                 session = NULL;
369                 application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
370             }
371             return ret;
372         }
373
374         // Save off return location as RelayState.
375         string relayState;
376         const char* returnloc = httpRequest.getParameter("return");
377         if (returnloc) {
378             relayState = returnloc;
379             preserveRelayState(application, httpResponse, relayState);
380         }
381
382         auto_ptr<LogoutRequest> msg(buildRequest(application, *session, *role, encoder));
383
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);
387         ret.first = true;
388         msg.release();  // freed by encoder
389     }
390     catch (exception& ex) {
391         m_log.error("error issuing SAML 2.0 logout request: %s", ex.what());
392     }
393
394     if (session) {
395         session->unlock();
396         session = NULL;
397         application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
398     }
399
400     return ret;
401 #else
402     session->unlock();
403     application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
404     throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
405 #endif
406 }
407
408 #ifndef SHIBSP_LITE
409
410 LogoutRequest* SAML2LogoutInitiator::buildRequest(
411     const Application& application, const Session& session, const RoleDescriptor& role, const MessageEncoder* encoder
412     ) const
413 {
414     const PropertySet* relyingParty = application.getRelyingParty(dynamic_cast<EntityDescriptor*>(role.getParent()));
415
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());
425     }
426
427     const NameID* nameid = session.getNameID();
428     pair<bool,const char*> flag = relyingParty->getString("encryption");
429     if (flag.first &&
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);
433         encrypted->encrypt(
434             *nameid,
435             *(application.getMetadataProvider()),
436             mcc,
437             encoder ? encoder->isCompact() : false,
438             relyingParty->getXMLString("encryptionAlg").second
439             );
440         msg->setEncryptedID(encrypted.release());
441     }
442     else {
443         msg->setNameID(nameid->cloneNameID());
444     }
445
446     if (!encoder) {
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();
451             if (credResolver) {
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");
457                 if (keyName.first)
458                     mcc.getKeyNames().insert(keyName.second);
459                 pair<bool,const XMLCh*> sigalg = relyingParty->getXMLString("signingAlg");
460                 if (sigalg.first)
461                     mcc.setXMLAlgorithm(sigalg.second);
462                 const Credential* cred = credResolver->resolve(&mcc);
463                 if (cred) {
464                     xmlsignature::Signature* sig = xmlsignature::SignatureBuilder::buildSignature();
465                     msg->setSignature(sig);
466                     if (sigalg.first)
467                         sig->setSignatureAlgorithm(sigalg.second);
468                     sigalg = relyingParty->getXMLString("digestAlg");
469                     if (sigalg.first) {
470                         ContentReference* cr = dynamic_cast<ContentReference*>(sig->getContentReference());
471                         if (cr)
472                             cr->setDigestAlgorithm(sigalg.second);
473                     }
474
475                     // Sign response while marshalling.
476                     vector<xmlsignature::Signature*> sigs(1,sig);
477                     msg->marshall((DOMDocument*)NULL,&sigs,cred);
478                 }
479                 else {
480                     m_log.warn("no signing credential resolved, leaving message unsigned");
481                 }
482             }
483             else {
484                 m_log.warn("no credential resolver installed, leaving message unsigned");
485             }
486         }
487     }
488
489     return msg.release();
490 }
491
492 #endif