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