2 * Copyright 2001-2010 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/SPRequest.h>
44 #include <shibsp/handler/AssertionConsumerService.h>
45 #include <shibsp/handler/LogoutInitiator.h>
46 #include <shibsp/handler/SessionInitiator.h>
47 #include <xmltooling/logging.h>
48 #include <xmltooling/util/DateTime.h>
49 #include <xmltooling/util/NDC.h>
50 #include <xmltooling/util/URLEncoder.h>
51 #include <xmltooling/util/XMLHelper.h>
55 # include <shibsp/attribute/resolver/ResolutionContext.h>
56 # include <shibsp/metadata/MetadataProviderCriteria.h>
57 # include <saml/SAMLConfig.h>
58 # include <saml/exceptions.h>
59 # include <saml/binding/SecurityPolicy.h>
60 # include <saml/saml1/core/Assertions.h>
61 # include <saml/saml2/core/Assertions.h>
62 # include <saml/saml2/metadata/Metadata.h>
63 # include <saml/saml2/metadata/EndpointManager.h>
64 # include <xmltooling/XMLToolingConfig.h>
65 # include <xmltooling/impl/AnyElement.h>
66 # include <xmltooling/util/ParserPool.h>
67 # include <xmltooling/validation/ValidatorSuite.h>
68 using namespace opensaml::saml2md;
70 # define min(a,b) (((a) < (b)) ? (a) : (b))
73 using namespace shibsp;
74 using namespace opensaml;
75 using namespace xmltooling::logging;
76 using namespace xmltooling;
77 using namespace xercesc;
80 #define WSFED_NS "http://schemas.xmlsoap.org/ws/2003/07/secext"
81 #define WSTRUST_NS "http://schemas.xmlsoap.org/ws/2005/02/trust"
86 class SHIBSP_DLLLOCAL ADFSDecoder : public MessageDecoder
90 ADFSDecoder() : m_ns(WSTRUST_NS) {}
91 virtual ~ADFSDecoder() {}
93 const XMLCh* getProtocolFamily() const {
97 XMLObject* decode(string& relayState, const GenericRequest& genericRequest, SecurityPolicy& policy) const;
100 void extractMessageDetails(
101 const XMLObject& message, const GenericRequest& req, const XMLCh* protocol, SecurityPolicy& policy
106 MessageDecoder* ADFSDecoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
108 return new ADFSDecoder();
112 #if defined (_MSC_VER)
113 #pragma warning( push )
114 #pragma warning( disable : 4250 )
117 class SHIBSP_DLLLOCAL ADFSSessionInitiator : public SessionInitiator, public AbstractHandler, public RemotedHandler
120 ADFSSessionInitiator(const DOMElement* e, const char* appId)
121 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator.ADFS"), nullptr, &m_remapper), m_appId(appId), m_binding(WSFED_NS) {
122 // If Location isn't set, defer address registration until the setParent call.
123 pair<bool,const char*> loc = getString("Location");
125 string address = m_appId + loc.second + "::run::ADFSSI";
126 setAddress(address.c_str());
129 virtual ~ADFSSessionInitiator() {}
131 void setParent(const PropertySet* parent) {
132 DOMPropertySet::setParent(parent);
133 pair<bool,const char*> loc = getString("Location");
135 string address = m_appId + loc.second + "::run::ADFSSI";
136 setAddress(address.c_str());
139 m_log.warn("no Location property in ADFS SessionInitiator (or parent), can't register as remoted handler");
143 void receive(DDF& in, ostream& out);
144 pair<bool,long> unwrap(SPRequest& request, DDF& out) const;
145 pair<bool,long> run(SPRequest& request, string& entityID, bool isHandler=true) const;
147 const XMLCh* getProtocolFamily() const {
148 return m_binding.get();
152 pair<bool,long> doRequest(
153 const Application& application,
154 const HTTPRequest* httpRequest,
155 HTTPResponse& httpResponse,
156 const char* entityID,
157 const char* acsLocation,
158 const char* authnContextClassRef,
162 auto_ptr_XMLCh m_binding;
165 class SHIBSP_DLLLOCAL ADFSConsumer : public shibsp::AssertionConsumerService
167 auto_ptr_XMLCh m_protocol;
169 ADFSConsumer(const DOMElement* e, const char* appId)
170 : shibsp::AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SSO.ADFS")), m_protocol(WSFED_NS) {}
171 virtual ~ADFSConsumer() {}
174 void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
175 AssertionConsumerService::generateMetadata(role, handlerURL);
176 role.addSupport(m_protocol.get());
180 void implementProtocol(
181 const Application& application,
182 const HTTPRequest& httpRequest,
183 HTTPResponse& httpResponse,
184 SecurityPolicy& policy,
186 const XMLObject& xmlObject
189 const XMLCh* getProtocolFamily() const {
190 return m_protocol.get();
195 class SHIBSP_DLLLOCAL ADFSLogoutInitiator : public AbstractHandler, public LogoutInitiator
198 ADFSLogoutInitiator(const DOMElement* e, const char* appId)
199 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".LogoutInitiator.ADFS")), m_appId(appId), m_binding(WSFED_NS) {
200 // If Location isn't set, defer address registration until the setParent call.
201 pair<bool,const char*> loc = getString("Location");
203 string address = m_appId + loc.second + "::run::ADFSLI";
204 setAddress(address.c_str());
207 virtual ~ADFSLogoutInitiator() {}
209 void setParent(const PropertySet* parent) {
210 DOMPropertySet::setParent(parent);
211 pair<bool,const char*> loc = getString("Location");
213 string address = m_appId + loc.second + "::run::ADFSLI";
214 setAddress(address.c_str());
217 m_log.warn("no Location property in ADFS LogoutInitiator (or parent), can't register as remoted handler");
221 void receive(DDF& in, ostream& out);
222 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
224 const XMLCh* getProtocolFamily() const {
225 return m_binding.get();
229 pair<bool,long> doRequest(const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse, Session* session) const;
232 auto_ptr_XMLCh m_binding;
235 class SHIBSP_DLLLOCAL ADFSLogout : public AbstractHandler, public LogoutHandler
238 ADFSLogout(const DOMElement* e, const char* appId)
239 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".Logout.ADFS")), m_login(e, appId) {
242 m_preserve.push_back("wreply");
243 string address = string(appId) + getString("Location").second + "::run::ADFSLO";
244 setAddress(address.c_str());
247 virtual ~ADFSLogout() {}
249 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
252 void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
253 m_login.generateMetadata(role, handlerURL);
254 const char* loc = getString("Location").second;
255 string hurl(handlerURL);
259 auto_ptr_XMLCh widen(hurl.c_str());
260 SingleLogoutService* ep = SingleLogoutServiceBuilder::buildSingleLogoutService();
261 ep->setLocation(widen.get());
262 ep->setBinding(m_login.getProtocolFamily());
263 role.getSingleLogoutServices().push_back(ep);
266 const char* getType() const {
267 return m_login.getType();
270 const XMLCh* getProtocolFamily() const {
271 return m_login.getProtocolFamily();
275 ADFSConsumer m_login;
278 #if defined (_MSC_VER)
279 #pragma warning( pop )
282 SessionInitiator* ADFSSessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
284 return new ADFSSessionInitiator(p.first, p.second);
287 Handler* ADFSLogoutFactory(const pair<const DOMElement*,const char*>& p)
289 return new ADFSLogout(p.first, p.second);
292 Handler* ADFSLogoutInitiatorFactory(const pair<const DOMElement*,const char*>& p)
294 return new ADFSLogoutInitiator(p.first, p.second);
297 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);
298 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);
301 extern "C" int ADFS_EXPORTS xmltooling_extension_init(void*)
303 SPConfig& conf=SPConfig::getConfig();
304 conf.SessionInitiatorManager.registerFactory("ADFS", ADFSSessionInitiatorFactory);
305 conf.LogoutInitiatorManager.registerFactory("ADFS", ADFSLogoutInitiatorFactory);
306 conf.AssertionConsumerServiceManager.registerFactory("ADFS", ADFSLogoutFactory);
307 conf.AssertionConsumerServiceManager.registerFactory(WSFED_NS, ADFSLogoutFactory);
309 SAMLConfig::getConfig().MessageDecoderManager.registerFactory(WSFED_NS, ADFSDecoderFactory);
310 XMLObjectBuilder::registerBuilder(xmltooling::QName(WSTRUST_NS,"RequestedSecurityToken"), new AnyElementBuilder());
311 XMLObjectBuilder::registerBuilder(xmltooling::QName(WSTRUST_NS,"RequestSecurityTokenResponse"), new AnyElementBuilder());
316 extern "C" void ADFS_EXPORTS xmltooling_extension_term()
318 /* should get unregistered during normal shutdown...
319 SPConfig& conf=SPConfig::getConfig();
320 conf.SessionInitiatorManager.deregisterFactory("ADFS");
321 conf.LogoutInitiatorManager.deregisterFactory("ADFS");
322 conf.AssertionConsumerServiceManager.deregisterFactory("ADFS");
323 conf.AssertionConsumerServiceManager.deregisterFactory(WSFED_NS);
325 SAMLConfig::getConfig().MessageDecoderManager.deregisterFactory(WSFED_NS);
330 pair<bool,long> ADFSSessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
332 // We have to know the IdP to function.
333 if (entityID.empty() || !checkCompatibility(request, isHandler))
334 return make_pair(false,0L);
337 pair<bool,const char*> prop;
338 pair<bool,const char*> acClass;
339 const Handler* ACS=nullptr;
340 const Application& app=request.getApplication();
343 prop.second = request.getParameter("acsIndex");
344 if (prop.second && *prop.second) {
345 ACS = app.getAssertionConsumerServiceByIndex(atoi(prop.second));
347 request.log(SPRequest::SPWarn, "invalid acsIndex specified in request, using acsIndex property");
350 prop = getString("target", request);
352 target = prop.second;
354 // Since we're passing the ACS by value, we need to compute the return URL,
355 // so we'll need the target resource for real.
356 recoverRelayState(app, request, request, target, false);
358 acClass = getString("authnContextClassRef", request);
361 // Check for a hardwired target value in the map or handler.
362 prop = getString("target", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
364 target = prop.second;
366 target = request.getRequestURL();
368 acClass = getString("authnContextClassRef", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
372 pair<bool,unsigned int> index = getUnsignedInt("acsIndex", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
374 ACS = app.getAssertionConsumerServiceByIndex(index.second);
377 // Validate the ACS for use with this protocol.
378 if (!ACS || !XMLString::equals(getProtocolFamily(), ACS->getProtocolFamily())) {
380 request.log(SPRequest::SPWarn, "invalid acsIndex property, or non-ADFS ACS, using default ADFS ACS");
381 ACS = app.getAssertionConsumerServiceByProtocol(getProtocolFamily());
383 throw ConfigurationException("Unable to locate an ADFS-compatible ACS in the configuration.");
386 // Since we're not passing by index, we need to fully compute the return URL.
387 // Compute the ACS URL. We add the ACS location to the base handlerURL.
388 string ACSloc=request.getHandlerURL(target.c_str());
389 prop = ACS->getString("Location");
391 ACSloc += prop.second;
394 // We may already have RelayState set if we looped back here,
395 // but we've turned it back into a resource by this point, so if there's
396 // a target on the URL, reset to that value.
397 prop.second = request.getParameter("target");
398 if (prop.second && *prop.second)
399 target = prop.second;
402 m_log.debug("attempting to initiate session using ADFS with provider (%s)", entityID.c_str());
404 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
405 // Out of process means the POST data via the request can be exposed directly to the private method.
406 // The method will handle POST preservation if necessary *before* issuing the response, but only if
407 // it dispatches to an IdP.
408 return doRequest(app, &request, request, entityID.c_str(), ACSloc.c_str(), (acClass.first ? acClass.second : nullptr), target);
412 DDF out,in = DDF(m_address.c_str()).structure();
413 DDFJanitor jin(in), jout(out);
414 in.addmember("application_id").string(app.getId());
415 in.addmember("entity_id").string(entityID.c_str());
416 in.addmember("acsLocation").string(ACSloc.c_str());
418 in.addmember("RelayState").unsafe_string(target.c_str());
420 in.addmember("authnContextClassRef").string(acClass.second);
422 // Remote the processing.
423 out = request.getServiceProvider().getListenerService()->send(in);
424 return unwrap(request, out);
427 pair<bool,long> ADFSSessionInitiator::unwrap(SPRequest& request, DDF& out) const
429 // See if there's any response to send back.
430 if (!out["redirect"].isnull() || !out["response"].isnull()) {
431 // If so, we're responsible for handling the POST data, probably by dropping a cookie.
432 preservePostData(request.getApplication(), request, request, out["RelayState"].string());
434 return RemotedHandler::unwrap(request, out);
437 void ADFSSessionInitiator::receive(DDF& in, ostream& out)
440 const char* aid=in["application_id"].string();
441 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
443 // Something's horribly wrong.
444 m_log.error("couldn't find application (%s) to generate ADFS request", aid ? aid : "(missing)");
445 throw ConfigurationException("Unable to locate application for new session, deleted?");
448 const char* entityID = in["entity_id"].string();
449 const char* acsLocation = in["acsLocation"].string();
450 if (!entityID || !acsLocation)
451 throw ConfigurationException("No entityID or acsLocation parameter supplied to remoted SessionInitiator.");
454 DDFJanitor jout(ret);
456 // Wrap the outgoing object with a Response facade.
457 auto_ptr<HTTPResponse> http(getResponse(ret));
459 string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");
461 // Since we're remoted, the result should either be a throw, which we pass on,
462 // a false/0 return, which we just return as an empty structure, or a response/redirect,
463 // which we capture in the facade and send back.
464 doRequest(*app, nullptr, *http.get(), entityID, acsLocation, in["authnContextClassRef"].string(), relayState);
467 ret.addmember("RelayState").unsafe_string(relayState.c_str());
471 pair<bool,long> ADFSSessionInitiator::doRequest(
472 const Application& app,
473 const HTTPRequest* httpRequest,
474 HTTPResponse& httpResponse,
475 const char* entityID,
476 const char* acsLocation,
477 const char* authnContextClassRef,
482 // Use metadata to invoke the SSO service directly.
483 MetadataProvider* m=app.getMetadataProvider();
485 MetadataProviderCriteria mc(app, entityID, &IDPSSODescriptor::ELEMENT_QNAME, m_binding.get());
486 pair<const EntityDescriptor*,const RoleDescriptor*> entity=m->getEntityDescriptor(mc);
488 m_log.warn("unable to locate metadata for provider (%s)", entityID);
489 throw MetadataException("Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", entityID));
491 else if (!entity.second) {
492 m_log.log(getParent() ? Priority::INFO : Priority::WARN, "unable to locate ADFS-aware identity provider role for provider (%s)", entityID);
494 return make_pair(false,0L);
495 throw MetadataException("Unable to locate ADFS-aware identity provider role for provider ($entityID)", namedparams(1, "entityID", entityID));
497 const EndpointType* ep = EndpointManager<SingleSignOnService>(
498 dynamic_cast<const IDPSSODescriptor*>(entity.second)->getSingleSignOnServices()
499 ).getByBinding(m_binding.get());
501 m_log.warn("unable to locate compatible SSO service for provider (%s)", entityID);
503 return make_pair(false,0L);
504 throw MetadataException("Unable to locate compatible SSO service for provider ($entityID)", namedparams(1, "entityID", entityID));
507 preserveRelayState(app, httpResponse, relayState);
510 time_t epoch=time(nullptr);
511 #ifndef HAVE_GMTIME_R
512 struct tm* ptime=gmtime(&epoch);
515 struct tm* ptime=gmtime_r(&epoch,&res);
518 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
520 auto_ptr_char dest(ep->getLocation());
521 const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
523 string req=string(dest.get()) + (strchr(dest.get(),'?') ? '&' : '?') + "wa=wsignin1.0&wreply=" + urlenc->encode(acsLocation) +
524 "&wct=" + urlenc->encode(timebuf) + "&wtrealm=" + urlenc->encode(app.getString("entityID").second);
525 if (authnContextClassRef)
526 req += "&wauth=" + urlenc->encode(authnContextClassRef);
527 if (!relayState.empty())
528 req += "&wctx=" + urlenc->encode(relayState.c_str());
531 // If the request object is available, we're responsible for the POST data.
532 preservePostData(app, *httpRequest, httpResponse, relayState.c_str());
535 return make_pair(true, httpResponse.sendRedirect(req.c_str()));
537 return make_pair(false,0L);
543 XMLObject* ADFSDecoder::decode(string& relayState, const GenericRequest& genericRequest, SecurityPolicy& policy) const
546 xmltooling::NDC ndc("decode");
548 Category& log = Category::getInstance(SHIBSP_LOGCAT".MessageDecoder.ADFS");
550 log.debug("validating input");
551 const HTTPRequest* httpRequest=dynamic_cast<const HTTPRequest*>(&genericRequest);
553 throw BindingException("Unable to cast request object to HTTPRequest type.");
554 if (strcmp(httpRequest->getMethod(),"POST"))
555 throw BindingException("Invalid HTTP method ($1).", params(1, httpRequest->getMethod()));
556 const char* param = httpRequest->getParameter("wa");
557 if (!param || strcmp(param, "wsignin1.0"))
558 throw BindingException("Missing or invalid wa parameter (should be wsignin1.0).");
559 param = httpRequest->getParameter("wctx");
563 param = httpRequest->getParameter("wresult");
565 throw BindingException("Request missing wresult parameter.");
567 log.debug("decoded ADFS response:\n%s", param);
569 // Parse and bind the document into an XMLObject.
570 istringstream is(param);
571 DOMDocument* doc = (policy.getValidating() ? XMLToolingConfig::getConfig().getValidatingParser()
572 : XMLToolingConfig::getConfig().getParser()).parse(is);
573 XercesJanitor<DOMDocument> janitor(doc);
574 auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
577 if (!XMLString::equals(xmlObject->getElementQName().getLocalPart(), RequestSecurityTokenResponse)) {
578 log.error("unrecognized root element on message: %s", xmlObject->getElementQName().toString().c_str());
579 throw BindingException("Decoded message was not of the appropriate type.");
582 SchemaValidators.validate(xmlObject.get());
584 // Skip policy step here, there's no security in the wrapper.
585 // policy.evaluate(*xmlObject.get(), &genericRequest);
587 return xmlObject.release();
590 void ADFSConsumer::implementProtocol(
591 const Application& application,
592 const HTTPRequest& httpRequest,
593 HTTPResponse& httpResponse,
594 SecurityPolicy& policy,
596 const XMLObject& xmlObject
599 // Implementation of ADFS profile.
600 m_log.debug("processing message against ADFS Passive Requester profile");
602 // With ADFS, all the security comes from the assertion, which is two levels down in the message.
604 const ElementProxy* response = dynamic_cast<const ElementProxy*>(&xmlObject);
605 if (!response || !response->hasChildren())
606 throw FatalProfileException("Incoming message was not of the proper type or contains no security token.");
608 const Assertion* token = nullptr;
609 for (vector<XMLObject*>::const_iterator xo = response->getUnknownXMLObjects().begin(); xo != response->getUnknownXMLObjects().end(); ++xo) {
610 // Look for the RequestedSecurityToken element.
611 if (XMLString::equals((*xo)->getElementQName().getLocalPart(), RequestedSecurityToken)) {
612 response = dynamic_cast<const ElementProxy*>(*xo);
613 if (!response || !response->hasChildren())
614 throw FatalProfileException("Token wrapper element did not contain a security token.");
615 token = dynamic_cast<const Assertion*>(response->getUnknownXMLObjects().front());
616 if (!token || !token->getSignature())
617 throw FatalProfileException("Incoming message did not contain a signed SAML assertion.");
622 // Extract message and issuer details from assertion.
623 extractMessageDetails(*token, m_protocol.get(), policy);
625 // Populate recipient as audience.
626 const EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : nullptr;
627 policy.getAudiences().push_back(application.getRelyingParty(entity)->getXMLString("entityID").second);
629 // Run the policy over the assertion. Handles replay, freshness, and
630 // signature verification, assuming the relevant rules are configured,
631 // along with condition enforcement.
632 policy.evaluate(*token, &httpRequest);
634 // If no security is in place now, we kick it.
635 if (!policy.isAuthenticated())
636 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
638 saml1::NameIdentifier* saml1name=nullptr;
639 saml2::NameID* saml2name=nullptr;
640 const XMLCh* authMethod=nullptr;
641 const XMLCh* authInstant=nullptr;
642 time_t now = time(nullptr), sessionExp = 0;
643 const PropertySet* sessionProps = application.getPropertySet("Sessions");
645 const saml1::Assertion* saml1token = dynamic_cast<const saml1::Assertion*>(token);
647 // Now do profile validation to ensure we can use it for SSO.
648 if (!saml1token->getConditions() || !saml1token->getConditions()->getNotBefore() || !saml1token->getConditions()->getNotOnOrAfter())
649 throw FatalProfileException("Assertion did not contain time conditions.");
650 else if (saml1token->getAuthenticationStatements().empty())
651 throw FatalProfileException("Assertion did not contain an authentication statement.");
653 // authnskew allows rejection of SSO if AuthnInstant is too old.
654 pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);
656 const saml1::AuthenticationStatement* ssoStatement=saml1token->getAuthenticationStatements().front();
657 if (authnskew.first && authnskew.second &&
658 ssoStatement->getAuthenticationInstant() && (now - ssoStatement->getAuthenticationInstantEpoch() > authnskew.second))
659 throw FatalProfileException("The gap between now and the time you logged into your identity provider exceeds the limit.");
662 saml1::SubjectLocality* locality = ssoStatement->getSubjectLocality();
663 if (locality && locality->getIPAddress()) {
664 auto_ptr_char ip(locality->getIPAddress());
665 checkAddress(application, httpRequest, ip.get());
668 saml1name = ssoStatement->getSubject()->getNameIdentifier();
669 authMethod = ssoStatement->getAuthenticationMethod();
670 if (ssoStatement->getAuthenticationInstant())
671 authInstant = ssoStatement->getAuthenticationInstant()->getRawData();
673 // Session expiration.
674 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
675 if (!lifetime.first || lifetime.second == 0)
676 lifetime.second = 28800;
677 sessionExp = now + lifetime.second;
680 const saml2::Assertion* saml2token = dynamic_cast<const saml2::Assertion*>(token);
682 throw FatalProfileException("Incoming message did not contain a recognized type of SAML assertion.");
684 // Now do profile validation to ensure we can use it for SSO.
685 if (!saml2token->getConditions() || !saml2token->getConditions()->getNotBefore() || !saml2token->getConditions()->getNotOnOrAfter())
686 throw FatalProfileException("Assertion did not contain time conditions.");
687 else if (saml2token->getAuthnStatements().empty())
688 throw FatalProfileException("Assertion did not contain an authentication statement.");
690 // authnskew allows rejection of SSO if AuthnInstant is too old.
691 pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);
693 const saml2::AuthnStatement* ssoStatement=saml2token->getAuthnStatements().front();
694 if (authnskew.first && authnskew.second &&
695 ssoStatement->getAuthnInstant() && (now - ssoStatement->getAuthnInstantEpoch() > authnskew.second))
696 throw FatalProfileException("The gap between now and the time you logged into your identity provider exceeds the limit.");
699 saml2::SubjectLocality* locality = ssoStatement->getSubjectLocality();
700 if (locality && locality->getAddress()) {
701 auto_ptr_char ip(locality->getAddress());
702 checkAddress(application, httpRequest, ip.get());
705 saml2name = saml2token->getSubject() ? saml2token->getSubject()->getNameID() : nullptr;
706 if (ssoStatement->getAuthnContext() && ssoStatement->getAuthnContext()->getAuthnContextClassRef())
707 authMethod = ssoStatement->getAuthnContext()->getAuthnContextClassRef()->getReference();
708 if (ssoStatement->getAuthnInstant())
709 authInstant = ssoStatement->getAuthnInstant()->getRawData();
711 // Session expiration for SAML 2.0 is jointly IdP- and SP-driven.
712 sessionExp = ssoStatement->getSessionNotOnOrAfter() ? ssoStatement->getSessionNotOnOrAfterEpoch() : 0;
713 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
714 if (!lifetime.first || lifetime.second == 0)
715 lifetime.second = 28800;
717 sessionExp = now + lifetime.second; // IdP says nothing, calulate based on SP.
719 sessionExp = min(sessionExp, now + lifetime.second); // Use the lowest.
722 m_log.debug("ADFS profile processing completed successfully");
724 // We've successfully "accepted" the SSO token.
725 // To complete processing, we need to extract and resolve attributes and then create the session.
727 // Normalize a SAML 1.x NameIdentifier...
728 auto_ptr<saml2::NameID> nameid(saml1name ? saml2::NameIDBuilder::buildNameID() : nullptr);
730 nameid->setName(saml1name->getName());
731 nameid->setFormat(saml1name->getFormat());
732 nameid->setNameQualifier(saml1name->getNameQualifier());
735 // The context will handle deleting attributes and new tokens.
736 vector<const Assertion*> tokens(1,token);
737 auto_ptr<ResolutionContext> ctx(
740 policy.getIssuerMetadata(),
743 (saml1name ? nameid.get() : saml2name),
751 // Copy over any new tokens, but leave them in the context for cleanup.
752 tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
755 application.getServiceProvider().getSessionCache()->insert(
762 (saml1name ? nameid.get() : saml2name),
768 ctx.get() ? &ctx->getResolvedAttributes() : nullptr
774 pair<bool,long> ADFSLogoutInitiator::run(SPRequest& request, bool isHandler) const
776 // Normally we'd do notifications and session clearage here, but ADFS logout
777 // is missing the needed request/response features, so we have to rely on
778 // the IdP half to notify us back about the logout and do the work there.
779 // Basically we have no way to tell in the Logout receiving handler whether
780 // we initiated the logout or not.
782 Session* session = nullptr;
784 session = request.getSession(false, true, false); // don't cache it and ignore all checks
786 return make_pair(false,0L);
788 // We only handle ADFS sessions.
789 if (!XMLString::equals(session->getProtocol(), WSFED_NS) || !session->getEntityID()) {
791 return make_pair(false,0L);
794 catch (exception& ex) {
795 m_log.error("error accessing current session: %s", ex.what());
796 return make_pair(false,0L);
799 string entityID(session->getEntityID());
802 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
803 // When out of process, we run natively.
804 return doRequest(request.getApplication(), request, request, session);
807 // When not out of process, we remote the request.
809 vector<string> headers(1,"Cookie");
810 DDF out,in = wrap(request,&headers);
811 DDFJanitor jin(in), jout(out);
812 out=request.getServiceProvider().getListenerService()->send(in);
813 return unwrap(request, out);
817 void ADFSLogoutInitiator::receive(DDF& in, ostream& out)
820 // Defer to base class for notifications
821 if (in["notify"].integer() == 1)
822 return LogoutHandler::receive(in, out);
825 const char* aid=in["application_id"].string();
826 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
828 // Something's horribly wrong.
829 m_log.error("couldn't find application (%s) for logout", aid ? aid : "(missing)");
830 throw ConfigurationException("Unable to locate application for logout, deleted?");
833 // Unpack the request.
834 auto_ptr<HTTPRequest> req(getRequest(in));
836 // Set up a response shim.
838 DDFJanitor jout(ret);
839 auto_ptr<HTTPResponse> resp(getResponse(ret));
841 Session* session = nullptr;
843 session = app->getServiceProvider().getSessionCache()->find(*app, *req.get(), nullptr, nullptr);
845 catch (exception& ex) {
846 m_log.error("error accessing current session: %s", ex.what());
849 // With no session, we just skip the request and let it fall through to an empty struct return.
851 if (session->getEntityID()) {
852 // Since we're remoted, the result should either be a throw, which we pass on,
853 // a false/0 return, which we just return as an empty structure, or a response/redirect,
854 // which we capture in the facade and send back.
855 doRequest(*app, *req.get(), *resp.get(), session);
858 m_log.error("no issuing entityID found in session");
860 app->getServiceProvider().getSessionCache()->remove(*app, *req.get(), resp.get());
865 throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
869 pair<bool,long> ADFSLogoutInitiator::doRequest(
870 const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse, Session* session
873 // Do back channel notification.
874 vector<string> sessions(1, session->getID());
875 if (!notifyBackChannel(application, httpRequest.getRequestURL(), sessions, false)) {
877 application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
878 return sendLogoutPage(application, httpRequest, httpResponse, "partial");
882 pair<bool,long> ret = make_pair(false,0L);
885 // With a session in hand, we can create a request message, if we can find a compatible endpoint.
886 MetadataProvider* m=application.getMetadataProvider();
887 Locker metadataLocker(m);
888 MetadataProviderCriteria mc(application, session->getEntityID(), &IDPSSODescriptor::ELEMENT_QNAME, m_binding.get());
889 pair<const EntityDescriptor*,const RoleDescriptor*> entity=m->getEntityDescriptor(mc);
891 throw MetadataException(
892 "Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", session->getEntityID())
895 else if (!entity.second) {
896 throw MetadataException(
897 "Unable to locate ADFS IdP role for identity provider ($entityID).", namedparams(1, "entityID", session->getEntityID())
901 const EndpointType* ep = EndpointManager<SingleLogoutService>(
902 dynamic_cast<const IDPSSODescriptor*>(entity.second)->getSingleLogoutServices()
903 ).getByBinding(m_binding.get());
905 throw MetadataException(
906 "Unable to locate ADFS single logout service for identity provider ($entityID).",
907 namedparams(1, "entityID", session->getEntityID())
911 const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
912 const char* returnloc = httpRequest.getParameter("return");
913 auto_ptr_char dest(ep->getLocation());
914 string req=string(dest.get()) + (strchr(dest.get(),'?') ? '&' : '?') + "wa=wsignout1.0";
916 req += "&wreply=" + urlenc->encode(returnloc);
917 ret.second = httpResponse.sendRedirect(req.c_str());
920 catch (exception& ex) {
921 m_log.error("error issuing ADFS logout request: %s", ex.what());
927 application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
932 throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
936 pair<bool,long> ADFSLogout::run(SPRequest& request, bool isHandler) const
938 // Defer to base class for front-channel loop first.
939 // This won't initiate the loop, only continue/end it.
940 pair<bool,long> ret = LogoutHandler::run(request, isHandler);
944 // wa parameter indicates the "action" to perform
945 bool returning = false;
946 const char* param = request.getParameter("wa");
948 if (!strcmp(param, "wsignin1.0"))
949 return m_login.run(request, isHandler);
950 else if (strcmp(param, "wsignout1.0") && strcmp(param, "wsignoutcleanup1.0"))
951 throw FatalProfileException("Unsupported WS-Federation action paremeter ($1).", params(1, param));
953 else if (strcmp(request.getMethod(),"GET") || !request.getParameter("notifying"))
954 throw FatalProfileException("Unsupported request to ADFS protocol endpoint.");
958 param = request.getParameter("wreply");
959 const Application& app = request.getApplication();
962 // Pass control to the first front channel notification point, if any.
963 map<string,string> parammap;
965 parammap["wreply"] = param;
966 pair<bool,long> result = notifyFrontChannel(app, request, request, ¶mmap);
971 // Best effort on back channel and to remove the user agent's session.
972 string session_id = app.getServiceProvider().getSessionCache()->active(app, request);
973 if (!session_id.empty()) {
974 vector<string> sessions(1,session_id);
975 notifyBackChannel(app, request.getRequestURL(), sessions, false);
977 app.getServiceProvider().getSessionCache()->remove(app, request, &request);
979 catch (exception& ex) {
980 m_log.error("error removing session (%s): %s", session_id.c_str(), ex.what());
985 return make_pair(true, request.sendRedirect(param));
986 return sendLogoutPage(app, request, request, "global");