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