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