2 * Copyright 2001-2005 Internet2
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
20 * ADFSv1 extension library
23 #if defined (_MSC_VER) || defined(__BORLANDC__)
24 # include "config_win32.h"
30 # define _CRT_NONSTDC_NO_DEPRECATE 1
31 # define _CRT_SECURE_NO_DEPRECATE 1
32 # define ADFS_EXPORTS __declspec(dllexport)
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>
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;
68 # define min(a,b) (((a) < (b)) ? (a) : (b))
71 using namespace shibsp;
72 using namespace opensaml;
73 using namespace xmltooling::logging;
74 using namespace xmltooling;
75 using namespace xercesc;
78 #define WSFED_NS "http://schemas.xmlsoap.org/ws/2003/07/secext"
79 #define WSTRUST_NS "http://schemas.xmlsoap.org/ws/2005/02/trust"
84 class SHIBSP_DLLLOCAL ADFSDecoder : public MessageDecoder
88 ADFSDecoder() : m_ns(WSTRUST_NS) {}
89 virtual ~ADFSDecoder() {}
91 XMLObject* decode(string& relayState, const GenericRequest& genericRequest, SecurityPolicy& policy) const;
94 void extractMessageDetails(
95 const XMLObject& message, const GenericRequest& req, const XMLCh* protocol, SecurityPolicy& policy
100 MessageDecoder* ADFSDecoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
102 return new ADFSDecoder();
106 #if defined (_MSC_VER)
107 #pragma warning( push )
108 #pragma warning( disable : 4250 )
111 class SHIBSP_DLLLOCAL ADFSSessionInitiator : public SessionInitiator, public AbstractHandler, public RemotedHandler
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");
119 string address = m_appId + loc.second + "::run::ADFSSI";
120 setAddress(address.c_str());
123 virtual ~ADFSSessionInitiator() {}
125 void setParent(const PropertySet* parent) {
126 DOMPropertySet::setParent(parent);
127 pair<bool,const char*> loc = getString("Location");
129 string address = m_appId + loc.second + "::run::ADFSSI";
130 setAddress(address.c_str());
133 m_log.warn("no Location property in ADFS SessionInitiator (or parent), can't register as remoted handler");
137 void receive(DDF& in, ostream& out);
138 pair<bool,long> run(SPRequest& request, string& entityID, bool isHandler=true) const;
141 pair<bool,long> doRequest(
142 const Application& application,
143 HTTPResponse& httpResponse,
144 const char* entityID,
145 const char* acsLocation,
146 const char* authnContextClassRef,
150 auto_ptr_XMLCh m_binding;
153 class SHIBSP_DLLLOCAL ADFSConsumer : public shibsp::AssertionConsumerService
156 ADFSConsumer(const DOMElement* e, const char* appId)
157 : shibsp::AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SSO.ADFS"))
159 ,m_protocol(WSFED_NS)
162 virtual ~ADFSConsumer() {}
165 void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
166 AssertionConsumerService::generateMetadata(role, handlerURL);
167 role.addSupport(m_protocol.get());
170 auto_ptr_XMLCh m_protocol;
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
184 class SHIBSP_DLLLOCAL ADFSLogoutInitiator : public AbstractHandler, public LogoutHandler
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");
192 string address = m_appId + loc.second + "::run::ADFSLI";
193 setAddress(address.c_str());
196 virtual ~ADFSLogoutInitiator() {}
198 void setParent(const PropertySet* parent) {
199 DOMPropertySet::setParent(parent);
200 pair<bool,const char*> loc = getString("Location");
202 string address = m_appId + loc.second + "::run::ADFSLI";
203 setAddress(address.c_str());
206 m_log.warn("no Location property in ADFS LogoutInitiator (or parent), can't register as remoted handler");
210 void receive(DDF& in, ostream& out);
211 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
214 const char* getType() const {
215 return "LogoutInitiator";
220 pair<bool,long> doRequest(const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse, Session* session) const;
223 auto_ptr_XMLCh m_binding;
226 class SHIBSP_DLLLOCAL ADFSLogout : public AbstractHandler, public LogoutHandler
229 ADFSLogout(const DOMElement* e, const char* appId)
230 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".Logout.ADFS")), m_login(e, appId) {
233 m_preserve.push_back("wreply");
234 string address = string(appId) + getString("Location").second + "::run::ADFSLO";
235 setAddress(address.c_str());
238 virtual ~ADFSLogout() {}
240 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
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);
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);
257 const char* getType() const {
258 return m_login.getType();
263 ADFSConsumer m_login;
266 #if defined (_MSC_VER)
267 #pragma warning( pop )
270 SessionInitiator* ADFSSessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
272 return new ADFSSessionInitiator(p.first, p.second);
275 Handler* ADFSLogoutFactory(const pair<const DOMElement*,const char*>& p)
277 return new ADFSLogout(p.first, p.second);
280 Handler* ADFSLogoutInitiatorFactory(const pair<const DOMElement*,const char*>& p)
282 return new ADFSLogoutInitiator(p.first, p.second);
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);
289 extern "C" int ADFS_EXPORTS xmltooling_extension_init(void*)
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);
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());
304 extern "C" void ADFS_EXPORTS xmltooling_extension_term()
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);
313 SAMLConfig::getConfig().MessageDecoderManager.deregisterFactory(WSFED_NS);
318 pair<bool,long> ADFSSessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
320 // We have to know the IdP to function.
321 if (entityID.empty())
322 return make_pair(false,0L);
325 const Handler* ACS=NULL;
327 pair<bool,const char*> acClass;
328 const Application& app=request.getApplication();
331 option = request.getParameter("target");
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);
339 if (acClass.second = request.getParameter("authnContextClassRef"))
340 acClass.first = true;
342 acClass = getString("authnContextClassRef");
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();
349 const PropertySet* settings = request.getRequestSettings().first;
350 acClass = settings->getString("authnContextClassRef");
352 acClass = getString("authnContextClassRef");
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());
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);
362 option = request.getParameter("acsIndex");
364 index = pair<bool,unsigned int>(true, atoi(option));
367 index = getUnsignedInt("defaultACSIndex");
369 for (vector<const Handler*>::const_iterator h = handlers.begin(); !ACS && h!=handlers.end(); ++h) {
370 if (index.second == (*h)->getUnsignedInt("index").second)
374 else if (!handlers.empty()) {
375 ACS = handlers.front();
378 throw ConfigurationException("Unable to locate ADFS response endpoint.");
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;
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.
389 option = request.getParameter("target");
394 m_log.debug("attempting to initiate session using ADFS with provider (%s)", entityID.c_str());
396 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess))
397 return doRequest(app, request, entityID.c_str(), ACSloc.c_str(), (acClass.first ? acClass.second : NULL), target);
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());
406 in.addmember("RelayState").string(target.c_str());
408 in.addmember("authnContextClassRef").string(acClass.second);
410 // Remote the processing.
411 out = request.getServiceProvider().getListenerService()->send(in);
412 return unwrap(request, out);
415 void ADFSSessionInitiator::receive(DDF& in, ostream& out)
418 const char* aid=in["application_id"].string();
419 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
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?");
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.");
432 DDFJanitor jout(ret);
434 // Wrap the outgoing object with a Response facade.
435 auto_ptr<HTTPResponse> http(getResponse(ret));
437 string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");
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);
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,
456 // Use metadata to invoke the SSO service directly.
457 MetadataProvider* m=app.getMetadataProvider();
459 MetadataProviderCriteria mc(app, entityID, &IDPSSODescriptor::ELEMENT_QNAME, m_binding.get());
460 pair<const EntityDescriptor*,const RoleDescriptor*> entity=m->getEntityDescriptor(mc);
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));
465 else if (!entity.second) {
466 m_log.warn("unable to locate ADFS-aware identity provider role for provider (%s)", entityID);
468 return make_pair(false,0L);
469 throw MetadataException("Unable to locate ADFS-aware identity provider role for provider ($entityID)", namedparams(1, "entityID", entityID));
471 const EndpointType* ep = EndpointManager<SingleSignOnService>(
472 dynamic_cast<const IDPSSODescriptor*>(entity.second)->getSingleSignOnServices()
473 ).getByBinding(m_binding.get());
475 m_log.warn("unable to locate compatible SSO service for provider (%s)", entityID);
477 return make_pair(false,0L);
478 throw MetadataException("Unable to locate compatible SSO service for provider ($entityID)", namedparams(1, "entityID", entityID));
481 preserveRelayState(app, httpResponse, relayState);
484 time_t epoch=time(NULL);
485 #ifndef HAVE_GMTIME_R
486 struct tm* ptime=gmtime(&epoch);
489 struct tm* ptime=gmtime_r(&epoch,&res);
492 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
494 auto_ptr_char dest(ep->getLocation());
495 const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
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());
504 return make_pair(true, httpResponse.sendRedirect(req.c_str()));
506 return make_pair(false,0L);
512 XMLObject* ADFSDecoder::decode(string& relayState, const GenericRequest& genericRequest, SecurityPolicy& policy) const
515 xmltooling::NDC ndc("decode");
517 Category& log = Category::getInstance(SHIBSP_LOGCAT".MessageDecoder.ADFS");
519 log.debug("validating input");
520 const HTTPRequest* httpRequest=dynamic_cast<const HTTPRequest*>(&genericRequest);
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");
532 param = httpRequest->getParameter("wresult");
534 throw BindingException("Request missing wresult parameter.");
536 log.debug("decoded ADFS response:\n%s", param);
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));
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.");
551 if (!policy.getValidating())
552 SchemaValidators.validate(xmlObject.get());
554 // Skip policy step here, there's no security in the wrapper.
555 // policy.evaluate(*xmlObject.get(), &genericRequest);
557 return xmlObject.release();
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
569 // Implementation of ADFS profile.
570 m_log.debug("processing message against ADFS Passive Requester profile");
572 // With ADFS, all the security comes from the assertion, which is two levels down in the message.
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.");
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.");
592 // Extract message and issuer details from assertion.
593 extractMessageDetails(*token, m_protocol.get(), policy);
595 // Run the policy over the assertion. Handles replay, freshness, and
596 // signature verification, assuming the relevant rules are configured.
597 policy.evaluate(*token);
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.");
603 time_t now = time(NULL);
605 const PropertySet* sessionProps = application.getPropertySet("Sessions");
606 const EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL;
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;
614 const saml1::Assertion* saml1token = dynamic_cast<const saml1::Assertion*>(token);
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.");
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);
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.");
633 saml1::SubjectLocality* locality = ssoStatement->getSubjectLocality();
634 if (locality && locality->getIPAddress()) {
635 auto_ptr_char ip(locality->getIPAddress());
636 checkAddress(application, httpRequest, ip.get());
639 saml1name = ssoStatement->getSubject()->getNameIdentifier();
640 authMethod = ssoStatement->getAuthenticationMethod();
641 if (ssoStatement->getAuthenticationInstant())
642 authInstant = ssoStatement->getAuthenticationInstant()->getRawData();
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;
651 const saml2::Assertion* saml2token = dynamic_cast<const saml2::Assertion*>(token);
653 throw FatalProfileException("Incoming message did not contain a recognized type of SAML assertion.");
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.");
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);
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.");
672 saml2::SubjectLocality* locality = ssoStatement->getSubjectLocality();
673 if (locality && locality->getAddress()) {
674 auto_ptr_char ip(locality->getAddress());
675 checkAddress(application, httpRequest, ip.get());
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();
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;
690 sessionExp = now + lifetime.second; // IdP says nothing, calulate based on SP.
692 sessionExp = min(sessionExp, now + lifetime.second); // Use the lowest.
695 m_log.debug("ADFS profile processing completed successfully");
697 // We've successfully "accepted" the SSO token.
698 // To complete processing, we need to extract and resolve attributes and then create the session.
700 // Normalize a SAML 1.x NameIdentifier...
701 auto_ptr<saml2::NameID> nameid(saml1name ? saml2::NameIDBuilder::buildNameID() : NULL);
703 nameid->setName(saml1name->getName());
704 nameid->setFormat(saml1name->getFormat());
705 nameid->setNameQualifier(saml1name->getNameQualifier());
708 // The context will handle deleting attributes and new tokens.
709 vector<const Assertion*> tokens(1,token);
710 auto_ptr<ResolutionContext> ctx(
713 policy.getIssuerMetadata(),
716 (saml1name ? nameid.get() : saml2name),
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());
728 application.getServiceProvider().getSessionCache()->insert(
735 (saml1name ? nameid.get() : saml2name),
741 ctx.get() ? &ctx->getResolvedAttributes() : NULL
747 pair<bool,long> ADFSLogoutInitiator::run(SPRequest& request, bool isHandler) const
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.
755 Session* session = NULL;
757 session = request.getSession(false, true, false); // don't cache it and ignore all checks
759 return make_pair(false,0L);
761 // We only handle ADFS sessions.
762 if (!XMLString::equals(session->getProtocol(), WSFED_NS) || !session->getEntityID()) {
764 return make_pair(false,0L);
767 catch (exception& ex) {
768 m_log.error("error accessing current session: %s", ex.what());
769 return make_pair(false,0L);
772 string entityID(session->getEntityID());
775 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
776 // When out of process, we run natively.
777 return doRequest(request.getApplication(), request, request, session);
780 // When not out of process, we remote the request.
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);
790 void ADFSLogoutInitiator::receive(DDF& in, ostream& out)
793 // Defer to base class for notifications
794 if (in["notify"].integer() == 1)
795 return LogoutHandler::receive(in, out);
798 const char* aid=in["application_id"].string();
799 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
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?");
806 // Unpack the request.
807 auto_ptr<HTTPRequest> req(getRequest(in));
809 // Set up a response shim.
811 DDFJanitor jout(ret);
812 auto_ptr<HTTPResponse> resp(getResponse(ret));
814 Session* session = NULL;
816 session = app->getServiceProvider().getSessionCache()->find(*app, *req.get(), NULL, NULL);
818 catch (exception& ex) {
819 m_log.error("error accessing current session: %s", ex.what());
822 // With no session, we just skip the request and let it fall through to an empty struct return.
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);
831 m_log.error("no issuing entityID found in session");
833 app->getServiceProvider().getSessionCache()->remove(*app, *req.get(), resp.get());
838 throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
842 pair<bool,long> ADFSLogoutInitiator::doRequest(
843 const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse, Session* session
846 // Do back channel notification.
847 vector<string> sessions(1, session->getID());
848 if (!notifyBackChannel(application, httpRequest.getRequestURL(), sessions, false)) {
850 application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
851 return sendLogoutPage(application, httpRequest, httpResponse, true, "Partial logout failure.");
855 pair<bool,long> ret = make_pair(false,0L);
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);
864 throw MetadataException(
865 "Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", session->getEntityID())
868 else if (!entity.second) {
869 throw MetadataException(
870 "Unable to locate ADFS IdP role for identity provider ($entityID).", namedparams(1, "entityID", session->getEntityID())
874 const EndpointType* ep = EndpointManager<SingleLogoutService>(
875 dynamic_cast<const IDPSSODescriptor*>(entity.second)->getSingleLogoutServices()
876 ).getByBinding(m_binding.get());
878 throw MetadataException(
879 "Unable to locate ADFS single logout service for identity provider ($entityID).", namedparams(1, "entityID", session->getEntityID())
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";
888 req += "&wreply=" + urlenc->encode(returnloc);
889 ret.second = httpResponse.sendRedirect(req.c_str());
892 catch (exception& ex) {
893 m_log.error("error issuing ADFS logout request: %s", ex.what());
899 application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
904 throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
908 pair<bool,long> ADFSLogout::run(SPRequest& request, bool isHandler) const
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);
916 // wa parameter indicates the "action" to perform
917 bool returning = false;
918 const char* param = request.getParameter("wa");
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));
925 else if (strcmp(request.getMethod(),"GET") || !request.getParameter("notifying"))
926 throw FatalProfileException("Unsupported request to ADFS protocol endpoint.");
930 param = request.getParameter("wreply");
931 const Application& app = request.getApplication();
934 // Pass control to the first front channel notification point, if any.
935 map<string,string> parammap;
937 parammap["wreply"] = param;
938 pair<bool,long> result = notifyFrontChannel(app, request, request, ¶mmap);
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);
949 app.getServiceProvider().getSessionCache()->remove(app, request, &request);
951 catch (exception& ex) {
952 m_log.error("error removing session (%s): %s", session_id.c_str(), ex.what());
957 return make_pair(true, request.sendRedirect(param));
958 return sendLogoutPage(app, request, request, false, "Logout complete.");