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