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