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