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