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