7dd1d78c1ae9807746ee4324a69f176da8053178
[shibboleth/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 "SessionCacheEx.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     SessionCacheEx* cacheex = dynamic_cast<SessionCacheEx*>(cache);
257     string session_id = cache->active(application, request);
258
259     if (!strcmp(request.getMethod(),"GET") && request.getParameter("notifying")) {
260         // This is returning from a front-channel notification, so we have to do the back-channel and then
261         // respond. To do that, we need state from the original request.
262         if (!request.getParameter("entityID")) {
263             cache->remove(application, request, &response);
264             throw FatalProfileException("Application notification loop did not return entityID for LogoutResponse.");
265         }
266
267         // Best effort on back channel and to remove the user agent's session.
268         bool worked1 = false,worked2 = false;
269         if (!session_id.empty()) {
270             vector<string> sessions(1,session_id);
271             worked1 = notifyBackChannel(application, request.getRequestURL(), sessions, false);
272             try {
273                 cache->remove(application, request, &response);
274                 worked2 = true;
275             }
276             catch (exception& ex) {
277                 m_log.error("error removing session (%s): %s", session_id, ex.what());
278             }
279         }
280         else {
281             worked1 = worked2 = true;
282         }
283
284         // We need metadata to issue a response.
285         MetadataProvider* m = application.getMetadataProvider();
286         Locker metadataLocker(m);
287         MetadataProvider::Criteria mc(request.getParameter("entityID"), &IDPSSODescriptor::ELEMENT_QNAME, samlconstants::SAML20P_NS);
288         pair<const EntityDescriptor*,const RoleDescriptor*> entity = m->getEntityDescriptor(mc);
289         if (!entity.first) {
290             throw MetadataException(
291                 "Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", request.getParameter("entityID"))
292                 );
293         }
294         else if (!entity.second) {
295             throw MetadataException(
296                 "Unable to locate SAML 2.0 IdP role for identity provider ($entityID).",
297                 namedparams(1, "entityID", request.getParameter("entityID"))
298                 );
299         }
300
301         auto_ptr_XMLCh reqid(request.getParameter("ID"));
302         if (worked1 && worked2) {
303             // Successful LogoutResponse. Has to be front-channel or we couldn't be here.
304             return sendResponse(
305                 reqid.get(), StatusCode::SUCCESS, NULL, NULL, request.getParameter("RelayState"), entity.second, application, response, true
306                 );
307         }
308
309         return sendResponse(
310             reqid.get(),
311             StatusCode::RESPONDER, NULL, "Unable to fully destroy principal's session.",
312             request.getParameter("RelayState"),
313             entity.second,
314             application,
315             response,
316             true
317             );
318     }
319
320     // If we get here, it's an external protocol message to decode.
321
322     // Locate policy key.
323     pair<bool,const char*> policyId = getString("policyId", m_configNS.get());  // namespace-qualified if inside handler element
324     if (!policyId.first)
325         policyId = application.getString("policyId");   // unqualified in Application(s) element
326         
327     // Access policy properties.
328     const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId.second);
329     pair<bool,bool> validate = settings->getBool("validate");
330
331     // Lock metadata for use by policy.
332     Locker metadataLocker(application.getMetadataProvider());
333
334     // Create the policy.
335     shibsp::SecurityPolicy policy(application, &m_role, validate.first && validate.second);
336     
337     // Decode the message.
338     string relayState;
339     auto_ptr<XMLObject> msg(m_decoder->decode(relayState, request, policy));
340     const LogoutRequest* logoutRequest = dynamic_cast<LogoutRequest*>(msg.get());
341     if (logoutRequest) {
342         if (!policy.isAuthenticated())
343             throw SecurityPolicyException("Security of LogoutRequest not established.");
344
345         // Message from IdP to logout one or more sessions.
346         
347         // If this is front-channel, we have to have a session_id to use already.
348         if (m_decoder->isUserAgentPresent() && session_id.empty()) {
349             m_log.error("no active session");
350             return sendResponse(
351                 logoutRequest->getID(),
352                 StatusCode::REQUESTER, StatusCode::UNKNOWN_PRINCIPAL, "No active session found in request.",
353                 relayState.c_str(),
354                 policy.getIssuerMetadata(),
355                 application,
356                 response,
357                 true
358                 );
359         }
360
361         bool ownedName = false;
362         NameID* nameid = logoutRequest->getNameID();
363         if (!nameid) {
364             // Check for EncryptedID.
365             EncryptedID* encname = logoutRequest->getEncryptedID();
366             if (encname) {
367                 CredentialResolver* cr=application.getCredentialResolver();
368                 if (!cr)
369                     m_log.warn("found encrypted NameID, but no decryption credential was available");
370                 else {
371                     Locker credlocker(cr);
372                     auto_ptr<MetadataCredentialCriteria> mcc(
373                         policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
374                         );
375                     try {
376                         auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr,application.getXMLString("entityID").second,mcc.get()));
377                         nameid = dynamic_cast<NameID*>(decryptedID.get());
378                         if (nameid) {
379                             ownedName = true;
380                             decryptedID.release();
381                         }
382                     }
383                     catch (exception& ex) {
384                         m_log.error(ex.what());
385                     }
386                 }
387             }
388         }
389         if (!nameid) {
390             // No NameID, so must respond with an error.
391             m_log.error("NameID not found in request");
392             return sendResponse(
393                 logoutRequest->getID(),
394                 StatusCode::REQUESTER, StatusCode::UNKNOWN_PRINCIPAL, "NameID not found in request.",
395                 relayState.c_str(),
396                 policy.getIssuerMetadata(),
397                 application,
398                 response,
399                 m_decoder->isUserAgentPresent()
400                 );
401         }
402
403         auto_ptr<NameID> namewrapper(ownedName ? nameid : NULL);
404
405         // Suck indexes out of the request for next steps.
406         set<string> indexes;
407         EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL;
408         const vector<SessionIndex*> sindexes = logoutRequest->getSessionIndexs();
409         for (vector<SessionIndex*>::const_iterator i = sindexes.begin(); i != sindexes.end(); ++i) {
410             auto_ptr_char sindex((*i)->getSessionIndex());
411             indexes.insert(sindex.get());
412         }
413
414         // For a front-channel LogoutRequest, we have to match the information in the request
415         // against the current session.
416         if (!session_id.empty()) {
417             if (!cache->matches(application, request, entity, *nameid, &indexes)) {
418                 return sendResponse(
419                     logoutRequest->getID(),
420                     StatusCode::REQUESTER, StatusCode::REQUEST_DENIED, "Active session did not match logout request.",
421                     relayState.c_str(),
422                     policy.getIssuerMetadata(),
423                     application,
424                     response,
425                     true
426                     );
427             }
428
429         }
430
431         // Now we perform "logout" by finding the matching sessions.
432         vector<string> sessions;
433         try {
434             if (cacheex) {
435                 time_t expires = logoutRequest->getNotOnOrAfter() ? logoutRequest->getNotOnOrAfterEpoch() : 0;
436                 cacheex->logout(application, entity, *nameid, &indexes, expires, sessions);
437
438                 // Now we actually terminate everything except for the active session,
439                 // if this is front-channel, for notification purposes.
440                 for (vector<string>::const_iterator sit = sessions.begin(); sit != sessions.end(); ++sit)
441                     if (*sit != session_id)
442                         cacheex->remove(application, sit->c_str());   // using the ID-based removal operation
443             }
444             else {
445                 m_log.warn("session cache does not support extended API, can't implement indirect logout of sessions");
446                 if (!session_id.empty())
447                     sessions.push_back(session_id);
448             }
449         }
450         catch (exception& ex) {
451             m_log.error("error while logging out matching sessions: %s", ex.what());
452             return sendResponse(
453                 logoutRequest->getID(),
454                 StatusCode::RESPONDER, NULL, ex.what(),
455                 relayState.c_str(),
456                 policy.getIssuerMetadata(),
457                 application,
458                 response,
459                 m_decoder->isUserAgentPresent()
460                 );
461         }
462
463         if (m_decoder->isUserAgentPresent()) {
464             // Pass control to the first front channel notification point, if any.
465             map<string,string> parammap;
466             if (!relayState.empty())
467                 parammap["RelayState"] = relayState;
468             auto_ptr_char entityID(entity ? entity->getEntityID() : NULL);
469             if (entityID.get())
470                 parammap["entityID"] = entityID.get();
471             auto_ptr_char reqID(logoutRequest->getID());
472             if (reqID.get())
473                 parammap["ID"] = reqID.get();
474             pair<bool,long> result = notifyFrontChannel(application, request, response, &parammap);
475             if (result.first)
476                 return result;
477         }
478         
479         // For back-channel requests, or if no front-channel notification is needed...
480         bool worked1 = false,worked2 = false;
481         worked1 = notifyBackChannel(application, request.getRequestURL(), sessions, false);
482         if (!session_id.empty()) {
483             // One last session to yoink...
484             try {
485                 cache->remove(application, request, &response);
486                 worked2 = true;
487             }
488             catch (exception& ex) {
489                 m_log.error("error removing active session (%s): %s", session_id.c_str(), ex.what());
490             }
491         }
492
493         return sendResponse(
494             logoutRequest->getID(),
495             (worked1 && worked2) ? StatusCode::SUCCESS : StatusCode::RESPONDER,
496             (worked1 && worked2) ? NULL : StatusCode::PARTIAL_LOGOUT,
497             NULL,
498             relayState.c_str(),
499             policy.getIssuerMetadata(),
500             application,
501             response,
502             m_decoder->isUserAgentPresent()
503             );
504     }
505
506     // A LogoutResponse completes an SP-initiated logout sequence.
507     const LogoutResponse* logoutResponse = dynamic_cast<LogoutResponse*>(msg.get());
508     if (logoutResponse) {
509         if (!policy.isAuthenticated()) {
510             SecurityPolicyException ex("Security of LogoutResponse not established.");
511             if (policy.getIssuerMetadata())
512                 annotateException(&ex, policy.getIssuerMetadata()); // throws it
513             ex.raise();
514         }
515         checkError(logoutResponse, policy.getIssuerMetadata()); // throws if Status doesn't look good...
516
517         // If relay state is set, recover the original return URL.
518         if (!relayState.empty())
519             recoverRelayState(application, request, response, relayState);
520         if (!relayState.empty())
521             return make_pair(true, response.sendRedirect(relayState.c_str()));
522
523         // Return template for completion of global logout, or redirect to homeURL.
524         return sendLogoutPage(application, request, response, false, "Global logout completed.");
525     }
526
527     FatalProfileException ex("Incoming message was not a samlp:LogoutRequest or samlp:LogoutResponse.");
528     if (policy.getIssuerMetadata())
529         annotateException(&ex, policy.getIssuerMetadata()); // throws it
530     ex.raise();
531     return make_pair(false,0L);  // never happen, satisfies compiler
532 #else
533     throw ConfigurationException("Cannot process logout message using lite version of shibsp library.");
534 #endif
535 }
536
537 #ifndef SHIBSP_LITE
538
539 pair<bool,long> SAML2Logout::sendResponse(
540     const XMLCh* requestID,
541     const XMLCh* code,
542     const XMLCh* subcode,
543     const char* msg,
544     const char* relayState,
545     const RoleDescriptor* role,
546     const Application& application,
547     HTTPResponse& httpResponse,
548     bool front
549     ) const
550 {
551     // Get endpoint and encoder to use.
552     const EndpointType* ep = NULL;
553     const MessageEncoder* encoder = NULL;
554     if (front) {
555         const IDPSSODescriptor* idp = dynamic_cast<const IDPSSODescriptor*>(role);
556         for (vector<const XMLCh*>::const_iterator b = m_bindings.begin(); idp && b!=m_bindings.end(); ++b) {
557             if (ep=EndpointManager<SingleLogoutService>(idp->getSingleLogoutServices()).getByBinding(*b)) {
558                 map<const XMLCh*,MessageEncoder*>::const_iterator enc = m_encoders.find(*b);
559                 if (enc!=m_encoders.end())
560                     encoder = enc->second;
561                 break;
562             }
563         }
564         if (!ep || !encoder) {
565             auto_ptr_char id(dynamic_cast<EntityDescriptor*>(role->getParent())->getEntityID());
566             m_log.error("unable to locate compatible SLO service for provider (%s)", id.get());
567             MetadataException ex("Unable to locate endpoint at IdP ($entityID) to send LogoutResponse.");
568             annotateException(&ex, role);   // throws it
569         }
570     }
571     else {
572         encoder = m_encoders.begin()->second;
573     }
574
575     // Prepare response.
576     auto_ptr<LogoutResponse> logout(LogoutResponseBuilder::buildLogoutResponse());
577     logout->setInResponseTo(requestID);
578     if (ep) {
579         const XMLCh* loc = ep->getResponseLocation();
580         if (!loc || !*loc)
581             loc = ep->getLocation();
582         logout->setDestination(loc);
583     }
584     Issuer* issuer = IssuerBuilder::buildIssuer();
585     logout->setIssuer(issuer);
586     issuer->setName(application.getXMLString("entityID").second);
587     fillStatus(*logout.get(), code, subcode, msg);
588
589     auto_ptr_char dest(logout->getDestination());
590
591     long ret = sendMessage(*encoder, logout.get(), relayState, dest.get(), role, application, httpResponse);
592     logout.release();  // freed by encoder
593     return make_pair(true,ret);
594 }
595
596 #endif