Change audience handling and validators to separate out entityID.
[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(
377                             encname->decrypt(
378                                 *cr,
379                                 application.getRelyingParty(policy.getIssuerMetadata() ? dynamic_cast<EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL)->getXMLString("entityID").second,
380                                 mcc.get()
381                                 )
382                             );
383                         nameid = dynamic_cast<NameID*>(decryptedID.get());
384                         if (nameid) {
385                             ownedName = true;
386                             decryptedID.release();
387                         }
388                     }
389                     catch (exception& ex) {
390                         m_log.error(ex.what());
391                     }
392                 }
393             }
394         }
395         if (!nameid) {
396             // No NameID, so must respond with an error.
397             m_log.error("NameID not found in request");
398             return sendResponse(
399                 logoutRequest->getID(),
400                 StatusCode::REQUESTER, StatusCode::UNKNOWN_PRINCIPAL, "NameID not found in request.",
401                 relayState.c_str(),
402                 policy.getIssuerMetadata(),
403                 application,
404                 response,
405                 m_decoder->isUserAgentPresent()
406                 );
407         }
408
409         auto_ptr<NameID> namewrapper(ownedName ? nameid : NULL);
410
411         // Suck indexes out of the request for next steps.
412         set<string> indexes;
413         EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL;
414         const vector<SessionIndex*> sindexes = logoutRequest->getSessionIndexs();
415         for (vector<SessionIndex*>::const_iterator i = sindexes.begin(); i != sindexes.end(); ++i) {
416             auto_ptr_char sindex((*i)->getSessionIndex());
417             indexes.insert(sindex.get());
418         }
419
420         // For a front-channel LogoutRequest, we have to match the information in the request
421         // against the current session.
422         if (!session_id.empty()) {
423             if (!cache->matches(application, request, entity, *nameid, &indexes)) {
424                 return sendResponse(
425                     logoutRequest->getID(),
426                     StatusCode::REQUESTER, StatusCode::REQUEST_DENIED, "Active session did not match logout request.",
427                     relayState.c_str(),
428                     policy.getIssuerMetadata(),
429                     application,
430                     response,
431                     true
432                     );
433             }
434
435         }
436
437         // Now we perform "logout" by finding the matching sessions.
438         vector<string> sessions;
439         try {
440             if (cacheex) {
441                 time_t expires = logoutRequest->getNotOnOrAfter() ? logoutRequest->getNotOnOrAfterEpoch() : 0;
442                 cacheex->logout(application, entity, *nameid, &indexes, expires, sessions);
443
444                 // Now we actually terminate everything except for the active session,
445                 // if this is front-channel, for notification purposes.
446                 for (vector<string>::const_iterator sit = sessions.begin(); sit != sessions.end(); ++sit)
447                     if (*sit != session_id)
448                         cacheex->remove(application, sit->c_str());   // using the ID-based removal operation
449             }
450             else {
451                 m_log.warn("session cache does not support extended API, can't implement indirect logout of sessions");
452                 if (!session_id.empty())
453                     sessions.push_back(session_id);
454             }
455         }
456         catch (exception& ex) {
457             m_log.error("error while logging out matching sessions: %s", ex.what());
458             return sendResponse(
459                 logoutRequest->getID(),
460                 StatusCode::RESPONDER, NULL, ex.what(),
461                 relayState.c_str(),
462                 policy.getIssuerMetadata(),
463                 application,
464                 response,
465                 m_decoder->isUserAgentPresent()
466                 );
467         }
468
469         if (m_decoder->isUserAgentPresent()) {
470             // Pass control to the first front channel notification point, if any.
471             map<string,string> parammap;
472             if (!relayState.empty())
473                 parammap["RelayState"] = relayState;
474             auto_ptr_char entityID(entity ? entity->getEntityID() : NULL);
475             if (entityID.get())
476                 parammap["entityID"] = entityID.get();
477             auto_ptr_char reqID(logoutRequest->getID());
478             if (reqID.get())
479                 parammap["ID"] = reqID.get();
480             pair<bool,long> result = notifyFrontChannel(application, request, response, &parammap);
481             if (result.first)
482                 return result;
483         }
484         
485         // For back-channel requests, or if no front-channel notification is needed...
486         bool worked1 = false,worked2 = false;
487         worked1 = notifyBackChannel(application, request.getRequestURL(), sessions, false);
488         if (!session_id.empty()) {
489             // One last session to yoink...
490             try {
491                 cache->remove(application, request, &response);
492                 worked2 = true;
493             }
494             catch (exception& ex) {
495                 m_log.error("error removing active session (%s): %s", session_id.c_str(), ex.what());
496             }
497         }
498
499         return sendResponse(
500             logoutRequest->getID(),
501             (worked1 && worked2) ? StatusCode::SUCCESS : StatusCode::RESPONDER,
502             (worked1 && worked2) ? NULL : StatusCode::PARTIAL_LOGOUT,
503             NULL,
504             relayState.c_str(),
505             policy.getIssuerMetadata(),
506             application,
507             response,
508             m_decoder->isUserAgentPresent()
509             );
510     }
511
512     // A LogoutResponse completes an SP-initiated logout sequence.
513     const LogoutResponse* logoutResponse = dynamic_cast<LogoutResponse*>(msg.get());
514     if (logoutResponse) {
515         if (!policy.isAuthenticated()) {
516             SecurityPolicyException ex("Security of LogoutResponse not established.");
517             if (policy.getIssuerMetadata())
518                 annotateException(&ex, policy.getIssuerMetadata()); // throws it
519             ex.raise();
520         }
521         checkError(logoutResponse, policy.getIssuerMetadata()); // throws if Status doesn't look good...
522
523         // If relay state is set, recover the original return URL.
524         if (!relayState.empty())
525             recoverRelayState(application, request, response, relayState);
526         if (!relayState.empty())
527             return make_pair(true, response.sendRedirect(relayState.c_str()));
528
529         // Return template for completion of global logout, or redirect to homeURL.
530         return sendLogoutPage(application, request, response, false, "Global logout completed.");
531     }
532
533     FatalProfileException ex("Incoming message was not a samlp:LogoutRequest or samlp:LogoutResponse.");
534     if (policy.getIssuerMetadata())
535         annotateException(&ex, policy.getIssuerMetadata()); // throws it
536     ex.raise();
537     return make_pair(false,0L);  // never happen, satisfies compiler
538 #else
539     throw ConfigurationException("Cannot process logout message using lite version of shibsp library.");
540 #endif
541 }
542
543 #ifndef SHIBSP_LITE
544
545 pair<bool,long> SAML2Logout::sendResponse(
546     const XMLCh* requestID,
547     const XMLCh* code,
548     const XMLCh* subcode,
549     const char* msg,
550     const char* relayState,
551     const RoleDescriptor* role,
552     const Application& application,
553     HTTPResponse& httpResponse,
554     bool front
555     ) const
556 {
557     // Get endpoint and encoder to use.
558     const EndpointType* ep = NULL;
559     const MessageEncoder* encoder = NULL;
560     if (front) {
561         const IDPSSODescriptor* idp = dynamic_cast<const IDPSSODescriptor*>(role);
562         for (vector<const XMLCh*>::const_iterator b = m_bindings.begin(); idp && b!=m_bindings.end(); ++b) {
563             if (ep=EndpointManager<SingleLogoutService>(idp->getSingleLogoutServices()).getByBinding(*b)) {
564                 map<const XMLCh*,MessageEncoder*>::const_iterator enc = m_encoders.find(*b);
565                 if (enc!=m_encoders.end())
566                     encoder = enc->second;
567                 break;
568             }
569         }
570         if (!ep || !encoder) {
571             auto_ptr_char id(dynamic_cast<EntityDescriptor*>(role->getParent())->getEntityID());
572             m_log.error("unable to locate compatible SLO service for provider (%s)", id.get());
573             MetadataException ex("Unable to locate endpoint at IdP ($entityID) to send LogoutResponse.");
574             annotateException(&ex, role);   // throws it
575         }
576     }
577     else {
578         encoder = m_encoders.begin()->second;
579     }
580
581     // Prepare response.
582     auto_ptr<LogoutResponse> logout(LogoutResponseBuilder::buildLogoutResponse());
583     logout->setInResponseTo(requestID);
584     if (ep) {
585         const XMLCh* loc = ep->getResponseLocation();
586         if (!loc || !*loc)
587             loc = ep->getLocation();
588         logout->setDestination(loc);
589     }
590     Issuer* issuer = IssuerBuilder::buildIssuer();
591     logout->setIssuer(issuer);
592     issuer->setName(application.getRelyingParty(dynamic_cast<EntityDescriptor*>(role->getParent()))->getXMLString("entityID").second);
593     fillStatus(*logout.get(), code, subcode, msg);
594
595     auto_ptr_char dest(logout->getDestination());
596
597     long ret = sendMessage(*encoder, logout.get(), relayState, dest.get(), role, application, httpResponse);
598     logout.release();  // freed by encoder
599     return make_pair(true,ret);
600 }
601
602 #endif