2 * Copyright 2001-2009 Internet2
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
20 * ADFSv1 extension library
23 #if defined (_MSC_VER) || defined(__BORLANDC__)
24 # include "config_win32.h"
30 # define _CRT_NONSTDC_NO_DEPRECATE 1
31 # define _CRT_SECURE_NO_DEPRECATE 1
32 # define ADFS_EXPORTS __declspec(dllexport)
39 #include <shibsp/base.h>
40 #include <shibsp/exceptions.h>
41 #include <shibsp/Application.h>
42 #include <shibsp/ServiceProvider.h>
43 #include <shibsp/SessionCache.h>
44 #include <shibsp/SPConfig.h>
45 #include <shibsp/handler/AssertionConsumerService.h>
46 #include <shibsp/handler/LogoutHandler.h>
47 #include <shibsp/handler/SessionInitiator.h>
48 #include <xmltooling/logging.h>
49 #include <xmltooling/util/NDC.h>
50 #include <xmltooling/util/URLEncoder.h>
51 #include <xmltooling/util/XMLHelper.h>
52 #include <xercesc/util/XMLUniDefs.hpp>
55 # include <shibsp/attribute/resolver/ResolutionContext.h>
56 # include <shibsp/metadata/MetadataProviderCriteria.h>
57 # include <saml/SAMLConfig.h>
58 # include <saml/saml1/core/Assertions.h>
59 # include <saml/saml1/profile/AssertionValidator.h>
60 # include <saml/saml2/core/Assertions.h>
61 # include <saml/saml2/metadata/Metadata.h>
62 # include <saml/saml2/metadata/EndpointManager.h>
63 # include <saml/saml2/profile/AssertionValidator.h>
64 # include <xmltooling/impl/AnyElement.h>
65 # include <xmltooling/validation/ValidatorSuite.h>
66 using namespace opensaml::saml2md;
68 # define min(a,b) (((a) < (b)) ? (a) : (b))
71 using namespace shibsp;
72 using namespace opensaml;
73 using namespace xmltooling::logging;
74 using namespace xmltooling;
75 using namespace xercesc;
78 #define WSFED_NS "http://schemas.xmlsoap.org/ws/2003/07/secext"
79 #define WSTRUST_NS "http://schemas.xmlsoap.org/ws/2005/02/trust"
84 class SHIBSP_DLLLOCAL ADFSDecoder : public MessageDecoder
88 ADFSDecoder() : m_ns(WSTRUST_NS) {}
89 virtual ~ADFSDecoder() {}
91 XMLObject* decode(string& relayState, const GenericRequest& genericRequest, SecurityPolicy& policy) const;
94 void extractMessageDetails(
95 const XMLObject& message, const GenericRequest& req, const XMLCh* protocol, SecurityPolicy& policy
100 MessageDecoder* ADFSDecoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
102 return new ADFSDecoder();
106 #if defined (_MSC_VER)
107 #pragma warning( push )
108 #pragma warning( disable : 4250 )
111 class SHIBSP_DLLLOCAL ADFSSessionInitiator : public SessionInitiator, public AbstractHandler, public RemotedHandler
114 ADFSSessionInitiator(const DOMElement* e, const char* appId)
115 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator.ADFS")), m_appId(appId), m_binding(WSFED_NS) {
116 // If Location isn't set, defer address registration until the setParent call.
117 pair<bool,const char*> loc = getString("Location");
119 string address = m_appId + loc.second + "::run::ADFSSI";
120 setAddress(address.c_str());
123 virtual ~ADFSSessionInitiator() {}
125 void setParent(const PropertySet* parent) {
126 DOMPropertySet::setParent(parent);
127 pair<bool,const char*> loc = getString("Location");
129 string address = m_appId + loc.second + "::run::ADFSSI";
130 setAddress(address.c_str());
133 m_log.warn("no Location property in ADFS SessionInitiator (or parent), can't register as remoted handler");
137 void receive(DDF& in, ostream& out);
138 pair<bool,long> unwrap(SPRequest& request, DDF& out) const;
139 pair<bool,long> run(SPRequest& request, string& entityID, bool isHandler=true) const;
142 pair<bool,long> doRequest(
143 const Application& application,
144 const HTTPRequest* httpRequest,
145 HTTPResponse& httpResponse,
146 const char* entityID,
147 const char* acsLocation,
148 const char* authnContextClassRef,
152 auto_ptr_XMLCh m_binding;
155 class SHIBSP_DLLLOCAL ADFSConsumer : public shibsp::AssertionConsumerService
158 ADFSConsumer(const DOMElement* e, const char* appId)
159 : shibsp::AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SSO.ADFS"))
161 ,m_protocol(WSFED_NS)
164 virtual ~ADFSConsumer() {}
167 void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
168 AssertionConsumerService::generateMetadata(role, handlerURL);
169 role.addSupport(m_protocol.get());
172 auto_ptr_XMLCh m_protocol;
175 void implementProtocol(
176 const Application& application,
177 const HTTPRequest& httpRequest,
178 HTTPResponse& httpResponse,
179 SecurityPolicy& policy,
180 const PropertySet* settings,
181 const XMLObject& xmlObject
186 class SHIBSP_DLLLOCAL ADFSLogoutInitiator : public AbstractHandler, public LogoutHandler
189 ADFSLogoutInitiator(const DOMElement* e, const char* appId)
190 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".LogoutInitiator.ADFS")), m_appId(appId), m_binding(WSFED_NS) {
191 // If Location isn't set, defer address registration until the setParent call.
192 pair<bool,const char*> loc = getString("Location");
194 string address = m_appId + loc.second + "::run::ADFSLI";
195 setAddress(address.c_str());
198 virtual ~ADFSLogoutInitiator() {}
200 void setParent(const PropertySet* parent) {
201 DOMPropertySet::setParent(parent);
202 pair<bool,const char*> loc = getString("Location");
204 string address = m_appId + loc.second + "::run::ADFSLI";
205 setAddress(address.c_str());
208 m_log.warn("no Location property in ADFS LogoutInitiator (or parent), can't register as remoted handler");
212 void receive(DDF& in, ostream& out);
213 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
216 const char* getType() const {
217 return "LogoutInitiator";
222 pair<bool,long> doRequest(const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse, Session* session) const;
225 auto_ptr_XMLCh m_binding;
228 class SHIBSP_DLLLOCAL ADFSLogout : public AbstractHandler, public LogoutHandler
231 ADFSLogout(const DOMElement* e, const char* appId)
232 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".Logout.ADFS")), m_login(e, appId) {
235 m_preserve.push_back("wreply");
236 string address = string(appId) + getString("Location").second + "::run::ADFSLO";
237 setAddress(address.c_str());
240 virtual ~ADFSLogout() {}
242 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
245 void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
246 m_login.generateMetadata(role, handlerURL);
247 const char* loc = getString("Location").second;
248 string hurl(handlerURL);
252 auto_ptr_XMLCh widen(hurl.c_str());
253 SingleLogoutService* ep = SingleLogoutServiceBuilder::buildSingleLogoutService();
254 ep->setLocation(widen.get());
255 ep->setBinding(m_login.m_protocol.get());
256 role.getSingleLogoutServices().push_back(ep);
259 const char* getType() const {
260 return m_login.getType();
265 ADFSConsumer m_login;
268 #if defined (_MSC_VER)
269 #pragma warning( pop )
272 SessionInitiator* ADFSSessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
274 return new ADFSSessionInitiator(p.first, p.second);
277 Handler* ADFSLogoutFactory(const pair<const DOMElement*,const char*>& p)
279 return new ADFSLogout(p.first, p.second);
282 Handler* ADFSLogoutInitiatorFactory(const pair<const DOMElement*,const char*>& p)
284 return new ADFSLogoutInitiator(p.first, p.second);
287 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);
288 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);
291 extern "C" int ADFS_EXPORTS xmltooling_extension_init(void*)
293 SPConfig& conf=SPConfig::getConfig();
294 conf.SessionInitiatorManager.registerFactory("ADFS", ADFSSessionInitiatorFactory);
295 conf.LogoutInitiatorManager.registerFactory("ADFS", ADFSLogoutInitiatorFactory);
296 conf.AssertionConsumerServiceManager.registerFactory("ADFS", ADFSLogoutFactory);
297 conf.AssertionConsumerServiceManager.registerFactory(WSFED_NS, ADFSLogoutFactory);
299 SAMLConfig::getConfig().MessageDecoderManager.registerFactory(WSFED_NS, ADFSDecoderFactory);
300 XMLObjectBuilder::registerBuilder(xmltooling::QName(WSTRUST_NS,"RequestedSecurityToken"), new AnyElementBuilder());
301 XMLObjectBuilder::registerBuilder(xmltooling::QName(WSTRUST_NS,"RequestSecurityTokenResponse"), new AnyElementBuilder());
306 extern "C" void ADFS_EXPORTS xmltooling_extension_term()
308 /* should get unregistered during normal shutdown...
309 SPConfig& conf=SPConfig::getConfig();
310 conf.SessionInitiatorManager.deregisterFactory("ADFS");
311 conf.LogoutInitiatorManager.deregisterFactory("ADFS");
312 conf.AssertionConsumerServiceManager.deregisterFactory("ADFS");
313 conf.AssertionConsumerServiceManager.deregisterFactory(WSFED_NS);
315 SAMLConfig::getConfig().MessageDecoderManager.deregisterFactory(WSFED_NS);
320 pair<bool,long> ADFSSessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
322 // We have to know the IdP to function.
323 if (entityID.empty())
324 return make_pair(false,0L);
327 const Handler* ACS=NULL;
329 pair<bool,const char*> acClass;
330 const Application& app=request.getApplication();
333 option = request.getParameter("target");
337 // Since we're passing the ACS by value, we need to compute the return URL,
338 // so we'll need the target resource for real.
339 recoverRelayState(request.getApplication(), request, request, target, false);
341 if (acClass.second = request.getParameter("authnContextClassRef"))
342 acClass.first = true;
344 acClass = getString("authnContextClassRef");
347 // We're running as a "virtual handler" from within the filter.
348 // The target resource is the current one and everything else is defaulted.
349 target=request.getRequestURL();
351 const PropertySet* settings = request.getRequestSettings().first;
352 acClass = settings->getString("authnContextClassRef");
354 acClass = getString("authnContextClassRef");
357 // Since we're not passing by index, we need to fully compute the return URL.
358 // Get all the ADFS endpoints.
359 const vector<const Handler*>& handlers = app.getAssertionConsumerServicesByBinding(m_binding.get());
361 // Index comes from request, or default set in the handler, or we just pick the first endpoint.
362 pair<bool,unsigned int> index(false,0);
364 option = request.getParameter("acsIndex");
366 index = pair<bool,unsigned int>(true, atoi(option));
369 index = getUnsignedInt("defaultACSIndex");
371 for (vector<const Handler*>::const_iterator h = handlers.begin(); !ACS && h!=handlers.end(); ++h) {
372 if (index.second == (*h)->getUnsignedInt("index").second)
376 else if (!handlers.empty()) {
377 ACS = handlers.front();
380 throw ConfigurationException("Unable to locate ADFS response endpoint.");
382 // Compute the ACS URL. We add the ACS location to the base handlerURL.
383 string ACSloc=request.getHandlerURL(target.c_str());
384 pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
385 if (loc.first) ACSloc+=loc.second;
388 // We may already have RelayState set if we looped back here,
389 // but just in case target is a resource, we reset it back.
391 option = request.getParameter("target");
396 m_log.debug("attempting to initiate session using ADFS with provider (%s)", entityID.c_str());
398 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
399 // Out of process means the POST data via the request can be exposed directly to the private method.
400 // The method will handle POST preservation if necessary *before* issuing the response, but only if
401 // it dispatches to an IdP.
402 return doRequest(app, &request, request, entityID.c_str(), ACSloc.c_str(), (acClass.first ? acClass.second : NULL), target);
406 DDF out,in = DDF(m_address.c_str()).structure();
407 DDFJanitor jin(in), jout(out);
408 in.addmember("application_id").string(app.getId());
409 in.addmember("entity_id").string(entityID.c_str());
410 in.addmember("acsLocation").string(ACSloc.c_str());
412 in.addmember("RelayState").string(target.c_str());
414 in.addmember("authnContextClassRef").string(acClass.second);
416 // Remote the processing.
417 out = request.getServiceProvider().getListenerService()->send(in);
418 return unwrap(request, out);
421 pair<bool,long> ADFSSessionInitiator::unwrap(SPRequest& request, DDF& out) const
423 // See if there's any response to send back.
424 if (!out["redirect"].isnull() || !out["response"].isnull()) {
425 // If so, we're responsible for handling the POST data, probably by dropping a cookie.
426 preservePostData(request.getApplication(), request, request, out["RelayState"].string());
428 return RemotedHandler::unwrap(request, out);
431 void ADFSSessionInitiator::receive(DDF& in, ostream& out)
434 const char* aid=in["application_id"].string();
435 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
437 // Something's horribly wrong.
438 m_log.error("couldn't find application (%s) to generate ADFS request", aid ? aid : "(missing)");
439 throw ConfigurationException("Unable to locate application for new session, deleted?");
442 const char* entityID = in["entity_id"].string();
443 const char* acsLocation = in["acsLocation"].string();
444 if (!entityID || !acsLocation)
445 throw ConfigurationException("No entityID or acsLocation parameter supplied to remoted SessionInitiator.");
448 DDFJanitor jout(ret);
450 // Wrap the outgoing object with a Response facade.
451 auto_ptr<HTTPResponse> http(getResponse(ret));
453 string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");
455 // Since we're remoted, the result should either be a throw, which we pass on,
456 // a false/0 return, which we just return as an empty structure, or a response/redirect,
457 // which we capture in the facade and send back.
458 doRequest(*app, NULL, *http.get(), entityID, acsLocation, in["authnContextClassRef"].string(), relayState);
461 ret.addmember("RelayState").string(relayState.c_str());
465 pair<bool,long> ADFSSessionInitiator::doRequest(
466 const Application& app,
467 const HTTPRequest* httpRequest,
468 HTTPResponse& httpResponse,
469 const char* entityID,
470 const char* acsLocation,
471 const char* authnContextClassRef,
476 // Use metadata to invoke the SSO service directly.
477 MetadataProvider* m=app.getMetadataProvider();
479 MetadataProviderCriteria mc(app, entityID, &IDPSSODescriptor::ELEMENT_QNAME, m_binding.get());
480 pair<const EntityDescriptor*,const RoleDescriptor*> entity=m->getEntityDescriptor(mc);
482 m_log.warn("unable to locate metadata for provider (%s)", entityID);
483 throw MetadataException("Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", entityID));
485 else if (!entity.second) {
486 m_log.warn("unable to locate ADFS-aware identity provider role for provider (%s)", entityID);
488 return make_pair(false,0L);
489 throw MetadataException("Unable to locate ADFS-aware identity provider role for provider ($entityID)", namedparams(1, "entityID", entityID));
491 const EndpointType* ep = EndpointManager<SingleSignOnService>(
492 dynamic_cast<const IDPSSODescriptor*>(entity.second)->getSingleSignOnServices()
493 ).getByBinding(m_binding.get());
495 m_log.warn("unable to locate compatible SSO service for provider (%s)", entityID);
497 return make_pair(false,0L);
498 throw MetadataException("Unable to locate compatible SSO service for provider ($entityID)", namedparams(1, "entityID", entityID));
501 preserveRelayState(app, httpResponse, relayState);
504 time_t epoch=time(NULL);
505 #ifndef HAVE_GMTIME_R
506 struct tm* ptime=gmtime(&epoch);
509 struct tm* ptime=gmtime_r(&epoch,&res);
512 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
514 auto_ptr_char dest(ep->getLocation());
515 const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
517 string req=string(dest.get()) + (strchr(dest.get(),'?') ? '&' : '?') + "wa=wsignin1.0&wreply=" + urlenc->encode(acsLocation) +
518 "&wct=" + urlenc->encode(timebuf) + "&wtrealm=" + urlenc->encode(app.getString("entityID").second);
519 if (authnContextClassRef)
520 req += "&wauth=" + urlenc->encode(authnContextClassRef);
521 if (!relayState.empty())
522 req += "&wctx=" + urlenc->encode(relayState.c_str());
525 // If the request object is available, we're responsible for the POST data.
526 preservePostData(app, *httpRequest, httpResponse, relayState.c_str());
529 return make_pair(true, httpResponse.sendRedirect(req.c_str()));
531 return make_pair(false,0L);
537 XMLObject* ADFSDecoder::decode(string& relayState, const GenericRequest& genericRequest, SecurityPolicy& policy) const
540 xmltooling::NDC ndc("decode");
542 Category& log = Category::getInstance(SHIBSP_LOGCAT".MessageDecoder.ADFS");
544 log.debug("validating input");
545 const HTTPRequest* httpRequest=dynamic_cast<const HTTPRequest*>(&genericRequest);
547 throw BindingException("Unable to cast request object to HTTPRequest type.");
548 if (strcmp(httpRequest->getMethod(),"POST"))
549 throw BindingException("Invalid HTTP method ($1).", params(1, httpRequest->getMethod()));
550 const char* param = httpRequest->getParameter("wa");
551 if (!param || strcmp(param, "wsignin1.0"))
552 throw BindingException("Missing or invalid wa parameter (should be wsignin1.0).");
553 param = httpRequest->getParameter("wctx");
557 param = httpRequest->getParameter("wresult");
559 throw BindingException("Request missing wresult parameter.");
561 log.debug("decoded ADFS response:\n%s", param);
563 // Parse and bind the document into an XMLObject.
564 istringstream is(param);
565 DOMDocument* doc = (policy.getValidating() ? XMLToolingConfig::getConfig().getValidatingParser()
566 : XMLToolingConfig::getConfig().getParser()).parse(is);
567 XercesJanitor<DOMDocument> janitor(doc);
568 auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
571 if (!XMLString::equals(xmlObject->getElementQName().getLocalPart(), RequestSecurityTokenResponse)) {
572 log.error("unrecognized root element on message: %s", xmlObject->getElementQName().toString().c_str());
573 throw BindingException("Decoded message was not of the appropriate type.");
576 if (!policy.getValidating())
577 SchemaValidators.validate(xmlObject.get());
579 // Skip policy step here, there's no security in the wrapper.
580 // policy.evaluate(*xmlObject.get(), &genericRequest);
582 return xmlObject.release();
585 void ADFSConsumer::implementProtocol(
586 const Application& application,
587 const HTTPRequest& httpRequest,
588 HTTPResponse& httpResponse,
589 SecurityPolicy& policy,
590 const PropertySet* settings,
591 const XMLObject& xmlObject
594 // Implementation of ADFS profile.
595 m_log.debug("processing message against ADFS Passive Requester profile");
597 // With ADFS, all the security comes from the assertion, which is two levels down in the message.
599 const ElementProxy* response = dynamic_cast<const ElementProxy*>(&xmlObject);
600 if (!response || !response->hasChildren())
601 throw FatalProfileException("Incoming message was not of the proper type or contains no security token.");
603 const Assertion* token = NULL;
604 for (vector<XMLObject*>::const_iterator xo = response->getUnknownXMLObjects().begin(); xo != response->getUnknownXMLObjects().end(); ++xo) {
605 // Look for the RequestedSecurityToken element.
606 if (XMLString::equals((*xo)->getElementQName().getLocalPart(), RequestedSecurityToken)) {
607 response = dynamic_cast<const ElementProxy*>(*xo);
608 if (!response || !response->hasChildren())
609 throw FatalProfileException("Token wrapper element did not contain a security token.");
610 token = dynamic_cast<const Assertion*>(response->getUnknownXMLObjects().front());
611 if (!token || !token->getSignature())
612 throw FatalProfileException("Incoming message did not contain a signed SAML assertion.");
617 // Extract message and issuer details from assertion.
618 extractMessageDetails(*token, m_protocol.get(), policy);
620 // Run the policy over the assertion. Handles replay, freshness, and
621 // signature verification, assuming the relevant rules are configured.
622 policy.evaluate(*token);
624 // If no security is in place now, we kick it.
625 if (!policy.isAuthenticated())
626 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
628 time_t now = time(NULL);
630 const PropertySet* sessionProps = application.getPropertySet("Sessions");
631 const EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL;
633 saml1::NameIdentifier* saml1name=NULL;
634 saml2::NameID* saml2name=NULL;
635 const XMLCh* authMethod=NULL;
636 const XMLCh* authInstant=NULL;
637 time_t sessionExp = 0;
639 const saml1::Assertion* saml1token = dynamic_cast<const saml1::Assertion*>(token);
641 // Now do profile and core semantic validation to ensure we can use it for SSO.
642 saml1::AssertionValidator ssoValidator(application.getRelyingParty(entity)->getXMLString("entityID").second, application.getAudiences(), now);
643 ssoValidator.validateAssertion(*saml1token);
644 if (!saml1token->getConditions() || !saml1token->getConditions()->getNotBefore() || !saml1token->getConditions()->getNotOnOrAfter())
645 throw FatalProfileException("Assertion did not contain time conditions.");
646 else if (saml1token->getAuthenticationStatements().empty())
647 throw FatalProfileException("Assertion did not contain an authentication statement.");
649 // authnskew allows rejection of SSO if AuthnInstant is too old.
650 pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);
652 const saml1::AuthenticationStatement* ssoStatement=saml1token->getAuthenticationStatements().front();
653 if (authnskew.first && authnskew.second &&
654 ssoStatement->getAuthenticationInstant() && (now - ssoStatement->getAuthenticationInstantEpoch() > authnskew.second))
655 throw FatalProfileException("The gap between now and the time you logged into your identity provider exceeds the limit.");
658 saml1::SubjectLocality* locality = ssoStatement->getSubjectLocality();
659 if (locality && locality->getIPAddress()) {
660 auto_ptr_char ip(locality->getIPAddress());
661 checkAddress(application, httpRequest, ip.get());
664 saml1name = ssoStatement->getSubject()->getNameIdentifier();
665 authMethod = ssoStatement->getAuthenticationMethod();
666 if (ssoStatement->getAuthenticationInstant())
667 authInstant = ssoStatement->getAuthenticationInstant()->getRawData();
669 // Session expiration.
670 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
671 if (!lifetime.first || lifetime.second == 0)
672 lifetime.second = 28800;
673 sessionExp = now + lifetime.second;
676 const saml2::Assertion* saml2token = dynamic_cast<const saml2::Assertion*>(token);
678 throw FatalProfileException("Incoming message did not contain a recognized type of SAML assertion.");
680 // Now do profile and core semantic validation to ensure we can use it for SSO.
681 saml2::AssertionValidator ssoValidator(application.getRelyingParty(entity)->getXMLString("entityID").second, application.getAudiences(), now);
682 ssoValidator.validateAssertion(*saml2token);
683 if (!saml2token->getConditions() || !saml2token->getConditions()->getNotBefore() || !saml2token->getConditions()->getNotOnOrAfter())
684 throw FatalProfileException("Assertion did not contain time conditions.");
685 else if (saml2token->getAuthnStatements().empty())
686 throw FatalProfileException("Assertion did not contain an authentication statement.");
688 // authnskew allows rejection of SSO if AuthnInstant is too old.
689 pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);
691 const saml2::AuthnStatement* ssoStatement=saml2token->getAuthnStatements().front();
692 if (authnskew.first && authnskew.second &&
693 ssoStatement->getAuthnInstant() && (now - ssoStatement->getAuthnInstantEpoch() > authnskew.second))
694 throw FatalProfileException("The gap between now and the time you logged into your identity provider exceeds the limit.");
697 saml2::SubjectLocality* locality = ssoStatement->getSubjectLocality();
698 if (locality && locality->getAddress()) {
699 auto_ptr_char ip(locality->getAddress());
700 checkAddress(application, httpRequest, ip.get());
703 saml2name = saml2token->getSubject() ? saml2token->getSubject()->getNameID() : NULL;
704 if (ssoStatement->getAuthnContext() && ssoStatement->getAuthnContext()->getAuthnContextClassRef())
705 authMethod = ssoStatement->getAuthnContext()->getAuthnContextClassRef()->getReference();
706 if (ssoStatement->getAuthnInstant())
707 authInstant = ssoStatement->getAuthnInstant()->getRawData();
709 // Session expiration for SAML 2.0 is jointly IdP- and SP-driven.
710 sessionExp = ssoStatement->getSessionNotOnOrAfter() ? ssoStatement->getSessionNotOnOrAfterEpoch() : 0;
711 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
712 if (!lifetime.first || lifetime.second == 0)
713 lifetime.second = 28800;
715 sessionExp = now + lifetime.second; // IdP says nothing, calulate based on SP.
717 sessionExp = min(sessionExp, now + lifetime.second); // Use the lowest.
720 m_log.debug("ADFS profile processing completed successfully");
722 // We've successfully "accepted" the SSO token.
723 // To complete processing, we need to extract and resolve attributes and then create the session.
725 // Normalize a SAML 1.x NameIdentifier...
726 auto_ptr<saml2::NameID> nameid(saml1name ? saml2::NameIDBuilder::buildNameID() : NULL);
728 nameid->setName(saml1name->getName());
729 nameid->setFormat(saml1name->getFormat());
730 nameid->setNameQualifier(saml1name->getNameQualifier());
733 // The context will handle deleting attributes and new tokens.
734 vector<const Assertion*> tokens(1,token);
735 auto_ptr<ResolutionContext> ctx(
738 policy.getIssuerMetadata(),
741 (saml1name ? nameid.get() : saml2name),
749 // Copy over any new tokens, but leave them in the context for cleanup.
750 tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
753 application.getServiceProvider().getSessionCache()->insert(
760 (saml1name ? nameid.get() : saml2name),
766 ctx.get() ? &ctx->getResolvedAttributes() : NULL
772 pair<bool,long> ADFSLogoutInitiator::run(SPRequest& request, bool isHandler) const
774 // Normally we'd do notifications and session clearage here, but ADFS logout
775 // is missing the needed request/response features, so we have to rely on
776 // the IdP half to notify us back about the logout and do the work there.
777 // Basically we have no way to tell in the Logout receiving handler whether
778 // we initiated the logout or not.
780 Session* session = NULL;
782 session = request.getSession(false, true, false); // don't cache it and ignore all checks
784 return make_pair(false,0L);
786 // We only handle ADFS sessions.
787 if (!XMLString::equals(session->getProtocol(), WSFED_NS) || !session->getEntityID()) {
789 return make_pair(false,0L);
792 catch (exception& ex) {
793 m_log.error("error accessing current session: %s", ex.what());
794 return make_pair(false,0L);
797 string entityID(session->getEntityID());
800 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
801 // When out of process, we run natively.
802 return doRequest(request.getApplication(), request, request, session);
805 // When not out of process, we remote the request.
807 vector<string> headers(1,"Cookie");
808 DDF out,in = wrap(request,&headers);
809 DDFJanitor jin(in), jout(out);
810 out=request.getServiceProvider().getListenerService()->send(in);
811 return unwrap(request, out);
815 void ADFSLogoutInitiator::receive(DDF& in, ostream& out)
818 // Defer to base class for notifications
819 if (in["notify"].integer() == 1)
820 return LogoutHandler::receive(in, out);
823 const char* aid=in["application_id"].string();
824 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
826 // Something's horribly wrong.
827 m_log.error("couldn't find application (%s) for logout", aid ? aid : "(missing)");
828 throw ConfigurationException("Unable to locate application for logout, deleted?");
831 // Unpack the request.
832 auto_ptr<HTTPRequest> req(getRequest(in));
834 // Set up a response shim.
836 DDFJanitor jout(ret);
837 auto_ptr<HTTPResponse> resp(getResponse(ret));
839 Session* session = NULL;
841 session = app->getServiceProvider().getSessionCache()->find(*app, *req.get(), NULL, NULL);
843 catch (exception& ex) {
844 m_log.error("error accessing current session: %s", ex.what());
847 // With no session, we just skip the request and let it fall through to an empty struct return.
849 if (session->getEntityID()) {
850 // Since we're remoted, the result should either be a throw, which we pass on,
851 // a false/0 return, which we just return as an empty structure, or a response/redirect,
852 // which we capture in the facade and send back.
853 doRequest(*app, *req.get(), *resp.get(), session);
856 m_log.error("no issuing entityID found in session");
858 app->getServiceProvider().getSessionCache()->remove(*app, *req.get(), resp.get());
863 throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
867 pair<bool,long> ADFSLogoutInitiator::doRequest(
868 const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse, Session* session
871 // Do back channel notification.
872 vector<string> sessions(1, session->getID());
873 if (!notifyBackChannel(application, httpRequest.getRequestURL(), sessions, false)) {
875 application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
876 return sendLogoutPage(application, httpRequest, httpResponse, true, "Partial logout failure.");
880 pair<bool,long> ret = make_pair(false,0L);
883 // With a session in hand, we can create a request message, if we can find a compatible endpoint.
884 MetadataProvider* m=application.getMetadataProvider();
885 Locker metadataLocker(m);
886 MetadataProviderCriteria mc(application, session->getEntityID(), &IDPSSODescriptor::ELEMENT_QNAME, m_binding.get());
887 pair<const EntityDescriptor*,const RoleDescriptor*> entity=m->getEntityDescriptor(mc);
889 throw MetadataException(
890 "Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", session->getEntityID())
893 else if (!entity.second) {
894 throw MetadataException(
895 "Unable to locate ADFS IdP role for identity provider ($entityID).", namedparams(1, "entityID", session->getEntityID())
899 const EndpointType* ep = EndpointManager<SingleLogoutService>(
900 dynamic_cast<const IDPSSODescriptor*>(entity.second)->getSingleLogoutServices()
901 ).getByBinding(m_binding.get());
903 throw MetadataException(
904 "Unable to locate ADFS single logout service for identity provider ($entityID).", namedparams(1, "entityID", session->getEntityID())
908 const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
909 const char* returnloc = httpRequest.getParameter("return");
910 auto_ptr_char dest(ep->getLocation());
911 string req=string(dest.get()) + (strchr(dest.get(),'?') ? '&' : '?') + "wa=wsignout1.0";
913 req += "&wreply=" + urlenc->encode(returnloc);
914 ret.second = httpResponse.sendRedirect(req.c_str());
917 catch (exception& ex) {
918 m_log.error("error issuing ADFS logout request: %s", ex.what());
924 application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
929 throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
933 pair<bool,long> ADFSLogout::run(SPRequest& request, bool isHandler) const
935 // Defer to base class for front-channel loop first.
936 // This won't initiate the loop, only continue/end it.
937 pair<bool,long> ret = LogoutHandler::run(request, isHandler);
941 // wa parameter indicates the "action" to perform
942 bool returning = false;
943 const char* param = request.getParameter("wa");
945 if (!strcmp(param, "wsignin1.0"))
946 return m_login.run(request, isHandler);
947 else if (strcmp(param, "wsignout1.0") && strcmp(param, "wsignoutcleanup1.0"))
948 throw FatalProfileException("Unsupported WS-Federation action paremeter ($1).", params(1, param));
950 else if (strcmp(request.getMethod(),"GET") || !request.getParameter("notifying"))
951 throw FatalProfileException("Unsupported request to ADFS protocol endpoint.");
955 param = request.getParameter("wreply");
956 const Application& app = request.getApplication();
959 // Pass control to the first front channel notification point, if any.
960 map<string,string> parammap;
962 parammap["wreply"] = param;
963 pair<bool,long> result = notifyFrontChannel(app, request, request, ¶mmap);
968 // Best effort on back channel and to remove the user agent's session.
969 string session_id = app.getServiceProvider().getSessionCache()->active(app, request);
970 if (!session_id.empty()) {
971 vector<string> sessions(1,session_id);
972 notifyBackChannel(app, request.getRequestURL(), sessions, false);
974 app.getServiceProvider().getSessionCache()->remove(app, request, &request);
976 catch (exception& ex) {
977 m_log.error("error removing session (%s): %s", session_id.c_str(), ex.what());
982 return make_pair(true, request.sendRedirect(param));
983 return sendLogoutPage(app, request, request, false, "Logout complete.");