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)
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>
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;
65 # define min(a,b) (((a) < (b)) ? (a) : (b))
68 using namespace shibsp;
69 using namespace opensaml;
70 using namespace xmltooling::logging;
71 using namespace xmltooling;
72 using namespace xercesc;
75 #define WSFED_NS "http://schemas.xmlsoap.org/ws/2003/07/secext"
76 #define WSTRUST_NS "http://schemas.xmlsoap.org/ws/2005/02/trust"
81 class SHIBSP_DLLLOCAL ADFSDecoder : public MessageDecoder
85 ADFSDecoder() : m_ns(WSTRUST_NS) {}
86 virtual ~ADFSDecoder() {}
88 XMLObject* decode(string& relayState, const GenericRequest& genericRequest, SecurityPolicy& policy) const;
91 void extractMessageDetails(
92 const XMLObject& message, const GenericRequest& req, const XMLCh* protocol, SecurityPolicy& policy
97 MessageDecoder* ADFSDecoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
99 return new ADFSDecoder();
103 #if defined (_MSC_VER)
104 #pragma warning( push )
105 #pragma warning( disable : 4250 )
108 class SHIBSP_DLLLOCAL ADFSSessionInitiator : public SessionInitiator, public AbstractHandler, public RemotedHandler
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");
116 string address = m_appId + loc.second + "::run::ADFSSI";
117 setAddress(address.c_str());
120 virtual ~ADFSSessionInitiator() {}
122 void setParent(const PropertySet* parent) {
123 DOMPropertySet::setParent(parent);
124 pair<bool,const char*> loc = getString("Location");
126 string address = m_appId + loc.second + "::run::ADFSSI";
127 setAddress(address.c_str());
130 m_log.warn("no Location property in ADFS SessionInitiator (or parent), can't register as remoted handler");
134 void receive(DDF& in, ostream& out);
135 pair<bool,long> run(SPRequest& request, string& entityID, bool isHandler=true) const;
138 pair<bool,long> doRequest(
139 const Application& application,
140 HTTPResponse& httpResponse,
141 const char* entityID,
142 const char* acsLocation,
143 const char* authnContextClassRef,
147 auto_ptr_XMLCh m_binding;
150 class SHIBSP_DLLLOCAL ADFSConsumer : public shibsp::AssertionConsumerService
153 ADFSConsumer(const DOMElement* e, const char* appId)
154 : shibsp::AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SSO.ADFS"))
156 ,m_protocol(WSFED_NS)
159 virtual ~ADFSConsumer() {}
162 void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
163 AssertionConsumerService::generateMetadata(role, handlerURL);
164 role.addSupport(m_protocol.get());
167 auto_ptr_XMLCh m_protocol;
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
181 class SHIBSP_DLLLOCAL ADFSLogoutInitiator : public AbstractHandler, public RemotedHandler
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");
189 string address = m_appId + loc.second + "::run::ADFSLI";
190 setAddress(address.c_str());
193 virtual ~ADFSLogoutInitiator() {}
195 void setParent(const PropertySet* parent) {
196 DOMPropertySet::setParent(parent);
197 pair<bool,const char*> loc = getString("Location");
199 string address = m_appId + loc.second + "::run::ADFSLI";
200 setAddress(address.c_str());
203 m_log.warn("no Location property in ADFS LogoutInitiator (or parent), can't register as remoted handler");
207 void receive(DDF& in, ostream& out);
208 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
211 const char* getType() const {
212 return "LogoutInitiator";
217 pair<bool,long> doRequest(const Application& application, const char* entityID, HTTPResponse& httpResponse) const;
220 auto_ptr_XMLCh m_binding;
223 class SHIBSP_DLLLOCAL ADFSLogout : public AbstractHandler, public LogoutHandler
226 ADFSLogout(const DOMElement* e, const char* appId)
227 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".Logout.ADFS")), m_login(e, appId) {
230 m_preserve.push_back("wreply");
231 string address = string(appId) + getString("Location").second + "::run::ADFSLO";
232 setAddress(address.c_str());
235 virtual ~ADFSLogout() {}
237 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
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);
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);
254 const char* getType() const {
255 return m_login.getType();
260 ADFSConsumer m_login;
263 #if defined (_MSC_VER)
264 #pragma warning( pop )
267 SessionInitiator* ADFSSessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
269 return new ADFSSessionInitiator(p.first, p.second);
272 Handler* ADFSLogoutFactory(const pair<const DOMElement*,const char*>& p)
274 return new ADFSLogout(p.first, p.second);
277 Handler* ADFSLogoutInitiatorFactory(const pair<const DOMElement*,const char*>& p)
279 return new ADFSLogoutInitiator(p.first, p.second);
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);
286 extern "C" int ADFS_EXPORTS xmltooling_extension_init(void*)
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);
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());
301 extern "C" void ADFS_EXPORTS xmltooling_extension_term()
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);
310 SAMLConfig::getConfig().MessageDecoderManager.deregisterFactory(WSFED_NS);
315 pair<bool,long> ADFSSessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
317 // We have to know the IdP to function.
318 if (entityID.empty())
319 return make_pair(false,0L);
322 const Handler* ACS=NULL;
324 pair<bool,const char*> acClass;
325 const Application& app=request.getApplication();
328 option = request.getParameter("target");
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);
336 if (acClass.second = request.getParameter("authnContextClassRef"))
337 acClass.first = true;
339 acClass = getString("authnContextClassRef");
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();
346 const PropertySet* settings = request.getRequestSettings().first;
347 acClass = settings->getString("authnContextClassRef");
349 acClass = getString("authnContextClassRef");
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());
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);
359 option = request.getParameter("acsIndex");
361 index = pair<bool,unsigned int>(true, atoi(option));
364 index = getUnsignedInt("defaultACSIndex");
366 for (vector<const Handler*>::const_iterator h = handlers.begin(); !ACS && h!=handlers.end(); ++h) {
367 if (index.second == (*h)->getUnsignedInt("index").second)
371 else if (!handlers.empty()) {
372 ACS = handlers.front();
375 throw ConfigurationException("Unable to locate ADFS response endpoint.");
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;
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.
386 option = request.getParameter("target");
391 m_log.debug("attempting to initiate session using ADFS with provider (%s)", entityID.c_str());
393 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess))
394 return doRequest(app, request, entityID.c_str(), ACSloc.c_str(), (acClass.first ? acClass.second : NULL), target);
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());
403 in.addmember("RelayState").string(target.c_str());
405 in.addmember("authnContextClassRef").string(acClass.second);
407 // Remote the processing.
408 out = request.getServiceProvider().getListenerService()->send(in);
409 return unwrap(request, out);
412 void ADFSSessionInitiator::receive(DDF& in, ostream& out)
415 const char* aid=in["application_id"].string();
416 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
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?");
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.");
429 DDFJanitor jout(ret);
431 // Wrap the outgoing object with a Response facade.
432 auto_ptr<HTTPResponse> http(getResponse(ret));
434 string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");
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);
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,
453 // Use metadata to invoke the SSO service directly.
454 MetadataProvider* m=app.getMetadataProvider();
456 MetadataProvider::Criteria mc(entityID, &IDPSSODescriptor::ELEMENT_QNAME, m_binding.get());
457 pair<const EntityDescriptor*,const RoleDescriptor*> entity=m->getEntityDescriptor(mc);
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));
462 else if (!entity.second) {
463 m_log.warn("unable to locate ADFS-aware identity provider role for provider (%s)", entityID);
465 return make_pair(false,0L);
466 throw MetadataException("Unable to locate ADFS-aware identity provider role for provider ($entityID)", namedparams(1, "entityID", entityID));
468 const EndpointType* ep = EndpointManager<SingleSignOnService>(
469 dynamic_cast<const IDPSSODescriptor*>(entity.second)->getSingleSignOnServices()
470 ).getByBinding(m_binding.get());
472 m_log.warn("unable to locate compatible SSO service for provider (%s)", entityID);
474 return make_pair(false,0L);
475 throw MetadataException("Unable to locate compatible SSO service for provider ($entityID)", namedparams(1, "entityID", entityID));
478 preserveRelayState(app, httpResponse, relayState);
481 time_t epoch=time(NULL);
482 #ifndef HAVE_GMTIME_R
483 struct tm* ptime=gmtime(&epoch);
486 struct tm* ptime=gmtime_r(&epoch,&res);
489 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
491 auto_ptr_char dest(ep->getLocation());
492 const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
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());
501 return make_pair(true, httpResponse.sendRedirect(req.c_str()));
503 return make_pair(false,0L);
509 XMLObject* ADFSDecoder::decode(string& relayState, const GenericRequest& genericRequest, SecurityPolicy& policy) const
512 xmltooling::NDC ndc("decode");
514 Category& log = Category::getInstance(SHIBSP_LOGCAT".MessageDecoder.ADFS");
516 log.debug("validating input");
517 const HTTPRequest* httpRequest=dynamic_cast<const HTTPRequest*>(&genericRequest);
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");
529 param = httpRequest->getParameter("wresult");
531 throw BindingException("Request missing wresult parameter.");
533 log.debug("decoded ADFS response:\n%s", param);
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));
543 if (!XMLHelper::isNodeNamed(xmlObject->getDOM(), m_ns.get(), RequestSecurityTokenResponse))
544 throw BindingException("Decoded message was not of the appropriate type.");
546 if (!policy.getValidating())
547 SchemaValidators.validate(xmlObject.get());
549 // Skip policy step here, there's no security in the wrapper.
550 // policy.evaluate(*xmlObject.get(), &genericRequest);
552 return xmlObject.release();
555 void ADFSConsumer::implementProtocol(
556 const Application& application,
557 const HTTPRequest& httpRequest,
558 HTTPResponse& httpResponse,
559 SecurityPolicy& policy,
560 const PropertySet* settings,
561 const XMLObject& xmlObject
564 // Implementation of ADFS profile.
565 m_log.debug("processing message against ADFS Passive Requester profile");
567 // With ADFS, all the security comes from the assertion, which is two levels down in the message.
569 const ElementProxy* response = dynamic_cast<const ElementProxy*>(&xmlObject);
570 if (!response || !response->hasChildren())
571 throw FatalProfileException("Incoming message was not of the proper type or contains no security token.");
572 response = dynamic_cast<const ElementProxy*>(response->getUnknownXMLObjects().front());
573 if (!response || !response->hasChildren())
574 throw FatalProfileException("Token wrapper element did not contain a security token.");
575 const Assertion* token = dynamic_cast<const Assertion*>(response->getUnknownXMLObjects().front());
576 if (!token || !token->getSignature())
577 throw FatalProfileException("Incoming message did not contain a signed SAML assertion.");
579 // Extract message and issuer details from assertion.
580 extractMessageDetails(*token, m_protocol.get(), policy);
582 // Run the policy over the assertion. Handles replay, freshness, and
583 // signature verification, assuming the relevant rules are configured.
584 policy.evaluate(*token);
586 // If no security is in place now, we kick it.
587 if (!policy.isAuthenticated())
588 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
590 time_t now = time(NULL);
592 const PropertySet* sessionProps = application.getPropertySet("Sessions");
593 const EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL;
595 saml1::NameIdentifier* saml1name=NULL;
596 saml2::NameID* saml2name=NULL;
597 const XMLCh* authMethod=NULL;
598 const XMLCh* authInstant=NULL;
599 time_t sessionExp = 0;
601 const saml1::Assertion* saml1token = dynamic_cast<const saml1::Assertion*>(token);
603 // Now do profile and core semantic validation to ensure we can use it for SSO.
604 saml1::AssertionValidator ssoValidator(application.getRelyingParty(entity)->getXMLString("entityID").second, application.getAudiences(), now);
605 ssoValidator.validateAssertion(*saml1token);
606 if (!saml1token->getConditions() || !saml1token->getConditions()->getNotBefore() || !saml1token->getConditions()->getNotOnOrAfter())
607 throw FatalProfileException("Assertion did not contain time conditions.");
608 else if (saml1token->getAuthenticationStatements().empty())
609 throw FatalProfileException("Assertion did not contain an authentication statement.");
611 // authnskew allows rejection of SSO if AuthnInstant is too old.
612 pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);
614 const saml1::AuthenticationStatement* ssoStatement=saml1token->getAuthenticationStatements().front();
615 if (authnskew.first && authnskew.second &&
616 ssoStatement->getAuthenticationInstant() && (now - ssoStatement->getAuthenticationInstantEpoch() > authnskew.second))
617 throw FatalProfileException("The gap between now and the time you logged into your identity provider exceeds the limit.");
620 saml1::SubjectLocality* locality = ssoStatement->getSubjectLocality();
621 if (locality && locality->getIPAddress()) {
622 auto_ptr_char ip(locality->getIPAddress());
623 checkAddress(application, httpRequest, ip.get());
626 saml1name = ssoStatement->getSubject()->getNameIdentifier();
627 authMethod = ssoStatement->getAuthenticationMethod();
628 if (ssoStatement->getAuthenticationInstant())
629 authInstant = ssoStatement->getAuthenticationInstant()->getRawData();
631 // Session expiration.
632 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
633 if (!lifetime.first || lifetime.second == 0)
634 lifetime.second = 28800;
635 sessionExp = now + lifetime.second;
638 const saml2::Assertion* saml2token = dynamic_cast<const saml2::Assertion*>(token);
640 throw FatalProfileException("Incoming message did not contain a recognized type of SAML assertion.");
642 // Now do profile and core semantic validation to ensure we can use it for SSO.
643 saml2::AssertionValidator ssoValidator(application.getRelyingParty(entity)->getXMLString("entityID").second, application.getAudiences(), now);
644 ssoValidator.validateAssertion(*saml2token);
645 if (!saml2token->getConditions() || !saml2token->getConditions()->getNotBefore() || !saml2token->getConditions()->getNotOnOrAfter())
646 throw FatalProfileException("Assertion did not contain time conditions.");
647 else if (saml2token->getAuthnStatements().empty())
648 throw FatalProfileException("Assertion did not contain an authentication statement.");
650 // authnskew allows rejection of SSO if AuthnInstant is too old.
651 pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);
653 const saml2::AuthnStatement* ssoStatement=saml2token->getAuthnStatements().front();
654 if (authnskew.first && authnskew.second &&
655 ssoStatement->getAuthnInstant() && (now - ssoStatement->getAuthnInstantEpoch() > authnskew.second))
656 throw FatalProfileException("The gap between now and the time you logged into your identity provider exceeds the limit.");
659 saml2::SubjectLocality* locality = ssoStatement->getSubjectLocality();
660 if (locality && locality->getAddress()) {
661 auto_ptr_char ip(locality->getAddress());
662 checkAddress(application, httpRequest, ip.get());
665 saml2name = saml2token->getSubject() ? saml2token->getSubject()->getNameID() : NULL;
666 if (ssoStatement->getAuthnContext() && ssoStatement->getAuthnContext()->getAuthnContextClassRef())
667 authMethod = ssoStatement->getAuthnContext()->getAuthnContextClassRef()->getReference();
668 if (ssoStatement->getAuthnInstant())
669 authInstant = ssoStatement->getAuthnInstant()->getRawData();
671 // Session expiration for SAML 2.0 is jointly IdP- and SP-driven.
672 sessionExp = ssoStatement->getSessionNotOnOrAfter() ? ssoStatement->getSessionNotOnOrAfterEpoch() : 0;
673 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
674 if (!lifetime.first || lifetime.second == 0)
675 lifetime.second = 28800;
677 sessionExp = now + lifetime.second; // IdP says nothing, calulate based on SP.
679 sessionExp = min(sessionExp, now + lifetime.second); // Use the lowest.
682 m_log.debug("ADFS profile processing completed successfully");
684 // We've successfully "accepted" the SSO token.
685 // To complete processing, we need to extract and resolve attributes and then create the session.
687 // Normalize a SAML 1.x NameIdentifier...
688 auto_ptr<saml2::NameID> nameid(saml1name ? saml2::NameIDBuilder::buildNameID() : NULL);
690 nameid->setName(saml1name->getName());
691 nameid->setFormat(saml1name->getFormat());
692 nameid->setNameQualifier(saml1name->getNameQualifier());
695 // The context will handle deleting attributes and new tokens.
696 vector<const Assertion*> tokens(1,token);
697 auto_ptr<ResolutionContext> ctx(
700 policy.getIssuerMetadata(),
703 (saml1name ? nameid.get() : saml2name),
711 // Copy over any new tokens, but leave them in the context for cleanup.
712 tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
715 application.getServiceProvider().getSessionCache()->insert(
722 (saml1name ? nameid.get() : saml2name),
728 ctx.get() ? &ctx->getResolvedAttributes() : NULL
734 pair<bool,long> ADFSLogoutInitiator::run(SPRequest& request, bool isHandler) const
736 // Normally we'd do notifications and session clearage here, but ADFS logout
737 // is missing the needed request/response features, so we have to rely on
738 // the IdP half to notify us back about the logout and do the work there.
739 // Basically we have no way to tell in the Logout receiving handler whether
740 // we initiated the logout or not.
742 Session* session = NULL;
744 session = request.getSession(false, true, false); // don't cache it and ignore all checks
746 return make_pair(false,0L);
748 // We only handle ADFS sessions.
749 if (!XMLString::equals(session->getProtocol(), WSFED_NS) || !session->getEntityID()) {
751 return make_pair(false,0L);
754 catch (exception& ex) {
755 m_log.error("error accessing current session: %s", ex.what());
756 return make_pair(false,0L);
759 string entityID(session->getEntityID());
762 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
763 // When out of process, we run natively.
764 return doRequest(request.getApplication(), entityID.c_str(), request);
767 // When not out of process, we remote the request.
768 Locker locker(session, false);
769 DDF out,in(m_address.c_str());
770 DDFJanitor jin(in), jout(out);
771 in.addmember("application_id").string(request.getApplication().getId());
772 in.addmember("entity_id").string(entityID.c_str());
773 out=request.getServiceProvider().getListenerService()->send(in);
774 return unwrap(request, out);
778 void ADFSLogoutInitiator::receive(DDF& in, ostream& out)
782 const char* aid=in["application_id"].string();
783 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
785 // Something's horribly wrong.
786 m_log.error("couldn't find application (%s) for logout", aid ? aid : "(missing)");
787 throw ConfigurationException("Unable to locate application for logout, deleted?");
790 // Set up a response shim.
792 DDFJanitor jout(ret);
793 auto_ptr<HTTPResponse> resp(getResponse(ret));
795 // Since we're remoted, the result should either be a throw, which we pass on,
796 // a false/0 return, which we just return as an empty structure, or a response/redirect,
797 // which we capture in the facade and send back.
798 doRequest(*app, in["entity_id"].string(), *resp.get());
802 throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
806 pair<bool,long> ADFSLogoutInitiator::doRequest(const Application& application, const char* entityID, HTTPResponse& response) const
811 throw ConfigurationException("Missing entityID parameter.");
813 // With a session in hand, we can create a request message, if we can find a compatible endpoint.
814 MetadataProvider* m=application.getMetadataProvider();
816 MetadataProvider::Criteria mc(entityID, &IDPSSODescriptor::ELEMENT_QNAME, m_binding.get());
817 pair<const EntityDescriptor*,const RoleDescriptor*> entity=m->getEntityDescriptor(mc);
819 throw MetadataException("Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", entityID));
820 else if (!entity.second)
821 throw MetadataException("Unable to locate ADFS IdP role for identity provider ($entityID).", namedparams(1, "entityID", entityID));
823 const EndpointType* ep = EndpointManager<SingleLogoutService>(
824 dynamic_cast<const IDPSSODescriptor*>(entity.second)->getSingleLogoutServices()
825 ).getByBinding(m_binding.get());
827 throw MetadataException(
828 "Unable to locate ADFS single logout service for identity provider ($entityID).",
829 namedparams(1, "entityID", entityID)
833 auto_ptr_char dest(ep->getLocation());
835 string req=string(dest.get()) + (strchr(dest.get(),'?') ? '&' : '?') + "wa=wsignout1.0";
836 return make_pair(true,response.sendRedirect(req.c_str()));
838 catch (exception& ex) {
839 m_log.error("error issuing ADFS logout request: %s", ex.what());
842 return make_pair(false,0L);
844 throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
848 pair<bool,long> ADFSLogout::run(SPRequest& request, bool isHandler) const
850 // Defer to base class for front-channel loop first.
851 // This won't initiate the loop, only continue/end it.
852 pair<bool,long> ret = LogoutHandler::run(request, isHandler);
856 // wa parameter indicates the "action" to perform
857 bool returning = false;
858 const char* param = request.getParameter("wa");
860 if (!strcmp(param, "wsignin1.0"))
861 return m_login.run(request, isHandler);
862 else if (strcmp(param, "wsignout1.0") && strcmp(param, "wsignoutcleanup1.0"))
863 throw FatalProfileException("Unsupported WS-Federation action paremeter ($1).", params(1, param));
865 else if (strcmp(request.getMethod(),"GET") || !request.getParameter("notifying"))
866 throw FatalProfileException("Unsupported request to ADFS protocol endpoint.");
870 param = request.getParameter("wreply");
871 const Application& app = request.getApplication();
874 // Pass control to the first front channel notification point, if any.
875 map<string,string> parammap;
877 parammap["wreply"] = param;
878 pair<bool,long> result = notifyFrontChannel(app, request, request, ¶mmap);
883 // Best effort on back channel and to remove the user agent's session.
884 string session_id = app.getServiceProvider().getSessionCache()->active(app, request);
885 if (!session_id.empty()) {
886 vector<string> sessions(1,session_id);
887 notifyBackChannel(app, request.getRequestURL(), sessions, false);
889 app.getServiceProvider().getSessionCache()->remove(app, request, &request);
891 catch (exception& ex) {
892 m_log.error("error removing session (%s): %s", session_id.c_str(), ex.what());
897 return make_pair(true, request.sendRedirect(param));
898 return sendLogoutPage(app, request, request, false, "Logout complete.");