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