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