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