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