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 (!XMLString::equals(xmlObject->getElementQName().getLocalPart(), RequestSecurityTokenResponse)) {
544 log.error("unrecognized root element on message: %s", xmlObject->getElementQName().toString().c_str());
545 throw BindingException("Decoded message was not of the appropriate type.");
548 if (!policy.getValidating())
549 SchemaValidators.validate(xmlObject.get());
551 // Skip policy step here, there's no security in the wrapper.
552 // policy.evaluate(*xmlObject.get(), &genericRequest);
554 return xmlObject.release();
557 void ADFSConsumer::implementProtocol(
558 const Application& application,
559 const HTTPRequest& httpRequest,
560 HTTPResponse& httpResponse,
561 SecurityPolicy& policy,
562 const PropertySet* settings,
563 const XMLObject& xmlObject
566 // Implementation of ADFS profile.
567 m_log.debug("processing message against ADFS Passive Requester profile");
569 // With ADFS, all the security comes from the assertion, which is two levels down in the message.
571 const ElementProxy* response = dynamic_cast<const ElementProxy*>(&xmlObject);
572 if (!response || !response->hasChildren())
573 throw FatalProfileException("Incoming message was not of the proper type or contains no security token.");
575 const Assertion* token = NULL;
576 for (vector<XMLObject*>::const_iterator xo = response->getUnknownXMLObjects().begin(); xo != response->getUnknownXMLObjects().end(); ++xo) {
577 // Look for the RequestedSecurityToken element.
578 if (XMLString::equals((*xo)->getElementQName().getLocalPart(), RequestedSecurityToken)) {
579 response = dynamic_cast<const ElementProxy*>(*xo);
580 if (!response || !response->hasChildren())
581 throw FatalProfileException("Token wrapper element did not contain a security token.");
582 token = dynamic_cast<const Assertion*>(response->getUnknownXMLObjects().front());
583 if (!token || !token->getSignature())
584 throw FatalProfileException("Incoming message did not contain a signed SAML assertion.");
589 // Extract message and issuer details from assertion.
590 extractMessageDetails(*token, m_protocol.get(), policy);
592 // Run the policy over the assertion. Handles replay, freshness, and
593 // signature verification, assuming the relevant rules are configured.
594 policy.evaluate(*token);
596 // If no security is in place now, we kick it.
597 if (!policy.isAuthenticated())
598 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
600 time_t now = time(NULL);
602 const PropertySet* sessionProps = application.getPropertySet("Sessions");
603 const EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL;
605 saml1::NameIdentifier* saml1name=NULL;
606 saml2::NameID* saml2name=NULL;
607 const XMLCh* authMethod=NULL;
608 const XMLCh* authInstant=NULL;
609 time_t sessionExp = 0;
611 const saml1::Assertion* saml1token = dynamic_cast<const saml1::Assertion*>(token);
613 // Now do profile and core semantic validation to ensure we can use it for SSO.
614 saml1::AssertionValidator ssoValidator(application.getRelyingParty(entity)->getXMLString("entityID").second, application.getAudiences(), now);
615 ssoValidator.validateAssertion(*saml1token);
616 if (!saml1token->getConditions() || !saml1token->getConditions()->getNotBefore() || !saml1token->getConditions()->getNotOnOrAfter())
617 throw FatalProfileException("Assertion did not contain time conditions.");
618 else if (saml1token->getAuthenticationStatements().empty())
619 throw FatalProfileException("Assertion did not contain an authentication statement.");
621 // authnskew allows rejection of SSO if AuthnInstant is too old.
622 pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);
624 const saml1::AuthenticationStatement* ssoStatement=saml1token->getAuthenticationStatements().front();
625 if (authnskew.first && authnskew.second &&
626 ssoStatement->getAuthenticationInstant() && (now - ssoStatement->getAuthenticationInstantEpoch() > authnskew.second))
627 throw FatalProfileException("The gap between now and the time you logged into your identity provider exceeds the limit.");
630 saml1::SubjectLocality* locality = ssoStatement->getSubjectLocality();
631 if (locality && locality->getIPAddress()) {
632 auto_ptr_char ip(locality->getIPAddress());
633 checkAddress(application, httpRequest, ip.get());
636 saml1name = ssoStatement->getSubject()->getNameIdentifier();
637 authMethod = ssoStatement->getAuthenticationMethod();
638 if (ssoStatement->getAuthenticationInstant())
639 authInstant = ssoStatement->getAuthenticationInstant()->getRawData();
641 // Session expiration.
642 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
643 if (!lifetime.first || lifetime.second == 0)
644 lifetime.second = 28800;
645 sessionExp = now + lifetime.second;
648 const saml2::Assertion* saml2token = dynamic_cast<const saml2::Assertion*>(token);
650 throw FatalProfileException("Incoming message did not contain a recognized type of SAML assertion.");
652 // Now do profile and core semantic validation to ensure we can use it for SSO.
653 saml2::AssertionValidator ssoValidator(application.getRelyingParty(entity)->getXMLString("entityID").second, application.getAudiences(), now);
654 ssoValidator.validateAssertion(*saml2token);
655 if (!saml2token->getConditions() || !saml2token->getConditions()->getNotBefore() || !saml2token->getConditions()->getNotOnOrAfter())
656 throw FatalProfileException("Assertion did not contain time conditions.");
657 else if (saml2token->getAuthnStatements().empty())
658 throw FatalProfileException("Assertion did not contain an authentication statement.");
660 // authnskew allows rejection of SSO if AuthnInstant is too old.
661 pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);
663 const saml2::AuthnStatement* ssoStatement=saml2token->getAuthnStatements().front();
664 if (authnskew.first && authnskew.second &&
665 ssoStatement->getAuthnInstant() && (now - ssoStatement->getAuthnInstantEpoch() > authnskew.second))
666 throw FatalProfileException("The gap between now and the time you logged into your identity provider exceeds the limit.");
669 saml2::SubjectLocality* locality = ssoStatement->getSubjectLocality();
670 if (locality && locality->getAddress()) {
671 auto_ptr_char ip(locality->getAddress());
672 checkAddress(application, httpRequest, ip.get());
675 saml2name = saml2token->getSubject() ? saml2token->getSubject()->getNameID() : NULL;
676 if (ssoStatement->getAuthnContext() && ssoStatement->getAuthnContext()->getAuthnContextClassRef())
677 authMethod = ssoStatement->getAuthnContext()->getAuthnContextClassRef()->getReference();
678 if (ssoStatement->getAuthnInstant())
679 authInstant = ssoStatement->getAuthnInstant()->getRawData();
681 // Session expiration for SAML 2.0 is jointly IdP- and SP-driven.
682 sessionExp = ssoStatement->getSessionNotOnOrAfter() ? ssoStatement->getSessionNotOnOrAfterEpoch() : 0;
683 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
684 if (!lifetime.first || lifetime.second == 0)
685 lifetime.second = 28800;
687 sessionExp = now + lifetime.second; // IdP says nothing, calulate based on SP.
689 sessionExp = min(sessionExp, now + lifetime.second); // Use the lowest.
692 m_log.debug("ADFS profile processing completed successfully");
694 // We've successfully "accepted" the SSO token.
695 // To complete processing, we need to extract and resolve attributes and then create the session.
697 // Normalize a SAML 1.x NameIdentifier...
698 auto_ptr<saml2::NameID> nameid(saml1name ? saml2::NameIDBuilder::buildNameID() : NULL);
700 nameid->setName(saml1name->getName());
701 nameid->setFormat(saml1name->getFormat());
702 nameid->setNameQualifier(saml1name->getNameQualifier());
705 // The context will handle deleting attributes and new tokens.
706 vector<const Assertion*> tokens(1,token);
707 auto_ptr<ResolutionContext> ctx(
710 policy.getIssuerMetadata(),
713 (saml1name ? nameid.get() : saml2name),
721 // Copy over any new tokens, but leave them in the context for cleanup.
722 tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
725 application.getServiceProvider().getSessionCache()->insert(
732 (saml1name ? nameid.get() : saml2name),
738 ctx.get() ? &ctx->getResolvedAttributes() : NULL
744 pair<bool,long> ADFSLogoutInitiator::run(SPRequest& request, bool isHandler) const
746 // Normally we'd do notifications and session clearage here, but ADFS logout
747 // is missing the needed request/response features, so we have to rely on
748 // the IdP half to notify us back about the logout and do the work there.
749 // Basically we have no way to tell in the Logout receiving handler whether
750 // we initiated the logout or not.
752 Session* session = NULL;
754 session = request.getSession(false, true, false); // don't cache it and ignore all checks
756 return make_pair(false,0L);
758 // We only handle ADFS sessions.
759 if (!XMLString::equals(session->getProtocol(), WSFED_NS) || !session->getEntityID()) {
761 return make_pair(false,0L);
764 catch (exception& ex) {
765 m_log.error("error accessing current session: %s", ex.what());
766 return make_pair(false,0L);
769 string entityID(session->getEntityID());
772 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
773 // When out of process, we run natively.
774 return doRequest(request.getApplication(), entityID.c_str(), request);
777 // When not out of process, we remote the request.
778 Locker locker(session, false);
779 DDF out,in(m_address.c_str());
780 DDFJanitor jin(in), jout(out);
781 in.addmember("application_id").string(request.getApplication().getId());
782 in.addmember("entity_id").string(entityID.c_str());
783 out=request.getServiceProvider().getListenerService()->send(in);
784 return unwrap(request, out);
788 void ADFSLogoutInitiator::receive(DDF& in, ostream& out)
792 const char* aid=in["application_id"].string();
793 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
795 // Something's horribly wrong.
796 m_log.error("couldn't find application (%s) for logout", aid ? aid : "(missing)");
797 throw ConfigurationException("Unable to locate application for logout, deleted?");
800 // Set up a response shim.
802 DDFJanitor jout(ret);
803 auto_ptr<HTTPResponse> resp(getResponse(ret));
805 // Since we're remoted, the result should either be a throw, which we pass on,
806 // a false/0 return, which we just return as an empty structure, or a response/redirect,
807 // which we capture in the facade and send back.
808 doRequest(*app, in["entity_id"].string(), *resp.get());
812 throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
816 pair<bool,long> ADFSLogoutInitiator::doRequest(const Application& application, const char* entityID, HTTPResponse& response) const
821 throw ConfigurationException("Missing entityID parameter.");
823 // With a session in hand, we can create a request message, if we can find a compatible endpoint.
824 MetadataProvider* m=application.getMetadataProvider();
826 MetadataProvider::Criteria mc(entityID, &IDPSSODescriptor::ELEMENT_QNAME, m_binding.get());
827 pair<const EntityDescriptor*,const RoleDescriptor*> entity=m->getEntityDescriptor(mc);
829 throw MetadataException("Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", entityID));
830 else if (!entity.second)
831 throw MetadataException("Unable to locate ADFS IdP role for identity provider ($entityID).", namedparams(1, "entityID", entityID));
833 const EndpointType* ep = EndpointManager<SingleLogoutService>(
834 dynamic_cast<const IDPSSODescriptor*>(entity.second)->getSingleLogoutServices()
835 ).getByBinding(m_binding.get());
837 throw MetadataException(
838 "Unable to locate ADFS single logout service for identity provider ($entityID).",
839 namedparams(1, "entityID", entityID)
843 auto_ptr_char dest(ep->getLocation());
845 string req=string(dest.get()) + (strchr(dest.get(),'?') ? '&' : '?') + "wa=wsignout1.0";
846 return make_pair(true,response.sendRedirect(req.c_str()));
848 catch (exception& ex) {
849 m_log.error("error issuing ADFS logout request: %s", ex.what());
852 return make_pair(false,0L);
854 throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
858 pair<bool,long> ADFSLogout::run(SPRequest& request, bool isHandler) const
860 // Defer to base class for front-channel loop first.
861 // This won't initiate the loop, only continue/end it.
862 pair<bool,long> ret = LogoutHandler::run(request, isHandler);
866 // wa parameter indicates the "action" to perform
867 bool returning = false;
868 const char* param = request.getParameter("wa");
870 if (!strcmp(param, "wsignin1.0"))
871 return m_login.run(request, isHandler);
872 else if (strcmp(param, "wsignout1.0") && strcmp(param, "wsignoutcleanup1.0"))
873 throw FatalProfileException("Unsupported WS-Federation action paremeter ($1).", params(1, param));
875 else if (strcmp(request.getMethod(),"GET") || !request.getParameter("notifying"))
876 throw FatalProfileException("Unsupported request to ADFS protocol endpoint.");
880 param = request.getParameter("wreply");
881 const Application& app = request.getApplication();
884 // Pass control to the first front channel notification point, if any.
885 map<string,string> parammap;
887 parammap["wreply"] = param;
888 pair<bool,long> result = notifyFrontChannel(app, request, request, ¶mmap);
893 // Best effort on back channel and to remove the user agent's session.
894 string session_id = app.getServiceProvider().getSessionCache()->active(app, request);
895 if (!session_id.empty()) {
896 vector<string> sessions(1,session_id);
897 notifyBackChannel(app, request.getRequestURL(), sessions, false);
899 app.getServiceProvider().getSessionCache()->remove(app, request, &request);
901 catch (exception& ex) {
902 m_log.error("error removing session (%s): %s", session_id.c_str(), ex.what());
907 return make_pair(true, request.sendRedirect(param));
908 return sendLogoutPage(app, request, request, false, "Logout complete.");