6fc91a44fc3add0825cf4637ef65710382813857
[shibboleth/sp.git] / adfs / adfs.cpp
1 /*
2  *  Copyright 2001-2005 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  * adfs.cpp
19  *
20  * ADFSv1 extension library
21  */
22
23 #if defined (_MSC_VER) || defined(__BORLANDC__)
24 # include "config_win32.h"
25 #else
26 # include "config.h"
27 #endif
28
29 #ifdef WIN32
30 # define _CRT_NONSTDC_NO_DEPRECATE 1
31 # define _CRT_SECURE_NO_DEPRECATE 1
32 # define ADFS_EXPORTS __declspec(dllexport)
33 #else
34 # define ADFS_EXPORTS
35 #endif
36
37 #include <shibsp/base.h>
38 #include <shibsp/exceptions.h>
39 #include <shibsp/Application.h>
40 #include <shibsp/ServiceProvider.h>
41 #include <shibsp/SessionCache.h>
42 #include <shibsp/SPConfig.h>
43 #include <shibsp/handler/AssertionConsumerService.h>
44 #include <shibsp/handler/LogoutHandler.h>
45 #include <shibsp/handler/SessionInitiator.h>
46 #include <xmltooling/logging.h>
47 #include <xmltooling/util/NDC.h>
48 #include <xmltooling/util/URLEncoder.h>
49 #include <xmltooling/util/XMLHelper.h>
50 #include <xercesc/util/XMLUniDefs.hpp>
51
52 #ifndef SHIBSP_LITE
53 # include <shibsp/attribute/resolver/ResolutionContext.h>
54 # include <saml/SAMLConfig.h>
55 # include <saml/saml1/core/Assertions.h>
56 # include <saml/saml1/profile/AssertionValidator.h>
57 # include <saml/saml2/core/Assertions.h>
58 # include <saml/saml2/metadata/Metadata.h>
59 # include <saml/saml2/metadata/EndpointManager.h>
60 # include <xmltooling/impl/AnyElement.h>
61 # include <xmltooling/validation/ValidatorSuite.h>
62 using namespace opensaml::saml2md;
63 #endif
64 using namespace shibsp;
65 using namespace opensaml;
66 using namespace xmltooling::logging;
67 using namespace xmltooling;
68 using namespace xercesc;
69 using namespace std;
70
71 #define WSFED_NS "http://schemas.xmlsoap.org/ws/2003/07/secext"
72 #define WSTRUST_NS "http://schemas.xmlsoap.org/ws/2005/02/trust"
73
74 namespace {
75
76 #ifndef SHIBSP_LITE
77     class SHIBSP_DLLLOCAL ADFSDecoder : public MessageDecoder
78     {
79         auto_ptr_XMLCh m_ns;
80     public:
81         ADFSDecoder() : m_ns(WSTRUST_NS) {}
82         virtual ~ADFSDecoder() {}
83         
84         XMLObject* decode(string& relayState, const GenericRequest& genericRequest, SecurityPolicy& policy) const;
85     };
86
87     MessageDecoder* ADFSDecoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
88     {
89         return new ADFSDecoder();
90     }
91 #endif
92
93 #if defined (_MSC_VER)
94     #pragma warning( push )
95     #pragma warning( disable : 4250 )
96 #endif
97
98     class SHIBSP_DLLLOCAL ADFSSessionInitiator : public SessionInitiator, public AbstractHandler, public RemotedHandler
99     {
100     public:
101         ADFSSessionInitiator(const DOMElement* e, const char* appId)
102                 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator.ADFS")), m_appId(appId), m_binding(WSFED_NS) {
103             // If Location isn't set, defer address registration until the setParent call.
104             pair<bool,const char*> loc = getString("Location");
105             if (loc.first) {
106                 string address = m_appId + loc.second + "::run::ADFSSI";
107                 setAddress(address.c_str());
108             }
109         }
110         virtual ~ADFSSessionInitiator() {}
111         
112         void setParent(const PropertySet* parent) {
113             DOMPropertySet::setParent(parent);
114             pair<bool,const char*> loc = getString("Location");
115             if (loc.first) {
116                 string address = m_appId + loc.second + "::run::ADFSSI";
117                 setAddress(address.c_str());
118             }
119             else {
120                 m_log.warn("no Location property in ADFS SessionInitiator (or parent), can't register as remoted handler");
121             }
122         }
123
124         void receive(DDF& in, ostream& out);
125         pair<bool,long> run(SPRequest& request, const char* entityID=NULL, bool isHandler=true) const;
126
127     private:
128         pair<bool,long> doRequest(
129             const Application& application,
130             HTTPResponse& httpResponse,
131             const char* entityID,
132             const char* acsLocation,
133             string& relayState
134             ) const;
135         string m_appId;
136         auto_ptr_XMLCh m_binding;
137     };
138
139     class SHIBSP_DLLLOCAL ADFSConsumer : public shibsp::AssertionConsumerService
140     {
141     public:
142         ADFSConsumer(const DOMElement* e, const char* appId)
143             : shibsp::AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SSO.ADFS"))
144 #ifndef SHIBSP_LITE
145                 ,m_protocol(WSFED_NS)
146 #endif
147             {}
148         virtual ~ADFSConsumer() {}
149
150     private:
151 #ifndef SHIBSP_LITE
152         string implementProtocol(
153             const Application& application,
154             const HTTPRequest& httpRequest,
155             SecurityPolicy& policy,
156             const PropertySet* settings,
157             const XMLObject& xmlObject
158             ) const;
159         auto_ptr_XMLCh m_protocol;
160 #endif
161     };
162
163     class SHIBSP_DLLLOCAL ADFSLogoutInitiator : public AbstractHandler, public RemotedHandler
164     {
165     public:
166         ADFSLogoutInitiator(const DOMElement* e, const char* appId)
167                 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".LogoutInitiator.ADFS")), m_appId(appId), m_binding(WSFED_NS) {
168             // If Location isn't set, defer address registration until the setParent call.
169             pair<bool,const char*> loc = getString("Location");
170             if (loc.first) {
171                 string address = m_appId + loc.second + "::run::ADFSLI";
172                 setAddress(address.c_str());
173             }
174         }
175         virtual ~ADFSLogoutInitiator() {}
176         
177         void setParent(const PropertySet* parent) {
178             DOMPropertySet::setParent(parent);
179             pair<bool,const char*> loc = getString("Location");
180             if (loc.first) {
181                 string address = m_appId + loc.second + "::run::ADFSLI";
182                 setAddress(address.c_str());
183             }
184             else {
185                 m_log.warn("no Location property in ADFS LogoutInitiator (or parent), can't register as remoted handler");
186             }
187         }
188
189         void receive(DDF& in, ostream& out);
190         pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
191
192     private:
193         pair<bool,long> doRequest(
194             const Application& application, const char* requestURL, const char* entityID, HTTPResponse& httpResponse
195             ) const;
196
197         string m_appId;
198         auto_ptr_XMLCh m_binding;
199     };
200
201     class SHIBSP_DLLLOCAL ADFSLogout : public AbstractHandler, public LogoutHandler
202     {
203     public:
204         ADFSLogout(const DOMElement* e, const char* appId)
205                 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".Logout.ADFS")), m_login(e, appId) {
206 #ifndef SHIBSP_LITE
207             m_initiator = false;
208             m_preserve.push_back("wreply");
209             string address = string(appId) + getString("Location").second + "::run::ADFSLO";
210             setAddress(address.c_str());
211 #endif
212         }
213         virtual ~ADFSLogout() {}
214
215         pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
216
217     private:
218         ADFSConsumer m_login;
219     };
220
221 #if defined (_MSC_VER)
222     #pragma warning( pop )
223 #endif
224
225     SessionInitiator* ADFSSessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
226     {
227         return new ADFSSessionInitiator(p.first, p.second);
228     }
229
230     Handler* ADFSLogoutFactory(const pair<const DOMElement*,const char*>& p)
231     {
232         return new ADFSLogout(p.first, p.second);
233     }
234
235     Handler* ADFSLogoutInitiatorFactory(const pair<const DOMElement*,const char*>& p)
236     {
237         return new ADFSLogoutInitiator(p.first, p.second);
238     }
239
240     const XMLCh RequestedSecurityToken[] =      UNICODE_LITERAL_22(R,e,q,u,e,s,t,e,d,S,e,c,u,r,i,t,y,T,o,k,e,n);
241     const XMLCh RequestSecurityTokenResponse[] =UNICODE_LITERAL_28(R,e,q,u,e,s,t,S,e,c,u,r,i,t,y,T,o,k,e,n,R,e,s,p,o,n,s,e);
242 };
243
244 extern "C" int ADFS_EXPORTS xmltooling_extension_init(void*)
245 {
246     SPConfig& conf=SPConfig::getConfig();
247     conf.SessionInitiatorManager.registerFactory("ADFS", ADFSSessionInitiatorFactory);
248     conf.LogoutInitiatorManager.registerFactory("ADFS", ADFSLogoutInitiatorFactory);
249     conf.AssertionConsumerServiceManager.registerFactory("ADFS", ADFSLogoutFactory);
250     conf.AssertionConsumerServiceManager.registerFactory(WSFED_NS, ADFSLogoutFactory);
251 #ifndef SHIBSP_LITE
252     SAMLConfig::getConfig().MessageDecoderManager.registerFactory(WSFED_NS, ADFSDecoderFactory);
253     XMLObjectBuilder::registerBuilder(QName(WSTRUST_NS,"RequestedSecurityToken"), new AnyElementBuilder());
254     XMLObjectBuilder::registerBuilder(QName(WSTRUST_NS,"RequestSecurityTokenResponse"), new AnyElementBuilder());
255 #endif
256     return 0;
257 }
258
259 extern "C" void ADFS_EXPORTS xmltooling_extension_term()
260 {
261     /* should get unregistered during normal shutdown...
262     SPConfig& conf=SPConfig::getConfig();
263     conf.SessionInitiatorManager.deregisterFactory("ADFS");
264     conf.LogoutInitiatorManager.deregisterFactory("ADFS");
265     conf.AssertionConsumerServiceManager.deregisterFactory("ADFS");
266     conf.AssertionConsumerServiceManager.deregisterFactory(WSFED_NS);
267 #ifndef SHIBSP_LITE
268     SAMLConfig::getConfig().MessageDecoderManager.deregisterFactory(WSFED_NS);
269 #endif
270     */
271 }
272
273 pair<bool,long> ADFSSessionInitiator::run(SPRequest& request, const char* entityID, bool isHandler) const
274 {
275     // We have to know the IdP to function.
276     if (!entityID || !*entityID)
277         return make_pair(false,0);
278
279     string target;
280     const Handler* ACS=NULL;
281     const char* option;
282     const Application& app=request.getApplication();
283
284     if (isHandler) {
285         option = request.getParameter("target");
286         if (option)
287             target = option;
288
289         // Since we're passing the ACS by value, we need to compute the return URL,
290         // so we'll need the target resource for real.
291         recoverRelayState(request.getApplication(), request, target, false);
292     }
293     else {
294         // We're running as a "virtual handler" from within the filter.
295         // The target resource is the current one and everything else is defaulted.
296         target=request.getRequestURL();
297     }
298
299     // Since we're not passing by index, we need to fully compute the return URL.
300     if (!ACS) {
301         // Get all the ADFS endpoints.
302         const vector<const Handler*>& handlers = app.getAssertionConsumerServicesByBinding(m_binding.get());
303
304         // Index comes from request, or default set in the handler, or we just pick the first endpoint.
305         pair<bool,unsigned int> index = make_pair(false,0);
306         if (isHandler) {
307             option = request.getParameter("acsIndex");
308             if (option)
309                 index = make_pair(true, atoi(option));
310         }
311         if (!index.first)
312             index = getUnsignedInt("defaultACSIndex");
313         if (index.first) {
314             for (vector<const Handler*>::const_iterator h = handlers.begin(); !ACS && h!=handlers.end(); ++h) {
315                 if (index.second == (*h)->getUnsignedInt("index").second)
316                     ACS = *h;
317             }
318         }
319         else if (!handlers.empty()) {
320             ACS = handlers.front();
321         }
322     }
323     if (!ACS)
324         throw ConfigurationException("Unable to locate ADFS response endpoint.");
325
326     // Compute the ACS URL. We add the ACS location to the base handlerURL.
327     string ACSloc=request.getHandlerURL(target.c_str());
328     pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
329     if (loc.first) ACSloc+=loc.second;
330
331     if (isHandler) {
332         // We may already have RelayState set if we looped back here,
333         // but just in case target is a resource, we reset it back.
334         target.erase();
335         option = request.getParameter("target");
336         if (option)
337             target = option;
338     }
339
340     m_log.debug("attempting to initiate session using ADFS with provider (%s)", entityID);
341
342     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess))
343         return doRequest(app, request, entityID, ACSloc.c_str(), target);
344
345     // Remote the call.
346     DDF out,in = DDF(m_address.c_str()).structure();
347     DDFJanitor jin(in), jout(out);
348     in.addmember("application_id").string(app.getId());
349     in.addmember("entity_id").string(entityID);
350     in.addmember("acsLocation").string(ACSloc.c_str());
351     if (!target.empty())
352         in.addmember("RelayState").string(target.c_str());
353
354     // Remote the processing.
355     out = request.getServiceProvider().getListenerService()->send(in);
356     return unwrap(request, out);
357 }
358
359 void ADFSSessionInitiator::receive(DDF& in, ostream& out)
360 {
361     // Find application.
362     const char* aid=in["application_id"].string();
363     const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
364     if (!app) {
365         // Something's horribly wrong.
366         m_log.error("couldn't find application (%s) to generate ADFS request", aid ? aid : "(missing)");
367         throw ConfigurationException("Unable to locate application for new session, deleted?");
368     }
369
370     const char* entityID = in["entity_id"].string();
371     const char* acsLocation = in["acsLocation"].string();
372     if (!entityID || !acsLocation)
373         throw ConfigurationException("No entityID or acsLocation parameter supplied to remoted SessionInitiator.");
374
375     DDF ret(NULL);
376     DDFJanitor jout(ret);
377
378     // Wrap the outgoing object with a Response facade.
379     auto_ptr<HTTPResponse> http(getResponse(ret));
380
381     string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");
382
383     // Since we're remoted, the result should either be a throw, which we pass on,
384     // a false/0 return, which we just return as an empty structure, or a response/redirect,
385     // which we capture in the facade and send back.
386     doRequest(*app, *http.get(), entityID, acsLocation, relayState);
387     out << ret;
388 }
389
390 pair<bool,long> ADFSSessionInitiator::doRequest(
391     const Application& app,
392     HTTPResponse& httpResponse,
393     const char* entityID,
394     const char* acsLocation,
395     string& relayState
396     ) const
397 {
398 #ifndef SHIBSP_LITE
399     // Use metadata to invoke the SSO service directly.
400     MetadataProvider* m=app.getMetadataProvider();
401     Locker locker(m);
402     const EntityDescriptor* entity=m->getEntityDescriptor(entityID);
403     if (!entity) {
404         m_log.error("unable to locate metadata for provider (%s)", entityID);
405         throw MetadataException("Unable to locate metadata for identity provider ($entityID)",
406             namedparams(1, "entityID", entityID));
407     }
408     const IDPSSODescriptor* role=entity->getIDPSSODescriptor(m_binding.get());
409     if (!role) {
410         m_log.error("unable to locate ADFS-aware identity provider role for provider (%s)", entityID);
411         return make_pair(false,0);
412     }
413     const EndpointType* ep=EndpointManager<SingleSignOnService>(role->getSingleSignOnServices()).getByBinding(m_binding.get());
414     if (!ep) {
415         m_log.error("unable to locate compatible SSO service for provider (%s)", entityID);
416         return make_pair(false,0);
417     }
418
419     preserveRelayState(app, httpResponse, relayState);
420
421     // UTC timestamp
422     time_t epoch=time(NULL);
423 #ifndef HAVE_GMTIME_R
424     struct tm* ptime=gmtime(&epoch);
425 #else
426     struct tm res;
427     struct tm* ptime=gmtime_r(&epoch,&res);
428 #endif
429     char timebuf[32];
430     strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
431
432     auto_ptr_char dest(ep->getLocation());
433     const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
434
435     string req=string(dest.get()) + (strchr(dest.get(),'?') ? '&' : '?') + "wa=wsignin1.0&wreply=" + urlenc->encode(acsLocation) +
436         "&wct=" + urlenc->encode(timebuf) + "&wtrealm=" + urlenc->encode(app.getString("entityID").second);
437     if (!relayState.empty())
438         req += "&wctx=" + urlenc->encode(relayState.c_str());
439
440     return make_pair(true, httpResponse.sendRedirect(req.c_str()));
441 #else
442     return make_pair(false,0);
443 #endif
444 }
445
446 #ifndef SHIBSP_LITE
447
448 XMLObject* ADFSDecoder::decode(string& relayState, const GenericRequest& genericRequest, SecurityPolicy& policy) const
449 {
450 #ifdef _DEBUG
451     xmltooling::NDC ndc("decode");
452 #endif
453     Category& log = Category::getInstance(SHIBSP_LOGCAT".MessageDecoder.ADFS");
454
455     log.debug("validating input");
456     const HTTPRequest* httpRequest=dynamic_cast<const HTTPRequest*>(&genericRequest);
457     if (!httpRequest)
458         throw BindingException("Unable to cast request object to HTTPRequest type.");
459     if (strcmp(httpRequest->getMethod(),"POST"))
460         throw BindingException("Invalid HTTP method ($1).", params(1, httpRequest->getMethod()));
461     const char* param = httpRequest->getParameter("wa");
462     if (!param || strcmp(param, "wsignin1.0"))
463         throw BindingException("Missing or invalid wa parameter (should be wsignin1.0).");
464     param = httpRequest->getParameter("wctx");
465     if (param)
466         relayState = param;
467
468     param = httpRequest->getParameter("wresult");
469     if (!param)
470         throw BindingException("Request missing wresult parameter.");
471
472     log.debug("decoded ADFS response:\n%s", param);
473
474     // Parse and bind the document into an XMLObject.
475     istringstream is(param);
476     DOMDocument* doc = (policy.getValidating() ? XMLToolingConfig::getConfig().getValidatingParser()
477         : XMLToolingConfig::getConfig().getParser()).parse(is); 
478     XercesJanitor<DOMDocument> janitor(doc);
479     auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
480     janitor.release();
481
482     if (!XMLHelper::isNodeNamed(xmlObject->getDOM(), m_ns.get(), RequestSecurityTokenResponse))
483         throw BindingException("Decoded message was not of the appropriate type.");
484
485     if (!policy.getValidating())
486         SchemaValidators.validate(xmlObject.get());
487
488     // Skip policy step here, there's no security in the wrapper.
489     // policy.evaluate(*xmlObject.get(), &genericRequest);
490     
491     return xmlObject.release();
492 }
493
494 string ADFSConsumer::implementProtocol(
495     const Application& application,
496     const HTTPRequest& httpRequest,
497     SecurityPolicy& policy,
498     const PropertySet* settings,
499     const XMLObject& xmlObject
500     ) const
501 {
502     // Implementation of ADFS profile.
503     m_log.debug("processing message against ADFS Passive Requester profile");
504
505     // With ADFS, all the security comes from the assertion, which is two levels down in the message.
506
507     const ElementProxy* response = dynamic_cast<const ElementProxy*>(&xmlObject);
508     if (!response || !response->hasChildren())
509         throw FatalProfileException("Incoming message was not of the proper type or contains no security token.");
510     response = dynamic_cast<const ElementProxy*>(response->getUnknownXMLObjects().front());
511     if (!response || !response->hasChildren())
512         throw FatalProfileException("Token wrapper element did not contain a security token.");
513     const saml1::Assertion* token = dynamic_cast<const saml1::Assertion*>(response->getUnknownXMLObjects().front());
514     if (!token || !token->getSignature())
515         throw FatalProfileException("Incoming message did not contain a signed SAML 1.1 assertion.");
516
517     // Run the policy over the assertion. Handles issuer consistency, replay, freshness,
518     // and signature verification, assuming the relevant rules are configured.
519     policy.evaluate(*token, NULL, m_protocol.get());
520     
521     // If no security is in place now, we kick it.
522     if (!policy.isSecure())
523         throw SecurityPolicyException("Unable to establish security of incoming assertion.");
524
525     // Now do profile and core semantic validation to ensure we can use it for SSO.
526     // Profile validator.
527     time_t now = time(NULL);
528     saml1::AssertionValidator ssoValidator(application.getAudiences(), now);
529     ssoValidator.validateAssertion(*token);
530     if (!token->getConditions() || !token->getConditions()->getNotBefore() || !token->getConditions()->getNotOnOrAfter())
531         throw FatalProfileException("Assertion did not contain time conditions.");
532     else if (token->getAuthenticationStatements().empty())
533         throw FatalProfileException("Assertion did not contain an authentication statement.");
534
535     // With ADFS, we only have one token, but we need to put it in a vector.
536     vector<const Assertion*> tokens(1,token);
537     const saml1::AuthenticationStatement* ssoStatement=token->getAuthenticationStatements().front();
538
539     // Address checking.
540     saml1::SubjectLocality* locality = ssoStatement->getSubjectLocality();
541     if (locality && locality->getIPAddress()) {
542         auto_ptr_char ip(locality->getIPAddress());
543         checkAddress(application, httpRequest, ip.get());
544     }
545
546     m_log.debug("ADFS profile processing completed successfully");
547
548     saml1::NameIdentifier* n = ssoStatement->getSubject()->getNameIdentifier();
549
550     // Now we have to extract the authentication details for attribute and session setup.
551
552     // Session expiration for ADFS is purely SP-driven, and the method is mapped to a ctx class.
553     const PropertySet* sessionProps = application.getPropertySet("Sessions");
554     pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
555     if (!lifetime.first || lifetime.second == 0)
556         lifetime.second = 28800;
557
558     // We've successfully "accepted" the SSO token.
559     // To complete processing, we need to extract and resolve attributes and then create the session.
560
561     // Normalize the SAML 1.x NameIdentifier...
562     auto_ptr<saml2::NameID> nameid(n ? saml2::NameIDBuilder::buildNameID() : NULL);
563     if (n) {
564         nameid->setName(n->getName());
565         nameid->setFormat(n->getFormat());
566         nameid->setNameQualifier(n->getNameQualifier());
567     }
568
569     // The context will handle deleting attributes and new tokens.
570         auto_ptr<ResolutionContext> ctx(
571         resolveAttributes(
572             application,
573             policy.getIssuerMetadata(),
574             m_protocol.get(),
575             n,
576             nameid.get(),
577             ssoStatement->getAuthenticationMethod(),
578             NULL,
579             &tokens
580             )
581         );
582
583     if (ctx.get()) {
584         // Copy over any new tokens, but leave them in the context for cleanup.
585         tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
586     }
587
588     return application.getServiceProvider().getSessionCache()->insert(
589         now + lifetime.second,
590         application,
591         httpRequest.getRemoteAddr().c_str(),
592         policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL,
593         m_protocol.get(),
594         nameid.get(),
595         ssoStatement->getAuthenticationInstant() ? ssoStatement->getAuthenticationInstant()->getRawData() : NULL,
596         NULL,
597         ssoStatement->getAuthenticationMethod(),
598         NULL,
599         &tokens,
600         ctx.get() ? &ctx->getResolvedAttributes() : NULL
601         );
602 }
603
604 #endif
605
606 pair<bool,long> ADFSLogoutInitiator::run(SPRequest& request, bool isHandler) const
607 {
608     // Normally we'd do notifications and session clearage here, but ADFS logout
609     // is missing the needed request/response features, so we have to rely on
610     // the IdP half to notify us back about the logout and do the work there.
611     // Basically we have no way to tell in the Logout receiving handler whether
612     // we initiated the logout or not.
613
614     Session* session = NULL;
615     try {
616         session = request.getSession(false, true, false);  // don't cache it and ignore all checks
617         if (!session)
618             return make_pair(false,0);
619
620         // We only handle ADFS sessions.
621         if (!XMLString::equals(session->getProtocol(), WSFED_NS) || !session->getEntityID()) {
622             session->unlock();
623             return make_pair(false,0);
624         }
625     }
626     catch (exception& ex) {
627         m_log.error("error accessing current session: %s", ex.what());
628         return make_pair(false,0);
629     }
630
631     string entityID(session->getEntityID());
632     session->unlock();
633
634     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
635         // When out of process, we run natively.
636         return doRequest(request.getApplication(), request.getRequestURL(), entityID.c_str(), request);
637     }
638     else {
639         // When not out of process, we remote the request.
640         Locker locker(session, false);
641         DDF out,in(m_address.c_str());
642         DDFJanitor jin(in), jout(out);
643         in.addmember("application_id").string(request.getApplication().getId());
644         in.addmember("url").string(request.getRequestURL());
645         in.addmember("entity_id").string(entityID.c_str());
646         out=request.getServiceProvider().getListenerService()->send(in);
647         return unwrap(request, out);
648     }
649 }
650
651 void ADFSLogoutInitiator::receive(DDF& in, ostream& out)
652 {
653 #ifndef SHIBSP_LITE
654     // Find application.
655     const char* aid=in["application_id"].string();
656     const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
657     if (!app) {
658         // Something's horribly wrong.
659         m_log.error("couldn't find application (%s) for logout", aid ? aid : "(missing)");
660         throw ConfigurationException("Unable to locate application for logout, deleted?");
661     }
662     
663     // Set up a response shim.
664     DDF ret(NULL);
665     DDFJanitor jout(ret);
666     auto_ptr<HTTPResponse> resp(getResponse(ret));
667     
668     // Since we're remoted, the result should either be a throw, which we pass on,
669     // a false/0 return, which we just return as an empty structure, or a response/redirect,
670     // which we capture in the facade and send back.
671     doRequest(*app, in["url"].string(), in["entity_id"].string(), *resp.get());
672
673     out << ret;
674 #else
675     throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
676 #endif
677 }
678
679 pair<bool,long> ADFSLogoutInitiator::doRequest(
680     const Application& application, const char* requestURL, const char* entityID, HTTPResponse& response
681     ) const
682 {
683 #ifndef SHIBSP_LITE
684     try {
685         if (!entityID)
686             throw ConfigurationException("Missing entityID parameter.");
687
688         // With a session in hand, we can create a request message, if we can find a compatible endpoint.
689         Locker metadataLocker(application.getMetadataProvider());
690         const EntityDescriptor* entity = application.getMetadataProvider()->getEntityDescriptor(entityID);
691         if (!entity) {
692             throw MetadataException(
693                 "Unable to locate metadata for identity provider ($entityID)",
694                 namedparams(1, "entityID", entityID)
695                 );
696         }
697         const IDPSSODescriptor* role = entity->getIDPSSODescriptor(m_binding.get());
698         if (!role) {
699             throw MetadataException(
700                 "Unable to locate ADFS IdP role for identity provider ($entityID).",
701                 namedparams(1, "entityID", entityID)
702                 );
703         }
704
705         const EndpointType* ep = EndpointManager<SingleLogoutService>(role->getSingleLogoutServices()).getByBinding(m_binding.get());
706         if (!ep) {
707             throw MetadataException(
708                 "Unable to locate ADFS single logout service for identity provider ($entityID).",
709                 namedparams(1, "entityID", entityID)
710                 );
711         }
712
713         auto_ptr_char dest(ep->getLocation());
714
715         string req=string(dest.get()) + (strchr(dest.get(),'?') ? '&' : '?') + "wa=wsignout1.0";
716         return make_pair(true,response.sendRedirect(req.c_str()));
717     }
718     catch (exception& ex) {
719         m_log.error("error issuing ADFS logout request: %s", ex.what());
720     }
721
722     return make_pair(false,0);
723 #else
724     throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
725 #endif
726 }
727
728 pair<bool,long> ADFSLogout::run(SPRequest& request, bool isHandler) const
729 {
730     // Defer to base class for front-channel loop first.
731     // This won't initiate the loop, only continue/end it.
732     pair<bool,long> ret = LogoutHandler::run(request, isHandler);
733     if (ret.first)
734         return ret;
735
736     // wa parameter indicates the "action" to perform
737     bool returning = false;
738     const char* param = request.getParameter("wa");
739     if (param) {
740         if (!strcmp(param, "wsignin1.0"))
741             return m_login.run(request, isHandler);
742         else if (strcmp(param, "wsignout1.0") && strcmp(param, "wsignoutcleanup1.0"))
743             throw FatalProfileException("Unsupported WS-Federation action paremeter ($1).", params(1, param));
744     }
745     else if (strcmp(request.getMethod(),"GET") || !request.getParameter("notifying"))
746         throw FatalProfileException("Unsupported request to ADFS protocol endpoint.");
747     else
748         returning = true;
749
750     param = request.getParameter("wreply");
751     const Application& app = request.getApplication();
752
753     // Get the session_id.
754     pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_");
755     const char* session_id = request.getCookie(shib_cookie.first.c_str());
756
757     if (!returning) {
758         // Pass control to the first front channel notification point, if any.
759         map<string,string> parammap;
760         if (param)
761             parammap["wreply"] = param;
762         pair<bool,long> result = notifyFrontChannel(app, request, request, &parammap);
763         if (result.first)
764             return result;
765     }
766
767     // Best effort on back channel and to remove the user agent's session.
768     if (session_id) {
769         vector<string> sessions(1,session_id);
770         notifyBackChannel(app, request.getRequestURL(), sessions, false);
771         try {
772             app.getServiceProvider().getSessionCache()->remove(session_id, app);
773         }
774         catch (exception& ex) {
775             m_log.error("error removing session (%s): %s", session_id, ex.what());
776         }
777         request.setCookie(shib_cookie.first.c_str(), shib_cookie.second);
778     }
779
780     if (param)
781         return make_pair(true, request.sendRedirect(param));
782     return sendLogoutPage(app, request, false, "Logout complete.");
783 }