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