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