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 <saml/SAMLConfig.h>
57 # include <saml/saml1/core/Assertions.h>
58 # include <saml/saml1/profile/AssertionValidator.h>
59 # include <saml/saml2/core/Assertions.h>
60 # include <saml/saml2/metadata/Metadata.h>
61 # include <saml/saml2/metadata/EndpointManager.h>
62 # include <saml/saml2/profile/AssertionValidator.h>
63 # include <xmltooling/impl/AnyElement.h>
64 # include <xmltooling/validation/ValidatorSuite.h>
65 using namespace opensaml::saml2md;
67 # define min(a,b) (((a) < (b)) ? (a) : (b))
70 using namespace shibsp;
71 using namespace opensaml;
72 using namespace xmltooling::logging;
73 using namespace xmltooling;
74 using namespace xercesc;
77 #define WSFED_NS "http://schemas.xmlsoap.org/ws/2003/07/secext"
78 #define WSTRUST_NS "http://schemas.xmlsoap.org/ws/2005/02/trust"
83 class SHIBSP_DLLLOCAL ADFSDecoder : public MessageDecoder
87 ADFSDecoder() : m_ns(WSTRUST_NS) {}
88 virtual ~ADFSDecoder() {}
90 XMLObject* decode(string& relayState, const GenericRequest& genericRequest, SecurityPolicy& policy) const;
93 void extractMessageDetails(
94 const XMLObject& message, const GenericRequest& req, const XMLCh* protocol, SecurityPolicy& policy
99 MessageDecoder* ADFSDecoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
101 return new ADFSDecoder();
105 #if defined (_MSC_VER)
106 #pragma warning( push )
107 #pragma warning( disable : 4250 )
110 class SHIBSP_DLLLOCAL ADFSSessionInitiator : public SessionInitiator, public AbstractHandler, public RemotedHandler
113 ADFSSessionInitiator(const DOMElement* e, const char* appId)
114 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator.ADFS")), m_appId(appId), m_binding(WSFED_NS) {
115 // If Location isn't set, defer address registration until the setParent call.
116 pair<bool,const char*> loc = getString("Location");
118 string address = m_appId + loc.second + "::run::ADFSSI";
119 setAddress(address.c_str());
122 virtual ~ADFSSessionInitiator() {}
124 void setParent(const PropertySet* parent) {
125 DOMPropertySet::setParent(parent);
126 pair<bool,const char*> loc = getString("Location");
128 string address = m_appId + loc.second + "::run::ADFSSI";
129 setAddress(address.c_str());
132 m_log.warn("no Location property in ADFS SessionInitiator (or parent), can't register as remoted handler");
136 void receive(DDF& in, ostream& out);
137 pair<bool,long> run(SPRequest& request, string& entityID, bool isHandler=true) const;
140 pair<bool,long> doRequest(
141 const Application& application,
142 HTTPResponse& httpResponse,
143 const char* entityID,
144 const char* acsLocation,
145 const char* authnContextClassRef,
149 auto_ptr_XMLCh m_binding;
152 class SHIBSP_DLLLOCAL ADFSConsumer : public shibsp::AssertionConsumerService
155 ADFSConsumer(const DOMElement* e, const char* appId)
156 : shibsp::AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SSO.ADFS"))
158 ,m_protocol(WSFED_NS)
161 virtual ~ADFSConsumer() {}
164 void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
165 AssertionConsumerService::generateMetadata(role, handlerURL);
166 role.addSupport(m_protocol.get());
169 auto_ptr_XMLCh m_protocol;
172 void implementProtocol(
173 const Application& application,
174 const HTTPRequest& httpRequest,
175 HTTPResponse& httpResponse,
176 SecurityPolicy& policy,
177 const PropertySet* settings,
178 const XMLObject& xmlObject
183 class SHIBSP_DLLLOCAL ADFSLogoutInitiator : public AbstractHandler, public LogoutHandler
186 ADFSLogoutInitiator(const DOMElement* e, const char* appId)
187 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".LogoutInitiator.ADFS")), m_appId(appId), m_binding(WSFED_NS) {
188 // If Location isn't set, defer address registration until the setParent call.
189 pair<bool,const char*> loc = getString("Location");
191 string address = m_appId + loc.second + "::run::ADFSLI";
192 setAddress(address.c_str());
195 virtual ~ADFSLogoutInitiator() {}
197 void setParent(const PropertySet* parent) {
198 DOMPropertySet::setParent(parent);
199 pair<bool,const char*> loc = getString("Location");
201 string address = m_appId + loc.second + "::run::ADFSLI";
202 setAddress(address.c_str());
205 m_log.warn("no Location property in ADFS LogoutInitiator (or parent), can't register as remoted handler");
209 void receive(DDF& in, ostream& out);
210 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
213 const char* getType() const {
214 return "LogoutInitiator";
219 pair<bool,long> doRequest(const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse, Session* session) const;
222 auto_ptr_XMLCh m_binding;
225 class SHIBSP_DLLLOCAL ADFSLogout : public AbstractHandler, public LogoutHandler
228 ADFSLogout(const DOMElement* e, const char* appId)
229 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".Logout.ADFS")), m_login(e, appId) {
232 m_preserve.push_back("wreply");
233 string address = string(appId) + getString("Location").second + "::run::ADFSLO";
234 setAddress(address.c_str());
237 virtual ~ADFSLogout() {}
239 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
242 void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
243 m_login.generateMetadata(role, handlerURL);
244 const char* loc = getString("Location").second;
245 string hurl(handlerURL);
249 auto_ptr_XMLCh widen(hurl.c_str());
250 SingleLogoutService* ep = SingleLogoutServiceBuilder::buildSingleLogoutService();
251 ep->setLocation(widen.get());
252 ep->setBinding(m_login.m_protocol.get());
253 role.getSingleLogoutServices().push_back(ep);
256 const char* getType() const {
257 return m_login.getType();
262 ADFSConsumer m_login;
265 #if defined (_MSC_VER)
266 #pragma warning( pop )
269 SessionInitiator* ADFSSessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
271 return new ADFSSessionInitiator(p.first, p.second);
274 Handler* ADFSLogoutFactory(const pair<const DOMElement*,const char*>& p)
276 return new ADFSLogout(p.first, p.second);
279 Handler* ADFSLogoutInitiatorFactory(const pair<const DOMElement*,const char*>& p)
281 return new ADFSLogoutInitiator(p.first, p.second);
284 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);
285 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);
288 extern "C" int ADFS_EXPORTS xmltooling_extension_init(void*)
290 SPConfig& conf=SPConfig::getConfig();
291 conf.SessionInitiatorManager.registerFactory("ADFS", ADFSSessionInitiatorFactory);
292 conf.LogoutInitiatorManager.registerFactory("ADFS", ADFSLogoutInitiatorFactory);
293 conf.AssertionConsumerServiceManager.registerFactory("ADFS", ADFSLogoutFactory);
294 conf.AssertionConsumerServiceManager.registerFactory(WSFED_NS, ADFSLogoutFactory);
296 SAMLConfig::getConfig().MessageDecoderManager.registerFactory(WSFED_NS, ADFSDecoderFactory);
297 XMLObjectBuilder::registerBuilder(QName(WSTRUST_NS,"RequestedSecurityToken"), new AnyElementBuilder());
298 XMLObjectBuilder::registerBuilder(QName(WSTRUST_NS,"RequestSecurityTokenResponse"), new AnyElementBuilder());
303 extern "C" void ADFS_EXPORTS xmltooling_extension_term()
305 /* should get unregistered during normal shutdown...
306 SPConfig& conf=SPConfig::getConfig();
307 conf.SessionInitiatorManager.deregisterFactory("ADFS");
308 conf.LogoutInitiatorManager.deregisterFactory("ADFS");
309 conf.AssertionConsumerServiceManager.deregisterFactory("ADFS");
310 conf.AssertionConsumerServiceManager.deregisterFactory(WSFED_NS);
312 SAMLConfig::getConfig().MessageDecoderManager.deregisterFactory(WSFED_NS);
317 pair<bool,long> ADFSSessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
319 // We have to know the IdP to function.
320 if (entityID.empty())
321 return make_pair(false,0L);
324 const Handler* ACS=NULL;
326 pair<bool,const char*> acClass;
327 const Application& app=request.getApplication();
330 option = request.getParameter("target");
334 // Since we're passing the ACS by value, we need to compute the return URL,
335 // so we'll need the target resource for real.
336 recoverRelayState(request.getApplication(), request, request, target, false);
338 if (acClass.second = request.getParameter("authnContextClassRef"))
339 acClass.first = true;
341 acClass = getString("authnContextClassRef");
344 // We're running as a "virtual handler" from within the filter.
345 // The target resource is the current one and everything else is defaulted.
346 target=request.getRequestURL();
348 const PropertySet* settings = request.getRequestSettings().first;
349 acClass = settings->getString("authnContextClassRef");
351 acClass = getString("authnContextClassRef");
354 // Since we're not passing by index, we need to fully compute the return URL.
355 // Get all the ADFS endpoints.
356 const vector<const Handler*>& handlers = app.getAssertionConsumerServicesByBinding(m_binding.get());
358 // Index comes from request, or default set in the handler, or we just pick the first endpoint.
359 pair<bool,unsigned int> index(false,0);
361 option = request.getParameter("acsIndex");
363 index = pair<bool,unsigned int>(true, atoi(option));
366 index = getUnsignedInt("defaultACSIndex");
368 for (vector<const Handler*>::const_iterator h = handlers.begin(); !ACS && h!=handlers.end(); ++h) {
369 if (index.second == (*h)->getUnsignedInt("index").second)
373 else if (!handlers.empty()) {
374 ACS = handlers.front();
377 throw ConfigurationException("Unable to locate ADFS response endpoint.");
379 // Compute the ACS URL. We add the ACS location to the base handlerURL.
380 string ACSloc=request.getHandlerURL(target.c_str());
381 pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
382 if (loc.first) ACSloc+=loc.second;
385 // We may already have RelayState set if we looped back here,
386 // but just in case target is a resource, we reset it back.
388 option = request.getParameter("target");
393 m_log.debug("attempting to initiate session using ADFS with provider (%s)", entityID.c_str());
395 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess))
396 return doRequest(app, request, entityID.c_str(), ACSloc.c_str(), (acClass.first ? acClass.second : NULL), target);
399 DDF out,in = DDF(m_address.c_str()).structure();
400 DDFJanitor jin(in), jout(out);
401 in.addmember("application_id").string(app.getId());
402 in.addmember("entity_id").string(entityID.c_str());
403 in.addmember("acsLocation").string(ACSloc.c_str());
405 in.addmember("RelayState").string(target.c_str());
407 in.addmember("authnContextClassRef").string(acClass.second);
409 // Remote the processing.
410 out = request.getServiceProvider().getListenerService()->send(in);
411 return unwrap(request, out);
414 void ADFSSessionInitiator::receive(DDF& in, ostream& out)
417 const char* aid=in["application_id"].string();
418 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
420 // Something's horribly wrong.
421 m_log.error("couldn't find application (%s) to generate ADFS request", aid ? aid : "(missing)");
422 throw ConfigurationException("Unable to locate application for new session, deleted?");
425 const char* entityID = in["entity_id"].string();
426 const char* acsLocation = in["acsLocation"].string();
427 if (!entityID || !acsLocation)
428 throw ConfigurationException("No entityID or acsLocation parameter supplied to remoted SessionInitiator.");
431 DDFJanitor jout(ret);
433 // Wrap the outgoing object with a Response facade.
434 auto_ptr<HTTPResponse> http(getResponse(ret));
436 string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");
438 // Since we're remoted, the result should either be a throw, which we pass on,
439 // a false/0 return, which we just return as an empty structure, or a response/redirect,
440 // which we capture in the facade and send back.
441 doRequest(*app, *http.get(), entityID, acsLocation, in["authnContextClassRef"].string(), relayState);
445 pair<bool,long> ADFSSessionInitiator::doRequest(
446 const Application& app,
447 HTTPResponse& httpResponse,
448 const char* entityID,
449 const char* acsLocation,
450 const char* authnContextClassRef,
455 // Use metadata to invoke the SSO service directly.
456 MetadataProvider* m=app.getMetadataProvider();
458 MetadataProvider::Criteria mc(entityID, &IDPSSODescriptor::ELEMENT_QNAME, m_binding.get());
459 pair<const EntityDescriptor*,const RoleDescriptor*> entity=m->getEntityDescriptor(mc);
461 m_log.warn("unable to locate metadata for provider (%s)", entityID);
462 throw MetadataException("Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", entityID));
464 else if (!entity.second) {
465 m_log.warn("unable to locate ADFS-aware identity provider role for provider (%s)", entityID);
467 return make_pair(false,0L);
468 throw MetadataException("Unable to locate ADFS-aware identity provider role for provider ($entityID)", namedparams(1, "entityID", entityID));
470 const EndpointType* ep = EndpointManager<SingleSignOnService>(
471 dynamic_cast<const IDPSSODescriptor*>(entity.second)->getSingleSignOnServices()
472 ).getByBinding(m_binding.get());
474 m_log.warn("unable to locate compatible SSO service for provider (%s)", entityID);
476 return make_pair(false,0L);
477 throw MetadataException("Unable to locate compatible SSO service for provider ($entityID)", namedparams(1, "entityID", entityID));
480 preserveRelayState(app, httpResponse, relayState);
483 time_t epoch=time(NULL);
484 #ifndef HAVE_GMTIME_R
485 struct tm* ptime=gmtime(&epoch);
488 struct tm* ptime=gmtime_r(&epoch,&res);
491 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
493 auto_ptr_char dest(ep->getLocation());
494 const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
496 string req=string(dest.get()) + (strchr(dest.get(),'?') ? '&' : '?') + "wa=wsignin1.0&wreply=" + urlenc->encode(acsLocation) +
497 "&wct=" + urlenc->encode(timebuf) + "&wtrealm=" + urlenc->encode(app.getString("entityID").second);
498 if (authnContextClassRef)
499 req += "&wauth=" + urlenc->encode(authnContextClassRef);
500 if (!relayState.empty())
501 req += "&wctx=" + urlenc->encode(relayState.c_str());
503 return make_pair(true, httpResponse.sendRedirect(req.c_str()));
505 return make_pair(false,0L);
511 XMLObject* ADFSDecoder::decode(string& relayState, const GenericRequest& genericRequest, SecurityPolicy& policy) const
514 xmltooling::NDC ndc("decode");
516 Category& log = Category::getInstance(SHIBSP_LOGCAT".MessageDecoder.ADFS");
518 log.debug("validating input");
519 const HTTPRequest* httpRequest=dynamic_cast<const HTTPRequest*>(&genericRequest);
521 throw BindingException("Unable to cast request object to HTTPRequest type.");
522 if (strcmp(httpRequest->getMethod(),"POST"))
523 throw BindingException("Invalid HTTP method ($1).", params(1, httpRequest->getMethod()));
524 const char* param = httpRequest->getParameter("wa");
525 if (!param || strcmp(param, "wsignin1.0"))
526 throw BindingException("Missing or invalid wa parameter (should be wsignin1.0).");
527 param = httpRequest->getParameter("wctx");
531 param = httpRequest->getParameter("wresult");
533 throw BindingException("Request missing wresult parameter.");
535 log.debug("decoded ADFS response:\n%s", param);
537 // Parse and bind the document into an XMLObject.
538 istringstream is(param);
539 DOMDocument* doc = (policy.getValidating() ? XMLToolingConfig::getConfig().getValidatingParser()
540 : XMLToolingConfig::getConfig().getParser()).parse(is);
541 XercesJanitor<DOMDocument> janitor(doc);
542 auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
545 if (!XMLString::equals(xmlObject->getElementQName().getLocalPart(), RequestSecurityTokenResponse)) {
546 log.error("unrecognized root element on message: %s", xmlObject->getElementQName().toString().c_str());
547 throw BindingException("Decoded message was not of the appropriate type.");
550 if (!policy.getValidating())
551 SchemaValidators.validate(xmlObject.get());
553 // Skip policy step here, there's no security in the wrapper.
554 // policy.evaluate(*xmlObject.get(), &genericRequest);
556 return xmlObject.release();
559 void ADFSConsumer::implementProtocol(
560 const Application& application,
561 const HTTPRequest& httpRequest,
562 HTTPResponse& httpResponse,
563 SecurityPolicy& policy,
564 const PropertySet* settings,
565 const XMLObject& xmlObject
568 // Implementation of ADFS profile.
569 m_log.debug("processing message against ADFS Passive Requester profile");
571 // With ADFS, all the security comes from the assertion, which is two levels down in the message.
573 const ElementProxy* response = dynamic_cast<const ElementProxy*>(&xmlObject);
574 if (!response || !response->hasChildren())
575 throw FatalProfileException("Incoming message was not of the proper type or contains no security token.");
577 const Assertion* token = NULL;
578 for (vector<XMLObject*>::const_iterator xo = response->getUnknownXMLObjects().begin(); xo != response->getUnknownXMLObjects().end(); ++xo) {
579 // Look for the RequestedSecurityToken element.
580 if (XMLString::equals((*xo)->getElementQName().getLocalPart(), RequestedSecurityToken)) {
581 response = dynamic_cast<const ElementProxy*>(*xo);
582 if (!response || !response->hasChildren())
583 throw FatalProfileException("Token wrapper element did not contain a security token.");
584 token = dynamic_cast<const Assertion*>(response->getUnknownXMLObjects().front());
585 if (!token || !token->getSignature())
586 throw FatalProfileException("Incoming message did not contain a signed SAML assertion.");
591 // Extract message and issuer details from assertion.
592 extractMessageDetails(*token, m_protocol.get(), policy);
594 // Run the policy over the assertion. Handles replay, freshness, and
595 // signature verification, assuming the relevant rules are configured.
596 policy.evaluate(*token);
598 // If no security is in place now, we kick it.
599 if (!policy.isAuthenticated())
600 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
602 time_t now = time(NULL);
604 const PropertySet* sessionProps = application.getPropertySet("Sessions");
605 const EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL;
607 saml1::NameIdentifier* saml1name=NULL;
608 saml2::NameID* saml2name=NULL;
609 const XMLCh* authMethod=NULL;
610 const XMLCh* authInstant=NULL;
611 time_t sessionExp = 0;
613 const saml1::Assertion* saml1token = dynamic_cast<const saml1::Assertion*>(token);
615 // Now do profile and core semantic validation to ensure we can use it for SSO.
616 saml1::AssertionValidator ssoValidator(application.getRelyingParty(entity)->getXMLString("entityID").second, application.getAudiences(), now);
617 ssoValidator.validateAssertion(*saml1token);
618 if (!saml1token->getConditions() || !saml1token->getConditions()->getNotBefore() || !saml1token->getConditions()->getNotOnOrAfter())
619 throw FatalProfileException("Assertion did not contain time conditions.");
620 else if (saml1token->getAuthenticationStatements().empty())
621 throw FatalProfileException("Assertion did not contain an authentication statement.");
623 // authnskew allows rejection of SSO if AuthnInstant is too old.
624 pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);
626 const saml1::AuthenticationStatement* ssoStatement=saml1token->getAuthenticationStatements().front();
627 if (authnskew.first && authnskew.second &&
628 ssoStatement->getAuthenticationInstant() && (now - ssoStatement->getAuthenticationInstantEpoch() > authnskew.second))
629 throw FatalProfileException("The gap between now and the time you logged into your identity provider exceeds the limit.");
632 saml1::SubjectLocality* locality = ssoStatement->getSubjectLocality();
633 if (locality && locality->getIPAddress()) {
634 auto_ptr_char ip(locality->getIPAddress());
635 checkAddress(application, httpRequest, ip.get());
638 saml1name = ssoStatement->getSubject()->getNameIdentifier();
639 authMethod = ssoStatement->getAuthenticationMethod();
640 if (ssoStatement->getAuthenticationInstant())
641 authInstant = ssoStatement->getAuthenticationInstant()->getRawData();
643 // Session expiration.
644 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
645 if (!lifetime.first || lifetime.second == 0)
646 lifetime.second = 28800;
647 sessionExp = now + lifetime.second;
650 const saml2::Assertion* saml2token = dynamic_cast<const saml2::Assertion*>(token);
652 throw FatalProfileException("Incoming message did not contain a recognized type of SAML assertion.");
654 // Now do profile and core semantic validation to ensure we can use it for SSO.
655 saml2::AssertionValidator ssoValidator(application.getRelyingParty(entity)->getXMLString("entityID").second, application.getAudiences(), now);
656 ssoValidator.validateAssertion(*saml2token);
657 if (!saml2token->getConditions() || !saml2token->getConditions()->getNotBefore() || !saml2token->getConditions()->getNotOnOrAfter())
658 throw FatalProfileException("Assertion did not contain time conditions.");
659 else if (saml2token->getAuthnStatements().empty())
660 throw FatalProfileException("Assertion did not contain an authentication statement.");
662 // authnskew allows rejection of SSO if AuthnInstant is too old.
663 pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);
665 const saml2::AuthnStatement* ssoStatement=saml2token->getAuthnStatements().front();
666 if (authnskew.first && authnskew.second &&
667 ssoStatement->getAuthnInstant() && (now - ssoStatement->getAuthnInstantEpoch() > authnskew.second))
668 throw FatalProfileException("The gap between now and the time you logged into your identity provider exceeds the limit.");
671 saml2::SubjectLocality* locality = ssoStatement->getSubjectLocality();
672 if (locality && locality->getAddress()) {
673 auto_ptr_char ip(locality->getAddress());
674 checkAddress(application, httpRequest, ip.get());
677 saml2name = saml2token->getSubject() ? saml2token->getSubject()->getNameID() : NULL;
678 if (ssoStatement->getAuthnContext() && ssoStatement->getAuthnContext()->getAuthnContextClassRef())
679 authMethod = ssoStatement->getAuthnContext()->getAuthnContextClassRef()->getReference();
680 if (ssoStatement->getAuthnInstant())
681 authInstant = ssoStatement->getAuthnInstant()->getRawData();
683 // Session expiration for SAML 2.0 is jointly IdP- and SP-driven.
684 sessionExp = ssoStatement->getSessionNotOnOrAfter() ? ssoStatement->getSessionNotOnOrAfterEpoch() : 0;
685 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
686 if (!lifetime.first || lifetime.second == 0)
687 lifetime.second = 28800;
689 sessionExp = now + lifetime.second; // IdP says nothing, calulate based on SP.
691 sessionExp = min(sessionExp, now + lifetime.second); // Use the lowest.
694 m_log.debug("ADFS profile processing completed successfully");
696 // We've successfully "accepted" the SSO token.
697 // To complete processing, we need to extract and resolve attributes and then create the session.
699 // Normalize a SAML 1.x NameIdentifier...
700 auto_ptr<saml2::NameID> nameid(saml1name ? saml2::NameIDBuilder::buildNameID() : NULL);
702 nameid->setName(saml1name->getName());
703 nameid->setFormat(saml1name->getFormat());
704 nameid->setNameQualifier(saml1name->getNameQualifier());
707 // The context will handle deleting attributes and new tokens.
708 vector<const Assertion*> tokens(1,token);
709 auto_ptr<ResolutionContext> ctx(
712 policy.getIssuerMetadata(),
715 (saml1name ? nameid.get() : saml2name),
723 // Copy over any new tokens, but leave them in the context for cleanup.
724 tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
727 application.getServiceProvider().getSessionCache()->insert(
734 (saml1name ? nameid.get() : saml2name),
740 ctx.get() ? &ctx->getResolvedAttributes() : NULL
746 pair<bool,long> ADFSLogoutInitiator::run(SPRequest& request, bool isHandler) const
748 // Normally we'd do notifications and session clearage here, but ADFS logout
749 // is missing the needed request/response features, so we have to rely on
750 // the IdP half to notify us back about the logout and do the work there.
751 // Basically we have no way to tell in the Logout receiving handler whether
752 // we initiated the logout or not.
754 Session* session = NULL;
756 session = request.getSession(false, true, false); // don't cache it and ignore all checks
758 return make_pair(false,0L);
760 // We only handle ADFS sessions.
761 if (!XMLString::equals(session->getProtocol(), WSFED_NS) || !session->getEntityID()) {
763 return make_pair(false,0L);
766 catch (exception& ex) {
767 m_log.error("error accessing current session: %s", ex.what());
768 return make_pair(false,0L);
771 string entityID(session->getEntityID());
774 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
775 // When out of process, we run natively.
776 return doRequest(request.getApplication(), request, request, session);
779 // When not out of process, we remote the request.
781 vector<string> headers(1,"Cookie");
782 DDF out,in = wrap(request,&headers);
783 DDFJanitor jin(in), jout(out);
784 out=request.getServiceProvider().getListenerService()->send(in);
785 return unwrap(request, out);
789 void ADFSLogoutInitiator::receive(DDF& in, ostream& out)
792 // Defer to base class for notifications
793 if (in["notify"].integer() == 1)
794 return LogoutHandler::receive(in, out);
797 const char* aid=in["application_id"].string();
798 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
800 // Something's horribly wrong.
801 m_log.error("couldn't find application (%s) for logout", aid ? aid : "(missing)");
802 throw ConfigurationException("Unable to locate application for logout, deleted?");
805 // Unpack the request.
806 auto_ptr<HTTPRequest> req(getRequest(in));
808 // Set up a response shim.
810 DDFJanitor jout(ret);
811 auto_ptr<HTTPResponse> resp(getResponse(ret));
813 Session* session = NULL;
815 session = app->getServiceProvider().getSessionCache()->find(*app, *req.get(), NULL, NULL);
817 catch (exception& ex) {
818 m_log.error("error accessing current session: %s", ex.what());
821 // With no session, we just skip the request and let it fall through to an empty struct return.
823 if (session->getEntityID()) {
824 // Since we're remoted, the result should either be a throw, which we pass on,
825 // a false/0 return, which we just return as an empty structure, or a response/redirect,
826 // which we capture in the facade and send back.
827 doRequest(*app, *req.get(), *resp.get(), session);
830 m_log.error("no issuing entityID found in session");
832 app->getServiceProvider().getSessionCache()->remove(*app, *req.get(), resp.get());
837 throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
841 pair<bool,long> ADFSLogoutInitiator::doRequest(
842 const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse, Session* session
845 // Do back channel notification.
846 vector<string> sessions(1, session->getID());
847 if (!notifyBackChannel(application, httpRequest.getRequestURL(), sessions, false)) {
849 application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
850 return sendLogoutPage(application, httpRequest, httpResponse, true, "Partial logout failure.");
854 pair<bool,long> ret = make_pair(false,0L);
857 // With a session in hand, we can create a request message, if we can find a compatible endpoint.
858 MetadataProvider* m=application.getMetadataProvider();
859 Locker metadataLocker(m);
860 MetadataProvider::Criteria mc(session->getEntityID(), &IDPSSODescriptor::ELEMENT_QNAME, m_binding.get());
861 pair<const EntityDescriptor*,const RoleDescriptor*> entity=m->getEntityDescriptor(mc);
863 throw MetadataException(
864 "Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", session->getEntityID())
867 else if (!entity.second) {
868 throw MetadataException(
869 "Unable to locate ADFS IdP role for identity provider ($entityID).", namedparams(1, "entityID", session->getEntityID())
873 const EndpointType* ep = EndpointManager<SingleLogoutService>(
874 dynamic_cast<const IDPSSODescriptor*>(entity.second)->getSingleLogoutServices()
875 ).getByBinding(m_binding.get());
877 throw MetadataException(
878 "Unable to locate ADFS single logout service for identity provider ($entityID).", namedparams(1, "entityID", session->getEntityID())
882 const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
883 const char* returnloc = httpRequest.getParameter("return");
884 auto_ptr_char dest(ep->getLocation());
885 string req=string(dest.get()) + (strchr(dest.get(),'?') ? '&' : '?') + "wa=wsignout1.0";
887 req += "&wreply=" + urlenc->encode(returnloc);
888 ret.second = httpResponse.sendRedirect(req.c_str());
891 catch (exception& ex) {
892 m_log.error("error issuing ADFS logout request: %s", ex.what());
898 application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
903 throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
907 pair<bool,long> ADFSLogout::run(SPRequest& request, bool isHandler) const
909 // Defer to base class for front-channel loop first.
910 // This won't initiate the loop, only continue/end it.
911 pair<bool,long> ret = LogoutHandler::run(request, isHandler);
915 // wa parameter indicates the "action" to perform
916 bool returning = false;
917 const char* param = request.getParameter("wa");
919 if (!strcmp(param, "wsignin1.0"))
920 return m_login.run(request, isHandler);
921 else if (strcmp(param, "wsignout1.0") && strcmp(param, "wsignoutcleanup1.0"))
922 throw FatalProfileException("Unsupported WS-Federation action paremeter ($1).", params(1, param));
924 else if (strcmp(request.getMethod(),"GET") || !request.getParameter("notifying"))
925 throw FatalProfileException("Unsupported request to ADFS protocol endpoint.");
929 param = request.getParameter("wreply");
930 const Application& app = request.getApplication();
933 // Pass control to the first front channel notification point, if any.
934 map<string,string> parammap;
936 parammap["wreply"] = param;
937 pair<bool,long> result = notifyFrontChannel(app, request, request, ¶mmap);
942 // Best effort on back channel and to remove the user agent's session.
943 string session_id = app.getServiceProvider().getSessionCache()->active(app, request);
944 if (!session_id.empty()) {
945 vector<string> sessions(1,session_id);
946 notifyBackChannel(app, request.getRequestURL(), sessions, false);
948 app.getServiceProvider().getSessionCache()->remove(app, request, &request);
950 catch (exception& ex) {
951 m_log.error("error removing session (%s): %s", session_id.c_str(), ex.what());
956 return make_pair(true, request.sendRedirect(param));
957 return sendLogoutPage(app, request, request, false, "Logout complete.");