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