4a0f630600be29263154b5670daf368466a08e27
[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 <saml/SAMLConfig.h>
34 # include <saml/saml2/core/Protocols.h>
35 # include <saml/saml2/binding/SAML2SOAPClient.h>
36 # include <saml/saml2/metadata/EndpointManager.h>
37 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
38 using namespace opensaml::saml2;
39 using namespace opensaml::saml2p;
40 using namespace opensaml::saml2md;
41 using namespace opensaml;
42 #else
43 # include "lite/SAMLConstants.h"
44 #endif
45
46 using namespace shibsp;
47 using namespace xmltooling;
48 using namespace log4cpp;
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     private:
76         pair<bool,long> doRequest(const Application& application, Session* session_id, HTTPResponse& httpResponse) const;
77
78         string m_appId;
79 #ifndef SHIBSP_LITE
80         LogoutRequest* buildRequest(
81             const Application& application, const Session& session, const IDPSSODescriptor& role, const MessageEncoder* encoder=NULL
82             ) const;
83
84         XMLCh* m_outgoing;
85         vector<const XMLCh*> m_bindings;
86         map<const XMLCh*,MessageEncoder*> m_encoders;
87 #endif
88         auto_ptr_char m_protocol;
89     };
90
91 #if defined (_MSC_VER)
92     #pragma warning( pop )
93 #endif
94
95     Handler* SHIBSP_DLLLOCAL SAML2LogoutInitiatorFactory(const pair<const DOMElement*,const char*>& p)
96     {
97         return new SAML2LogoutInitiator(p.first, p.second);
98     }
99 };
100
101 SAML2LogoutInitiator::SAML2LogoutInitiator(const DOMElement* e, const char* appId)
102     : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".LogoutInitiator")), m_appId(appId),
103 #ifndef SHIBSP_LITE
104         m_outgoing(NULL),
105 #endif
106         m_protocol(samlconstants::SAML20P_NS)
107 {
108 #ifndef SHIBSP_LITE
109     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
110         // Handle outgoing binding setup.
111         pair<bool,const XMLCh*> outgoing = getXMLString("outgoingBindings");
112         if (outgoing.first) {
113             m_outgoing = XMLString::replicate(outgoing.second);
114             XMLString::trim(m_outgoing);
115         }
116         else {
117             // No override, so we'll install a default binding precedence.
118             string prec = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
119                 samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
120             m_outgoing = XMLString::transcode(prec.c_str());
121         }
122
123         int pos;
124         XMLCh* start = m_outgoing;
125         while (start && *start) {
126             pos = XMLString::indexOf(start,chSpace);
127             if (pos != -1)
128                 *(start + pos)=chNull;
129             m_bindings.push_back(start);
130             try {
131                 auto_ptr_char b(start);
132                 MessageEncoder * encoder = SAMLConfig::getConfig().MessageEncoderManager.newPlugin(b.get(),e);
133                 m_encoders[start] = encoder;
134                 m_log.debug("supporting outgoing binding (%s)", b.get());
135             }
136             catch (exception& ex) {
137                 m_log.error("error building MessageEncoder: %s", ex.what());
138             }
139             if (pos != -1)
140                 start = start + pos + 1;
141             else
142                 break;
143         }
144     }
145 #endif
146
147     pair<bool,const char*> loc = getString("Location");
148     if (loc.first) {
149         string address = m_appId + loc.second + "::run::SAML2LI";
150         setAddress(address.c_str());
151     }
152 }
153
154 void SAML2LogoutInitiator::setParent(const PropertySet* parent)
155 {
156     DOMPropertySet::setParent(parent);
157     pair<bool,const char*> loc = getString("Location");
158     if (loc.first) {
159         string address = m_appId + loc.second + "::run::SAML2LI";
160         setAddress(address.c_str());
161     }
162     else {
163         m_log.warn("no Location property in SAML2 LogoutInitiator (or parent), can't register as remoted handler");
164     }
165 }
166
167 pair<bool,long> SAML2LogoutInitiator::run(SPRequest& request, bool isHandler) const
168 {
169     // Defer to base class for front-channel loop first.
170     pair<bool,long> ret = LogoutHandler::run(request, isHandler);
171     if (ret.first)
172         return ret;
173
174     // At this point we know the front-channel is handled.
175     // We need the session to do any other work.
176
177     Session* session = NULL;
178     try {
179         session = request.getSession(false, true, false);  // don't cache it and ignore all checks
180         if (!session)
181             return make_pair(false,0);
182
183         // We only handle SAML 2.0 sessions.
184         if (!XMLString::equals(session->getProtocol(), m_protocol.get())) {
185             session->unlock();
186             return make_pair(false,0);
187         }
188     }
189     catch (exception& ex) {
190         m_log.error("error accessing current session: %s", ex.what());
191         return make_pair(false,0);
192     }
193
194     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
195         // When out of process, we run natively.
196         return doRequest(request.getApplication(), session, request);
197     }
198     else {
199         // When not out of process, we remote the request.
200         Locker locker(session);
201         DDF out,in(m_address.c_str());
202         DDFJanitor jin(in), jout(out);
203         in.addmember("application_id").string(request.getApplication().getId());
204         in.addmember("session_id").string(session->getID());
205         out=request.getServiceProvider().getListenerService()->send(in);
206         return unwrap(request, out);
207     }
208 }
209
210 void SAML2LogoutInitiator::receive(DDF& in, ostream& out)
211 {
212 #ifndef SHIBSP_LITE
213     // Defer to base class for notifications
214     if (in["notify"].integer() == 1)
215         return LogoutHandler::receive(in, out);
216
217     // Find application.
218     const char* aid=in["application_id"].string();
219     const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
220     if (!app) {
221         // Something's horribly wrong.
222         m_log.error("couldn't find application (%s) for logout", aid ? aid : "(missing)");
223         throw ConfigurationException("Unable to locate application for logout, deleted?");
224     }
225     
226     // Set up a response shim.
227     DDF ret(NULL);
228     DDFJanitor jout(ret);
229     auto_ptr<HTTPResponse> resp(getResponse(ret));
230     
231     Session* session = NULL;
232     try {
233          session = app->getServiceProvider().getSessionCache()->find(in["session_id"].string(), *app, NULL, NULL);
234     }
235     catch (exception& ex) {
236         m_log.error("error accessing current session: %s", ex.what());
237     }
238
239     // With no session, we just skip the request and let it fall through to an empty struct return.
240     if (session) {
241         if (session->getNameID() && session->getEntityID()) {
242             // Since we're remoted, the result should either be a throw, which we pass on,
243             // a false/0 return, which we just return as an empty structure, or a response/redirect,
244             // which we capture in the facade and send back.
245             doRequest(*app, session, *resp.get());
246         }
247         else {
248              m_log.error("no NameID or issuing entityID found in session");
249              session->unlock();
250              session = NULL;
251              app->getServiceProvider().getSessionCache()->remove(in["session_id"].string(), *app);
252          }
253     }
254     out << ret;
255 #else
256     throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
257 #endif
258 }
259
260 pair<bool,long> SAML2LogoutInitiator::doRequest(const Application& application, Session* session, HTTPResponse& response) const
261 {
262     // Do back channel notification.
263     vector<string> sessions(1, session->getID());
264     if (!notifyBackChannel(application, sessions)) {
265         session->unlock();
266         application.getServiceProvider().getSessionCache()->remove(sessions.front().c_str(), application);
267         return sendLogoutPage(application, response, true, "Partial logout failure.");
268     }
269
270 #ifndef SHIBSP_LITE
271     pair<bool,long> ret = make_pair(false,0);
272     try {
273         // With a session in hand, we can create a LogoutRequest message, if we can find a compatible endpoint.
274         Locker metadataLocker(application.getMetadataProvider());
275         const EntityDescriptor* entity = application.getMetadataProvider()->getEntityDescriptor(session->getEntityID());
276         if (!entity) {
277             throw MetadataException(
278                 "Unable to locate metadata for identity provider ($entityID)",
279                 namedparams(1, "entityID", session->getEntityID())
280                 );
281         }
282         const IDPSSODescriptor* role = entity->getIDPSSODescriptor(samlconstants::SAML20P_NS);
283         if (!role) {
284             throw MetadataException(
285                 "Unable to locate SAML 2.0 IdP role for identity provider ($entityID).",
286                 namedparams(1, "entityID", session->getEntityID())
287                 );
288         }
289
290         const EndpointType* ep=NULL;
291         const MessageEncoder* encoder=NULL;
292         vector<const XMLCh*>::const_iterator b;
293         for (b = m_bindings.begin(); b!=m_bindings.end(); ++b) {
294             if (ep=EndpointManager<SingleLogoutService>(role->getSingleLogoutServices()).getByBinding(*b)) {
295                 map<const XMLCh*,MessageEncoder*>::const_iterator enc = m_encoders.find(*b);
296                 if (enc!=m_encoders.end())
297                     encoder = enc->second;
298                 break;
299             }
300         }
301         if (!ep || !encoder) {
302             m_log.warn("no compatible front channel SingleLogoutService, trying back channel...");
303             shibsp::SecurityPolicy policy(application);
304             shibsp::SOAPClient soaper(policy);
305             MetadataCredentialCriteria mcc(*role);
306
307             LogoutResponse* logoutResponse=NULL;
308             auto_ptr_XMLCh binding(samlconstants::SAML20_BINDING_SOAP);
309             const vector<SingleLogoutService*>& endpoints=role->getSingleLogoutServices();
310             for (vector<SingleLogoutService*>::const_iterator epit=endpoints.begin(); !logoutResponse && epit!=endpoints.end(); ++epit) {
311                 try {
312                     if (!XMLString::equals((*epit)->getBinding(),binding.get()))
313                         continue;
314                     LogoutRequest* msg = buildRequest(application, *session, *role);
315                     auto_ptr_char dest((*epit)->getLocation());
316
317                     SAML2SOAPClient client(soaper, false);
318                     client.sendSAML(msg, mcc, dest.get());
319                     StatusResponseType* srt = client.receiveSAML();
320                     if (!(logoutResponse = dynamic_cast<LogoutResponse*>(srt))) {
321                         delete srt;
322                         break;
323                     }
324                 }
325                 catch (exception& ex) {
326                     m_log.error("error sending LogoutRequest message: %s", ex.what());
327                     soaper.reset();
328                 }
329             }
330
331             if (!logoutResponse)
332                 return sendLogoutPage(application, response, false, "Identity provider did not respond to logout request.");
333             if (!logoutResponse->getStatus() || !logoutResponse->getStatus()->getStatusCode() ||
334                    !XMLString::equals(logoutResponse->getStatus()->getStatusCode()->getValue(), saml2p::StatusCode::SUCCESS)) {
335                 delete logoutResponse;
336                 return sendLogoutPage(application, response, false, "Identity provider returned a SAML error in response to logout request.");
337             }
338             delete logoutResponse;
339             return sendLogoutPage(application, response, false, "Logout completed successfully.");
340         }
341
342         auto_ptr<LogoutRequest> msg(buildRequest(application, *session, *role, encoder));
343
344         msg->setDestination(ep->getLocation());
345         auto_ptr_char dest(ep->getLocation());
346         ret.second = sendMessage(*encoder, msg.get(), NULL, dest.get(), role, application, response, "signRequests");
347         ret.first = true;
348         msg.release();  // freed by encoder
349     }
350     catch (exception& ex) {
351         m_log.error("error issuing SAML 2.0 logout request: %s", ex.what());
352     }
353
354     if (session) {
355         string session_id = session->getID();
356         session->unlock();
357         session = NULL;
358         application.getServiceProvider().getSessionCache()->remove(session_id.c_str(), application);
359     }
360
361     return ret;
362 #else
363     string session_id = session->getID();
364     session->unlock();
365     application.getServiceProvider().getSessionCache()->remove(session_id.c_str(), application);
366     throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
367 #endif
368 }
369
370 #ifndef SHIBSP_LITE
371
372 LogoutRequest* SAML2LogoutInitiator::buildRequest(
373     const Application& application, const Session& session, const IDPSSODescriptor& role, const MessageEncoder* encoder
374     ) const
375 {
376     auto_ptr<LogoutRequest> msg(LogoutRequestBuilder::buildLogoutRequest());
377     Issuer* issuer = IssuerBuilder::buildIssuer();
378     msg->setIssuer(issuer);
379     issuer->setName(application.getXMLString("entityID").second);
380     auto_ptr_XMLCh index(session.getSessionIndex());
381     if (index.get() && *index.get()) {
382         SessionIndex* si = SessionIndexBuilder::buildSessionIndex();
383         msg->getSessionIndexs().push_back(si);
384         si->setSessionIndex(index.get());
385     }
386
387     const NameID* nameid = session.getNameID();
388     const PropertySet* relyingParty = application.getRelyingParty(dynamic_cast<EntityDescriptor*>(role.getParent()));
389     pair<bool,const char*> flag = relyingParty->getString("encryptRequests");
390     if (flag.first &&
391         (!strcmp(flag.second, "true") || (encoder && !strcmp(flag.second, "front")) || (!encoder && !strcmp(flag.second, "back")))) {
392         auto_ptr<EncryptedID> encrypted(EncryptedIDBuilder::buildEncryptedID());
393         MetadataCredentialCriteria mcc(role);
394         encrypted->encrypt(
395             *nameid,
396             *(application.getMetadataProvider()),
397             mcc,
398             encoder ? encoder->isCompact() : false,
399             relyingParty->getXMLString("encryptionAlg").second
400             );
401         msg->setEncryptedID(encrypted.release());
402     }
403
404     if (!encoder) {
405         // No encoder being used, so sign for SOAP client manually.
406         flag = relyingParty->getString("signRequests");
407         if (flag.first && (!strcmp(flag.second, "true") || !strcmp(flag.second, "back"))) {
408             CredentialResolver* credResolver=application.getCredentialResolver();
409             if (credResolver) {
410                 Locker credLocker(credResolver);
411                 // Fill in criteria to use.
412                 MetadataCredentialCriteria mcc(role);
413                 mcc.setUsage(CredentialCriteria::SIGNING_CREDENTIAL);
414                 pair<bool,const char*> keyName = relyingParty->getString("keyName");
415                 if (keyName.first)
416                     mcc.getKeyNames().insert(keyName.second);
417                 pair<bool,const XMLCh*> sigalg = relyingParty->getXMLString("signatureAlg");
418                 if (sigalg.first)
419                     mcc.setXMLAlgorithm(sigalg.second);
420                 const Credential* cred = credResolver->resolve(&mcc);
421                 if (cred) {
422                     xmlsignature::Signature* sig = xmlsignature::SignatureBuilder::buildSignature();
423                     msg->setSignature(sig);
424                     pair<bool, const XMLCh*> alg = relyingParty->getXMLString("signatureAlg");
425                     if (alg.first)
426                         sig->setSignatureAlgorithm(alg.second);
427                     alg = relyingParty->getXMLString("digestAlg");
428                     if (alg.first) {
429                         ContentReference* cr = dynamic_cast<ContentReference*>(sig->getContentReference());
430                         if (cr)
431                             cr->setDigestAlgorithm(alg.second);
432                     }
433             
434                     // Sign response while marshalling.
435                     vector<xmlsignature::Signature*> sigs(1,sig);
436                     msg->marshall((DOMDocument*)NULL,&sigs,cred);
437                 }
438                 else {
439                     m_log.warn("no signing credential resolved, leaving message unsigned");
440                 }
441             }
442             else {
443                 m_log.warn("no credential resolver installed, leaving message unsigned");
444             }
445         }
446     }
447
448     return msg.release();
449 }
450
451 #endif