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