5f50712080d7b8da425da8e18b331209c20597be
[shibboleth/cpp-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(application, httpRequest, httpResponse, false, "Identity provider did not respond to logout request.");
345             else if (!logoutResponse->getStatus() || !logoutResponse->getStatus()->getStatusCode() ||
346                    !XMLString::equals(logoutResponse->getStatus()->getStatusCode()->getValue(), saml2p::StatusCode::SUCCESS)) {
347                 delete logoutResponse;
348                 ret = sendLogoutPage(application, httpRequest, httpResponse, false, "Identity provider returned a SAML error in response to logout request.");
349             }
350             else {
351                 delete logoutResponse;
352                 const char* returnloc = httpRequest.getParameter("return");
353                 if (returnloc) {
354                     ret.second = httpResponse.sendRedirect(returnloc);
355                     ret.first = true;
356                 }
357                 ret = sendLogoutPage(application, httpRequest, httpResponse, false, "Logout completed successfully.");
358             }
359
360             if (session) {
361                 session->unlock();
362                 session = NULL;
363                 application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
364             }
365             return ret;
366         }
367
368         // Save off return location as RelayState.
369         string relayState;
370         const char* returnloc = httpRequest.getParameter("return");
371         if (returnloc) {
372             relayState = returnloc;
373             preserveRelayState(application, httpResponse, relayState);
374         }
375
376         auto_ptr<LogoutRequest> msg(buildRequest(application, *session, *role, encoder));
377
378         msg->setDestination(ep->getLocation());
379         auto_ptr_char dest(ep->getLocation());
380         ret.second = sendMessage(*encoder, msg.get(), relayState.c_str(), dest.get(), role, application, httpResponse);
381         ret.first = true;
382         msg.release();  // freed by encoder
383     }
384     catch (exception& ex) {
385         m_log.error("error issuing SAML 2.0 logout request: %s", ex.what());
386     }
387
388     if (session) {
389         session->unlock();
390         session = NULL;
391         application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
392     }
393
394     return ret;
395 #else
396     session->unlock();
397     application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
398     throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
399 #endif
400 }
401
402 #ifndef SHIBSP_LITE
403
404 LogoutRequest* SAML2LogoutInitiator::buildRequest(
405     const Application& application, const Session& session, const RoleDescriptor& role, const MessageEncoder* encoder
406     ) const
407 {
408     const PropertySet* relyingParty = application.getRelyingParty(dynamic_cast<EntityDescriptor*>(role.getParent()));
409
410     auto_ptr<LogoutRequest> msg(LogoutRequestBuilder::buildLogoutRequest());
411     Issuer* issuer = IssuerBuilder::buildIssuer();
412     msg->setIssuer(issuer);
413     issuer->setName(relyingParty->getXMLString("entityID").second);
414     auto_ptr_XMLCh index(session.getSessionIndex());
415     if (index.get() && *index.get()) {
416         SessionIndex* si = SessionIndexBuilder::buildSessionIndex();
417         msg->getSessionIndexs().push_back(si);
418         si->setSessionIndex(index.get());
419     }
420
421     const NameID* nameid = session.getNameID();
422     pair<bool,const char*> flag = relyingParty->getString("encryption");
423     if (flag.first &&
424         (!strcmp(flag.second, "true") || (encoder && !strcmp(flag.second, "front")) || (!encoder && !strcmp(flag.second, "back")))) {
425         auto_ptr<EncryptedID> encrypted(EncryptedIDBuilder::buildEncryptedID());
426         MetadataCredentialCriteria mcc(role);
427         encrypted->encrypt(
428             *nameid,
429             *(application.getMetadataProvider()),
430             mcc,
431             encoder ? encoder->isCompact() : false,
432             relyingParty->getXMLString("encryptionAlg").second
433             );
434         msg->setEncryptedID(encrypted.release());
435     }
436     else {
437         msg->setNameID(nameid->cloneNameID());
438     }
439
440     if (!encoder) {
441         // No encoder being used, so sign for SOAP client manually.
442         flag = relyingParty->getString("signing");
443         if (flag.first && (!strcmp(flag.second, "true") || !strcmp(flag.second, "back"))) {
444             CredentialResolver* credResolver=application.getCredentialResolver();
445             if (credResolver) {
446                 Locker credLocker(credResolver);
447                 // Fill in criteria to use.
448                 MetadataCredentialCriteria mcc(role);
449                 mcc.setUsage(Credential::SIGNING_CREDENTIAL);
450                 pair<bool,const char*> keyName = relyingParty->getString("keyName");
451                 if (keyName.first)
452                     mcc.getKeyNames().insert(keyName.second);
453                 pair<bool,const XMLCh*> sigalg = relyingParty->getXMLString("signingAlg");
454                 if (sigalg.first)
455                     mcc.setXMLAlgorithm(sigalg.second);
456                 const Credential* cred = credResolver->resolve(&mcc);
457                 if (cred) {
458                     xmlsignature::Signature* sig = xmlsignature::SignatureBuilder::buildSignature();
459                     msg->setSignature(sig);
460                     if (sigalg.first)
461                         sig->setSignatureAlgorithm(sigalg.second);
462                     sigalg = relyingParty->getXMLString("digestAlg");
463                     if (sigalg.first) {
464                         ContentReference* cr = dynamic_cast<ContentReference*>(sig->getContentReference());
465                         if (cr)
466                             cr->setDigestAlgorithm(sigalg.second);
467                     }
468             
469                     // Sign response while marshalling.
470                     vector<xmlsignature::Signature*> sigs(1,sig);
471                     msg->marshall((DOMDocument*)NULL,&sigs,cred);
472                 }
473                 else {
474                     m_log.warn("no signing credential resolved, leaving message unsigned");
475                 }
476             }
477             else {
478                 m_log.warn("no credential resolver installed, leaving message unsigned");
479             }
480         }
481     }
482
483     return msg.release();
484 }
485
486 #endif