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