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