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