First cut at logout race detection in cache.
[shibboleth/cpp-sp.git] / shibsp / handler / impl / SAML2Logout.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  * SAML2Logout.cpp
19  * 
20  * Handles SAML 2.0 single logout protocol messages.
21  */
22
23 #include "internal.h"
24 #include "exceptions.h"
25 #include "Application.h"
26 #include "ServiceProvider.h"
27 #include "handler/AbstractHandler.h"
28 #include "handler/LogoutHandler.h"
29 #include "util/SPConstants.h"
30
31 #ifndef SHIBSP_LITE
32 # include "SessionCache.h"
33 # include "security/SecurityPolicy.h"
34 # include "util/TemplateParameters.h"
35 # include <fstream>
36 # include <saml/SAMLConfig.h>
37 # include <saml/saml2/core/Protocols.h>
38 # include <saml/saml2/metadata/EndpointManager.h>
39 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
40 # include <xmltooling/util/URLEncoder.h>
41 using namespace opensaml::saml2;
42 using namespace opensaml::saml2p;
43 using namespace opensaml::saml2md;
44 using namespace opensaml;
45 #endif
46
47 using namespace shibsp;
48 using namespace xmltooling;
49 using namespace log4cpp;
50 using namespace std;
51
52 namespace shibsp {
53
54 #if defined (_MSC_VER)
55     #pragma warning( push )
56     #pragma warning( disable : 4250 )
57 #endif
58     
59     class SHIBSP_DLLLOCAL SAML2Logout : public AbstractHandler, public LogoutHandler
60     {
61     public:
62         SAML2Logout(const DOMElement* e, const char* appId);
63         virtual ~SAML2Logout() {
64 #ifndef SHIBSP_LITE
65             if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
66                 delete m_decoder;
67                 XMLString::release(&m_outgoing);
68                 for_each(m_encoders.begin(), m_encoders.end(), cleanup_pair<const XMLCh*,MessageEncoder>());
69             }
70 #endif
71         }
72         
73         void receive(DDF& in, ostream& out);
74         pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
75
76     private:
77         pair<bool,long> doRequest(
78             const Application& application, const char* session_id, const HTTPRequest& httpRequest, HTTPResponse& httpResponse
79             ) const;
80
81 #ifndef SHIBSP_LITE
82         bool stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const;
83
84         pair<bool,long> sendResponse(
85             const XMLCh* requestID,
86             const XMLCh* code,
87             const XMLCh* subcode,
88             const char* msg,
89             const char* relayState,
90             const RoleDescriptor* role,
91             const Application& application,
92             HTTPResponse& httpResponse,
93             bool front
94             ) const;
95
96         QName m_role;
97         MessageDecoder* m_decoder;
98         XMLCh* m_outgoing;
99         vector<const XMLCh*> m_bindings;
100         map<const XMLCh*,MessageEncoder*> m_encoders;
101 #endif
102     };
103
104 #if defined (_MSC_VER)
105     #pragma warning( pop )
106 #endif
107
108     Handler* SHIBSP_DLLLOCAL SAML2LogoutFactory(const pair<const DOMElement*,const char*>& p)
109     {
110         return new SAML2Logout(p.first, p.second);
111     }
112 };
113
114 SAML2Logout::SAML2Logout(const DOMElement* e, const char* appId)
115     : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SAML2Logout"))
116 #ifndef SHIBSP_LITE
117         ,m_role(samlconstants::SAML20MD_NS, IDPSSODescriptor::LOCAL_NAME), m_decoder(NULL), m_outgoing(NULL)
118 #endif
119 {
120 #ifndef SHIBSP_LITE
121     m_initiator = false;
122     m_preserve.push_back("ID");
123     m_preserve.push_back("entityID");
124     m_preserve.push_back("RelayState");
125
126     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
127         SAMLConfig& conf = SAMLConfig::getConfig();
128
129         // Handle incoming binding.
130         m_decoder = conf.MessageDecoderManager.newPlugin(getString("Binding").second,make_pair(e,shibspconstants::SHIB2SPCONFIG_NS));
131         m_decoder->setArtifactResolver(SPConfig::getConfig().getArtifactResolver());
132
133         if (m_decoder->isUserAgentPresent()) {
134             // Handle front-channel binding setup.
135             pair<bool,const XMLCh*> outgoing = getXMLString("outgoingBindings", m_configNS.get());
136             if (outgoing.first) {
137                 m_outgoing = XMLString::replicate(outgoing.second);
138                 XMLString::trim(m_outgoing);
139             }
140             else {
141                 // No override, so we'll install a default binding precedence.
142                 string prec = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
143                     samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
144                 m_outgoing = XMLString::transcode(prec.c_str());
145             }
146
147             int pos;
148             XMLCh* start = m_outgoing;
149             while (start && *start) {
150                 pos = XMLString::indexOf(start,chSpace);
151                 if (pos != -1)
152                     *(start + pos)=chNull;
153                 m_bindings.push_back(start);
154                 try {
155                     auto_ptr_char b(start);
156                     MessageEncoder * encoder = conf.MessageEncoderManager.newPlugin(b.get(),make_pair(e,shibspconstants::SHIB2SPCONFIG_NS));
157                     m_encoders[start] = encoder;
158                     m_log.debug("supporting outgoing front-channel binding (%s)", b.get());
159                 }
160                 catch (exception& ex) {
161                     m_log.error("error building MessageEncoder: %s", ex.what());
162                 }
163                 if (pos != -1)
164                     start = start + pos + 1;
165                 else
166                     break;
167             }
168         }
169         else {
170             MessageEncoder* encoder = conf.MessageEncoderManager.newPlugin(
171                 getString("Binding").second,make_pair(e,shibspconstants::SHIB2SPCONFIG_NS)
172                 );
173             m_encoders.insert(pair<const XMLCh*,MessageEncoder*>(NULL, encoder));
174         }
175     }
176 #endif
177
178     string address(appId);
179     address += getString("Location").second;
180     setAddress(address.c_str());
181 }
182
183 pair<bool,long> SAML2Logout::run(SPRequest& request, bool isHandler) const
184 {
185     // Defer to base class for front-channel loop first.
186     // This won't initiate the loop, only continue/end it.
187     pair<bool,long> ret = LogoutHandler::run(request, isHandler);
188     if (ret.first)
189         return ret;
190
191     // Get the session_id in case this is a front-channel LogoutRequest.
192     pair<string,const char*> shib_cookie = request.getApplication().getCookieNameProps("_shibsession_");
193     const char* session_id = request.getCookie(shib_cookie.first.c_str());
194
195     SPConfig& conf = SPConfig::getConfig();
196     if (conf.isEnabled(SPConfig::OutOfProcess)) {
197         // When out of process, we run natively and directly process the message.
198         return doRequest(request.getApplication(), session_id, request, request);
199     }
200     else {
201         // When not out of process, we remote all the message processing.
202         DDF out,in = wrap(request, NULL, true);
203         DDFJanitor jin(in), jout(out);
204         if (session_id)
205             in.addmember("session_id").string(session_id);
206         out=request.getServiceProvider().getListenerService()->send(in);
207         return unwrap(request, out);
208     }
209 }
210
211 void SAML2Logout::receive(DDF& in, ostream& out)
212 {
213     // Find application.
214     const char* aid=in["application_id"].string();
215     const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
216     if (!app) {
217         // Something's horribly wrong.
218         m_log.error("couldn't find application (%s) for logout", aid ? aid : "(missing)");
219         throw ConfigurationException("Unable to locate application for logout, deleted?");
220     }
221     
222     // Unpack the request.
223     DDF ret(NULL);
224     DDFJanitor jout(ret);
225     auto_ptr<HTTPRequest> req(getRequest(in));
226     auto_ptr<HTTPResponse> resp(getResponse(ret));
227     
228     // Since we're remoted, the result should either be a throw, which we pass on,
229     // a false/0 return, which we just return as an empty structure, or a response/redirect,
230     // which we capture in the facade and send back.
231     doRequest(*app, in["session_id"].string(), *req.get(), *resp.get());
232     out << ret;
233 }
234
235 pair<bool,long> SAML2Logout::doRequest(
236     const Application& application, const char* session_id, const HTTPRequest& request, HTTPResponse& response
237     ) const
238 {
239 #ifndef SHIBSP_LITE
240     SessionCache* cache = application.getServiceProvider().getSessionCache();
241     if (!strcmp(request.getMethod(),"GET") && request.getParameter("notifying")) {
242
243         // This is returning from a front-channel notification, so we have to do the back-channel and then
244         // respond. To do that, we need state from the original request.
245         if (!request.getParameter("entityID")) {
246             if (session_id)
247                 cache->remove(session_id, application);
248             throw FatalProfileException("Application notification loop did not return entityID for LogoutResponse.");
249         }
250
251         // Best effort on back channel and to remove the user agent's session.
252         bool worked1 = false,worked2 = false;
253         if (session_id) {
254             vector<string> sessions(1,session_id);
255             worked1 = notifyBackChannel(application, request.getRequestURL(), sessions, false);
256             try {
257                 cache->remove(session_id, application);
258                 worked2 = true;
259             }
260             catch (exception& ex) {
261                 m_log.error("error removing session (%s): %s", session_id, ex.what());
262             }
263         }
264         else {
265             worked1 = worked2 = true;
266         }
267
268         // We need metadata to issue a response.
269         Locker metadataLocker(application.getMetadataProvider());
270         const EntityDescriptor* entity = application.getMetadataProvider()->getEntityDescriptor(request.getParameter("entityID"));
271         if (!entity) {
272             throw MetadataException(
273                 "Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", request.getParameter("entityID"))
274                 );
275         }
276         const IDPSSODescriptor* idp = entity->getIDPSSODescriptor(samlconstants::SAML20P_NS);
277         if (!idp) {
278             throw MetadataException(
279                 "Unable to locate SAML 2.0 IdP role for identity provider ($entityID).",
280                 namedparams(1, "entityID", request.getParameter("entityID"))
281                 );
282         }
283
284         auto_ptr_XMLCh reqid(request.getParameter("ID"));
285         if (worked1 && worked2) {
286             // Successful LogoutResponse. Has to be front-channel or we couldn't be here.
287             return sendResponse(
288                 reqid.get(), StatusCode::SUCCESS, NULL, NULL, request.getParameter("RelayState"), idp, application, response, true
289                 );
290         }
291
292         return sendResponse(
293             reqid.get(),
294             StatusCode::RESPONDER, NULL, "Unable to fully destroy principal's session.",
295             request.getParameter("RelayState"),
296             idp,
297             application,
298             response,
299             true
300             );
301     }
302
303     // If we get here, it's an external protocol message to decode.
304
305     // Locate policy key.
306     pair<bool,const char*> policyId = getString("policyId", m_configNS.get());  // namespace-qualified if inside handler element
307     if (!policyId.first)
308         policyId = application.getString("policyId");   // unqualified in Application(s) element
309         
310     // Access policy properties.
311     const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId.second);
312     pair<bool,bool> validate = settings->getBool("validate");
313
314     // Lock metadata for use by policy.
315     Locker metadataLocker(application.getMetadataProvider());
316
317     // Create the policy.
318     shibsp::SecurityPolicy policy(application, &m_role, validate.first && validate.second);
319     
320     // Decode the message.
321     string relayState;
322     auto_ptr<XMLObject> msg(m_decoder->decode(relayState, request, policy));
323     const LogoutRequest* logoutRequest = dynamic_cast<LogoutRequest*>(msg.get());
324     if (logoutRequest) {
325         if (!policy.isSecure())
326             throw SecurityPolicyException("Security of LogoutRequest not established.");
327
328         // Message from IdP to logout one or more sessions.
329         
330         // If this is front-channel, we have to have a session_id to use already.
331         if (m_decoder->isUserAgentPresent() && !session_id) {
332             m_log.error("no active session");
333             return sendResponse(
334                 logoutRequest->getID(),
335                 StatusCode::REQUESTER, StatusCode::UNKNOWN_PRINCIPAL, "No active session found in request.",
336                 relayState.c_str(),
337                 policy.getIssuerMetadata(),
338                 application,
339                 response,
340                 true
341                 );
342         }
343
344         bool ownedName = false;
345         NameID* nameid = logoutRequest->getNameID();
346         if (!nameid) {
347             // Check for EncryptedID.
348             EncryptedID* encname = logoutRequest->getEncryptedID();
349             if (encname) {
350                 CredentialResolver* cr=application.getCredentialResolver();
351                 if (!cr)
352                     m_log.warn("found encrypted NameID, but no decryption credential was available");
353                 else {
354                     Locker credlocker(cr);
355                     auto_ptr<MetadataCredentialCriteria> mcc(
356                         policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
357                         );
358                     try {
359                         auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr,application.getXMLString("entityID").second,mcc.get()));
360                         nameid = dynamic_cast<NameID*>(decryptedID.get());
361                         if (nameid) {
362                             ownedName = true;
363                             decryptedID.release();
364                         }
365                     }
366                     catch (exception& ex) {
367                         m_log.error(ex.what());
368                     }
369                 }
370             }
371         }
372         if (!nameid) {
373             // No NameID, so must respond with an error.
374             m_log.error("NameID not found in request");
375             return sendResponse(
376                 logoutRequest->getID(),
377                 StatusCode::REQUESTER, StatusCode::UNKNOWN_PRINCIPAL, "NameID not found in request.",
378                 relayState.c_str(),
379                 policy.getIssuerMetadata(),
380                 application,
381                 response,
382                 m_decoder->isUserAgentPresent()
383                 );
384         }
385
386         // Suck indexes out of the request for next steps.
387         set<string> indexes;
388         EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL;
389         const vector<SessionIndex*> sindexes = logoutRequest->getSessionIndexs();
390         for (vector<SessionIndex*>::const_iterator i = sindexes.begin(); i != sindexes.end(); ++i) {
391             auto_ptr_char sindex((*i)->getSessionIndex());
392             indexes.insert(sindex.get());
393         }
394
395         // For a front-channel LogoutRequest, we have to match the information in the request
396         // against the current session.
397         if (session_id) {
398             if (!cache->matches(session_id, entity, *nameid, &indexes, application)) {
399                 return sendResponse(
400                     logoutRequest->getID(),
401                     StatusCode::REQUESTER, StatusCode::REQUEST_DENIED, "Active sessions did not match logout request.",
402                     relayState.c_str(),
403                     policy.getIssuerMetadata(),
404                     application,
405                     response,
406                     true
407                     );
408             }
409
410         }
411
412         // Now we perform "logout" by finding the matching sessions.
413         vector<string> sessions;
414         try {
415             time_t expires = logoutRequest->getNotOnOrAfter() ? logoutRequest->getNotOnOrAfterEpoch() : 0;
416             cache->logout(entity, *nameid, &indexes, expires, application, sessions);
417
418             // Now we actually terminate everything except for the active session,
419             // if this is front-channel, for notification purposes.
420             for (vector<string>::const_iterator sit = sessions.begin(); sit != sessions.end(); ++sit)
421                 if (session_id && strcmp(sit->c_str(), session_id))
422                     cache->remove(sit->c_str(), application);
423         }
424         catch (exception& ex) {
425             m_log.error("error while logging out matching sessions: %s", ex.what());
426             return sendResponse(
427                 logoutRequest->getID(),
428                 StatusCode::RESPONDER, NULL, ex.what(),
429                 relayState.c_str(),
430                 policy.getIssuerMetadata(),
431                 application,
432                 response,
433                 m_decoder->isUserAgentPresent()
434                 );
435         }
436
437         if (m_decoder->isUserAgentPresent()) {
438             // Pass control to the first front channel notification point, if any.
439             map<string,string> parammap;
440             if (!relayState.empty())
441                 parammap["RelayState"] = relayState;
442             auto_ptr_char entityID(entity ? entity->getEntityID() : NULL);
443             if (entityID.get())
444                 parammap["entityID"] = entityID.get();
445             auto_ptr_char reqID(logoutRequest->getID());
446             if (reqID.get())
447                 parammap["ID"] = reqID.get();
448             pair<bool,long> result = notifyFrontChannel(application, request, response, &parammap);
449             if (result.first)
450                 return result;
451         }
452         
453         // For back-channel requests, or if no front-channel notification is needed...
454         bool worked1 = false,worked2 = false;
455         worked1 = notifyBackChannel(application, request.getRequestURL(), sessions, false);
456         if (session_id) {
457             // One last session to yoink...
458             try {
459                 cache->remove(session_id, application);
460                 worked2 = true;
461             }
462             catch (exception& ex) {
463                 m_log.error("error removing active session (%s): %s", session_id, ex.what());
464             }
465         }
466
467         return sendResponse(
468             logoutRequest->getID(),
469             (worked1 && worked2) ? StatusCode::SUCCESS : StatusCode::RESPONDER,
470             (worked1 && worked2) ? NULL : StatusCode::PARTIAL_LOGOUT,
471             NULL,
472             relayState.c_str(),
473             policy.getIssuerMetadata(),
474             application,
475             response,
476             m_decoder->isUserAgentPresent()
477             );
478     }
479
480     // A LogoutResponse completes an SP-initiated logout sequence.
481     const LogoutResponse* logoutResponse = dynamic_cast<LogoutResponse*>(msg.get());
482     if (logoutResponse) {
483         if (!policy.isSecure()) {
484             SecurityPolicyException ex("Security of LogoutResponse not established.");
485             if (policy.getIssuerMetadata())
486                 annotateException(&ex, policy.getIssuerMetadata()); // throws it
487             ex.raise();
488         }
489         checkError(logoutResponse, policy.getIssuerMetadata()); // throws if Status doesn't look good...
490
491         // Return template for completion of global logout, or redirect to homeURL.
492         return sendLogoutPage(application, response, false, "Global logout completed.");
493     }
494
495     FatalProfileException ex("Incoming message was not a samlp:LogoutRequest or samlp:LogoutResponse.");
496     if (policy.getIssuerMetadata())
497         annotateException(&ex, policy.getIssuerMetadata()); // throws it
498     ex.raise();
499     return make_pair(false,0);  // never happen, satisfies compiler
500 #else
501     throw ConfigurationException("Cannot process logout message using lite version of shibsp library.");
502 #endif
503 }
504
505 #ifndef SHIBSP_LITE
506
507 bool SAML2Logout::stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const
508 {
509     if (!XMLString::equals(n1.getName(), n2.getName()))
510         return false;
511     
512     const XMLCh* s1 = n1.getFormat();
513     const XMLCh* s2 = n2.getFormat();
514     if (!s1 || !*s1)
515         s1 = saml2::NameID::UNSPECIFIED;
516     if (!s2 || !*s2)
517         s2 = saml2::NameID::UNSPECIFIED;
518     if (!XMLString::equals(s1,s2))
519         return false;
520     
521     s1 = n1.getNameQualifier();
522     s2 = n2.getNameQualifier();
523     if (!s1 || !*s1)
524         s1 = idp;
525     if (!s2 || !*s2)
526         s2 = idp;
527     if (!XMLString::equals(s1,s2))
528         return false;
529
530     s1 = n1.getSPNameQualifier();
531     s2 = n2.getSPNameQualifier();
532     if (!s1 || !*s1)
533         s1 = sp;
534     if (!s2 || !*s2)
535         s2 = sp;
536     if (!XMLString::equals(s1,s2))
537         return false;
538
539     return true;
540 }
541
542 pair<bool,long> SAML2Logout::sendResponse(
543     const XMLCh* requestID,
544     const XMLCh* code,
545     const XMLCh* subcode,
546     const char* msg,
547     const char* relayState,
548     const RoleDescriptor* role,
549     const Application& application,
550     HTTPResponse& httpResponse,
551     bool front
552     ) const
553 {
554     // Get endpoint and encoder to use.
555     const EndpointType* ep = NULL;
556     const MessageEncoder* encoder = NULL;
557     if (front) {
558         const IDPSSODescriptor* idp = dynamic_cast<const IDPSSODescriptor*>(role);
559         for (vector<const XMLCh*>::const_iterator b = m_bindings.begin(); idp && b!=m_bindings.end(); ++b) {
560             if (ep=EndpointManager<SingleLogoutService>(idp->getSingleLogoutServices()).getByBinding(*b)) {
561                 map<const XMLCh*,MessageEncoder*>::const_iterator enc = m_encoders.find(*b);
562                 if (enc!=m_encoders.end())
563                     encoder = enc->second;
564                 break;
565             }
566         }
567         if (!ep || !encoder) {
568             auto_ptr_char id(dynamic_cast<EntityDescriptor*>(role->getParent())->getEntityID());
569             m_log.error("unable to locate compatible SLO service for provider (%s)", id.get());
570             MetadataException ex("Unable to locate endpoint at IdP ($entityID) to send LogoutResponse.");
571             annotateException(&ex, role);   // throws it
572         }
573     }
574     else {
575         encoder = m_encoders.begin()->second;
576     }
577
578     // Prepare response.
579     auto_ptr<LogoutResponse> logout(LogoutResponseBuilder::buildLogoutResponse());
580     logout->setInResponseTo(requestID);
581     if (ep)
582         logout->setDestination(ep->getLocation());
583     Issuer* issuer = IssuerBuilder::buildIssuer();
584     logout->setIssuer(issuer);
585     issuer->setName(application.getXMLString("entityID").second);
586     fillStatus(*logout.get(), code, subcode, msg);
587
588     auto_ptr_char dest(ep ? ep->getLocation() : NULL);
589
590     long ret = sendMessage(*encoder, logout.get(), relayState, dest.get(), role, application, httpResponse, "signResponses");
591     logout.release();  // freed by encoder
592     return make_pair(true,ret);
593 }
594
595 #endif