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