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