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)
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/LogoutHandler.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 XMLObject* decode(string& relayState, const GenericRequest& genericRequest, SecurityPolicy& policy) const;
96 void extractMessageDetails(
97 const XMLObject& message, const GenericRequest& req, const XMLCh* protocol, SecurityPolicy& policy
102 MessageDecoder* ADFSDecoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
104 return new ADFSDecoder();
108 #if defined (_MSC_VER)
109 #pragma warning( push )
110 #pragma warning( disable : 4250 )
113 class SHIBSP_DLLLOCAL ADFSSessionInitiator : public SessionInitiator, public AbstractHandler, public RemotedHandler
116 ADFSSessionInitiator(const DOMElement* e, const char* appId)
117 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator.ADFS"), NULL, &m_remapper), m_appId(appId), m_binding(WSFED_NS) {
118 // If Location isn't set, defer address registration until the setParent call.
119 pair<bool,const char*> loc = getString("Location");
121 string address = m_appId + loc.second + "::run::ADFSSI";
122 setAddress(address.c_str());
125 virtual ~ADFSSessionInitiator() {}
127 void setParent(const PropertySet* parent) {
128 DOMPropertySet::setParent(parent);
129 pair<bool,const char*> loc = getString("Location");
131 string address = m_appId + loc.second + "::run::ADFSSI";
132 setAddress(address.c_str());
135 m_log.warn("no Location property in ADFS SessionInitiator (or parent), can't register as remoted handler");
139 void receive(DDF& in, ostream& out);
140 pair<bool,long> unwrap(SPRequest& request, DDF& out) const;
141 pair<bool,long> run(SPRequest& request, string& entityID, bool isHandler=true) const;
144 pair<bool,long> doRequest(
145 const Application& application,
146 const HTTPRequest* httpRequest,
147 HTTPResponse& httpResponse,
148 const char* entityID,
149 const char* acsLocation,
150 const char* authnContextClassRef,
154 auto_ptr_XMLCh m_binding;
157 class SHIBSP_DLLLOCAL ADFSConsumer : public shibsp::AssertionConsumerService
160 ADFSConsumer(const DOMElement* e, const char* appId)
161 : shibsp::AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SSO.ADFS"))
163 ,m_protocol(WSFED_NS)
166 virtual ~ADFSConsumer() {}
169 void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
170 AssertionConsumerService::generateMetadata(role, handlerURL);
171 role.addSupport(m_protocol.get());
174 auto_ptr_XMLCh m_protocol;
177 void implementProtocol(
178 const Application& application,
179 const HTTPRequest& httpRequest,
180 HTTPResponse& httpResponse,
181 SecurityPolicy& policy,
182 const PropertySet* settings,
183 const XMLObject& xmlObject
188 class SHIBSP_DLLLOCAL ADFSLogoutInitiator : public AbstractHandler, public LogoutHandler
191 ADFSLogoutInitiator(const DOMElement* e, const char* appId)
192 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".LogoutInitiator.ADFS")), m_appId(appId), m_binding(WSFED_NS) {
193 // If Location isn't set, defer address registration until the setParent call.
194 pair<bool,const char*> loc = getString("Location");
196 string address = m_appId + loc.second + "::run::ADFSLI";
197 setAddress(address.c_str());
200 virtual ~ADFSLogoutInitiator() {}
202 void setParent(const PropertySet* parent) {
203 DOMPropertySet::setParent(parent);
204 pair<bool,const char*> loc = getString("Location");
206 string address = m_appId + loc.second + "::run::ADFSLI";
207 setAddress(address.c_str());
210 m_log.warn("no Location property in ADFS LogoutInitiator (or parent), can't register as remoted handler");
214 void receive(DDF& in, ostream& out);
215 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
218 const char* getType() const {
219 return "LogoutInitiator";
224 pair<bool,long> doRequest(const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse, Session* session) const;
227 auto_ptr_XMLCh m_binding;
230 class SHIBSP_DLLLOCAL ADFSLogout : public AbstractHandler, public LogoutHandler
233 ADFSLogout(const DOMElement* e, const char* appId)
234 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".Logout.ADFS")), m_login(e, appId) {
237 m_preserve.push_back("wreply");
238 string address = string(appId) + getString("Location").second + "::run::ADFSLO";
239 setAddress(address.c_str());
242 virtual ~ADFSLogout() {}
244 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
247 void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
248 m_login.generateMetadata(role, handlerURL);
249 const char* loc = getString("Location").second;
250 string hurl(handlerURL);
254 auto_ptr_XMLCh widen(hurl.c_str());
255 SingleLogoutService* ep = SingleLogoutServiceBuilder::buildSingleLogoutService();
256 ep->setLocation(widen.get());
257 ep->setBinding(m_login.m_protocol.get());
258 role.getSingleLogoutServices().push_back(ep);
261 const char* getType() const {
262 return m_login.getType();
267 ADFSConsumer m_login;
270 #if defined (_MSC_VER)
271 #pragma warning( pop )
274 SessionInitiator* ADFSSessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
276 return new ADFSSessionInitiator(p.first, p.second);
279 Handler* ADFSLogoutFactory(const pair<const DOMElement*,const char*>& p)
281 return new ADFSLogout(p.first, p.second);
284 Handler* ADFSLogoutInitiatorFactory(const pair<const DOMElement*,const char*>& p)
286 return new ADFSLogoutInitiator(p.first, p.second);
289 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);
290 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);
293 extern "C" int ADFS_EXPORTS xmltooling_extension_init(void*)
295 SPConfig& conf=SPConfig::getConfig();
296 conf.SessionInitiatorManager.registerFactory("ADFS", ADFSSessionInitiatorFactory);
297 conf.LogoutInitiatorManager.registerFactory("ADFS", ADFSLogoutInitiatorFactory);
298 conf.AssertionConsumerServiceManager.registerFactory("ADFS", ADFSLogoutFactory);
299 conf.AssertionConsumerServiceManager.registerFactory(WSFED_NS, ADFSLogoutFactory);
301 SAMLConfig::getConfig().MessageDecoderManager.registerFactory(WSFED_NS, ADFSDecoderFactory);
302 XMLObjectBuilder::registerBuilder(xmltooling::QName(WSTRUST_NS,"RequestedSecurityToken"), new AnyElementBuilder());
303 XMLObjectBuilder::registerBuilder(xmltooling::QName(WSTRUST_NS,"RequestSecurityTokenResponse"), new AnyElementBuilder());
308 extern "C" void ADFS_EXPORTS xmltooling_extension_term()
310 /* should get unregistered during normal shutdown...
311 SPConfig& conf=SPConfig::getConfig();
312 conf.SessionInitiatorManager.deregisterFactory("ADFS");
313 conf.LogoutInitiatorManager.deregisterFactory("ADFS");
314 conf.AssertionConsumerServiceManager.deregisterFactory("ADFS");
315 conf.AssertionConsumerServiceManager.deregisterFactory(WSFED_NS);
317 SAMLConfig::getConfig().MessageDecoderManager.deregisterFactory(WSFED_NS);
322 pair<bool,long> ADFSSessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
324 // We have to know the IdP to function.
325 if (entityID.empty())
326 return make_pair(false,0L);
329 const Handler* ACS=NULL;
331 pair<bool,const char*> acClass;
332 const Application& app=request.getApplication();
335 option=request.getParameter("acsIndex");
337 ACS = app.getAssertionConsumerServiceByIndex(atoi(option));
339 request.log(SPRequest::SPWarn, "invalid acsIndex specified in request, using acsIndex property");
342 option = request.getParameter("target");
346 // Since we're passing the ACS by value, we need to compute the return URL,
347 // so we'll need the target resource for real.
348 recoverRelayState(request.getApplication(), request, request, target, false);
350 if (acClass.second = request.getParameter("authnContextClassRef"))
351 acClass.first = true;
353 acClass = getString("authnContextClassRef");
356 // We're running as a "virtual handler" from within the filter.
357 // The target resource is the current one and everything else is defaulted.
358 target=request.getRequestURL();
360 const PropertySet* settings = request.getRequestSettings().first;
361 acClass = settings->getString("authnContextClassRef");
363 acClass = getString("authnContextClassRef");
367 pair<bool,unsigned int> index = getUnsignedInt("acsIndex");
369 ACS = app.getAssertionConsumerServiceByIndex(index.second);
371 request.log(SPRequest::SPWarn, "invalid acsIndex property, using default ACS location");
374 const vector<const Handler*>& endpoints = app.getAssertionConsumerServicesByBinding(m_binding.get());
375 if (endpoints.empty()) {
376 m_log.error("unable to locate a compatible ACS");
377 throw ConfigurationException("Unable to locate an ADFS-compatible ACS in the configuration.");
379 ACS = endpoints.front();
383 // Validate the ACS for use with this protocol.
384 pair<bool,const XMLCh*> ACSbinding = ACS->getXMLString("Binding");
385 if (ACSbinding.first) {
386 if (!XMLString::equals(ACSbinding.second, m_binding.get())) {
387 m_log.error("configured or requested ACS has non-ADFS binding");
388 throw ConfigurationException("Configured or requested ACS has non-ADFS binding ($1).", params(1, ACSbinding.second));
392 // Since we're not passing by index, we need to fully compute the return URL.
393 // Compute the ACS URL. We add the ACS location to the base handlerURL.
394 string ACSloc=request.getHandlerURL(target.c_str());
395 pair<bool,const char*> loc=ACS->getString("Location");
396 if (loc.first) ACSloc+=loc.second;
399 // We may already have RelayState set if we looped back here,
400 // but just in case target is a resource, we reset it back.
402 option = request.getParameter("target");
407 m_log.debug("attempting to initiate session using ADFS with provider (%s)", entityID.c_str());
409 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
410 // Out of process means the POST data via the request can be exposed directly to the private method.
411 // The method will handle POST preservation if necessary *before* issuing the response, but only if
412 // it dispatches to an IdP.
413 return doRequest(app, &request, request, entityID.c_str(), ACSloc.c_str(), (acClass.first ? acClass.second : NULL), target);
417 DDF out,in = DDF(m_address.c_str()).structure();
418 DDFJanitor jin(in), jout(out);
419 in.addmember("application_id").string(app.getId());
420 in.addmember("entity_id").string(entityID.c_str());
421 in.addmember("acsLocation").string(ACSloc.c_str());
423 in.addmember("RelayState").unsafe_string(target.c_str());
425 in.addmember("authnContextClassRef").string(acClass.second);
427 // Remote the processing.
428 out = request.getServiceProvider().getListenerService()->send(in);
429 return unwrap(request, out);
432 pair<bool,long> ADFSSessionInitiator::unwrap(SPRequest& request, DDF& out) const
434 // See if there's any response to send back.
435 if (!out["redirect"].isnull() || !out["response"].isnull()) {
436 // If so, we're responsible for handling the POST data, probably by dropping a cookie.
437 preservePostData(request.getApplication(), request, request, out["RelayState"].string());
439 return RemotedHandler::unwrap(request, out);
442 void ADFSSessionInitiator::receive(DDF& in, ostream& out)
445 const char* aid=in["application_id"].string();
446 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
448 // Something's horribly wrong.
449 m_log.error("couldn't find application (%s) to generate ADFS request", aid ? aid : "(missing)");
450 throw ConfigurationException("Unable to locate application for new session, deleted?");
453 const char* entityID = in["entity_id"].string();
454 const char* acsLocation = in["acsLocation"].string();
455 if (!entityID || !acsLocation)
456 throw ConfigurationException("No entityID or acsLocation parameter supplied to remoted SessionInitiator.");
459 DDFJanitor jout(ret);
461 // Wrap the outgoing object with a Response facade.
462 auto_ptr<HTTPResponse> http(getResponse(ret));
464 string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");
466 // Since we're remoted, the result should either be a throw, which we pass on,
467 // a false/0 return, which we just return as an empty structure, or a response/redirect,
468 // which we capture in the facade and send back.
469 doRequest(*app, NULL, *http.get(), entityID, acsLocation, in["authnContextClassRef"].string(), relayState);
472 ret.addmember("RelayState").unsafe_string(relayState.c_str());
476 pair<bool,long> ADFSSessionInitiator::doRequest(
477 const Application& app,
478 const HTTPRequest* httpRequest,
479 HTTPResponse& httpResponse,
480 const char* entityID,
481 const char* acsLocation,
482 const char* authnContextClassRef,
487 // Use metadata to invoke the SSO service directly.
488 MetadataProvider* m=app.getMetadataProvider();
490 MetadataProviderCriteria mc(app, entityID, &IDPSSODescriptor::ELEMENT_QNAME, m_binding.get());
491 pair<const EntityDescriptor*,const RoleDescriptor*> entity=m->getEntityDescriptor(mc);
493 m_log.warn("unable to locate metadata for provider (%s)", entityID);
494 throw MetadataException("Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", entityID));
496 else if (!entity.second) {
497 m_log.log(getParent() ? Priority::INFO : Priority::WARN, "unable to locate ADFS-aware identity provider role for provider (%s)", entityID);
499 return make_pair(false,0L);
500 throw MetadataException("Unable to locate ADFS-aware identity provider role for provider ($entityID)", namedparams(1, "entityID", entityID));
502 const EndpointType* ep = EndpointManager<SingleSignOnService>(
503 dynamic_cast<const IDPSSODescriptor*>(entity.second)->getSingleSignOnServices()
504 ).getByBinding(m_binding.get());
506 m_log.warn("unable to locate compatible SSO service for provider (%s)", entityID);
508 return make_pair(false,0L);
509 throw MetadataException("Unable to locate compatible SSO service for provider ($entityID)", namedparams(1, "entityID", entityID));
512 preserveRelayState(app, httpResponse, relayState);
515 time_t epoch=time(NULL);
516 #ifndef HAVE_GMTIME_R
517 struct tm* ptime=gmtime(&epoch);
520 struct tm* ptime=gmtime_r(&epoch,&res);
523 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
525 auto_ptr_char dest(ep->getLocation());
526 const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
528 string req=string(dest.get()) + (strchr(dest.get(),'?') ? '&' : '?') + "wa=wsignin1.0&wreply=" + urlenc->encode(acsLocation) +
529 "&wct=" + urlenc->encode(timebuf) + "&wtrealm=" + urlenc->encode(app.getString("entityID").second);
530 if (authnContextClassRef)
531 req += "&wauth=" + urlenc->encode(authnContextClassRef);
532 if (!relayState.empty())
533 req += "&wctx=" + urlenc->encode(relayState.c_str());
536 // If the request object is available, we're responsible for the POST data.
537 preservePostData(app, *httpRequest, httpResponse, relayState.c_str());
540 return make_pair(true, httpResponse.sendRedirect(req.c_str()));
542 return make_pair(false,0L);
548 XMLObject* ADFSDecoder::decode(string& relayState, const GenericRequest& genericRequest, SecurityPolicy& policy) const
551 xmltooling::NDC ndc("decode");
553 Category& log = Category::getInstance(SHIBSP_LOGCAT".MessageDecoder.ADFS");
555 log.debug("validating input");
556 const HTTPRequest* httpRequest=dynamic_cast<const HTTPRequest*>(&genericRequest);
558 throw BindingException("Unable to cast request object to HTTPRequest type.");
559 if (strcmp(httpRequest->getMethod(),"POST"))
560 throw BindingException("Invalid HTTP method ($1).", params(1, httpRequest->getMethod()));
561 const char* param = httpRequest->getParameter("wa");
562 if (!param || strcmp(param, "wsignin1.0"))
563 throw BindingException("Missing or invalid wa parameter (should be wsignin1.0).");
564 param = httpRequest->getParameter("wctx");
568 param = httpRequest->getParameter("wresult");
570 throw BindingException("Request missing wresult parameter.");
572 log.debug("decoded ADFS response:\n%s", param);
574 // Parse and bind the document into an XMLObject.
575 istringstream is(param);
576 DOMDocument* doc = (policy.getValidating() ? XMLToolingConfig::getConfig().getValidatingParser()
577 : XMLToolingConfig::getConfig().getParser()).parse(is);
578 XercesJanitor<DOMDocument> janitor(doc);
579 auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
582 if (!XMLString::equals(xmlObject->getElementQName().getLocalPart(), RequestSecurityTokenResponse)) {
583 log.error("unrecognized root element on message: %s", xmlObject->getElementQName().toString().c_str());
584 throw BindingException("Decoded message was not of the appropriate type.");
587 SchemaValidators.validate(xmlObject.get());
589 // Skip policy step here, there's no security in the wrapper.
590 // policy.evaluate(*xmlObject.get(), &genericRequest);
592 return xmlObject.release();
595 void ADFSConsumer::implementProtocol(
596 const Application& application,
597 const HTTPRequest& httpRequest,
598 HTTPResponse& httpResponse,
599 SecurityPolicy& policy,
600 const PropertySet* settings,
601 const XMLObject& xmlObject
604 // Implementation of ADFS profile.
605 m_log.debug("processing message against ADFS Passive Requester profile");
607 // With ADFS, all the security comes from the assertion, which is two levels down in the message.
609 const ElementProxy* response = dynamic_cast<const ElementProxy*>(&xmlObject);
610 if (!response || !response->hasChildren())
611 throw FatalProfileException("Incoming message was not of the proper type or contains no security token.");
613 const Assertion* token = NULL;
614 for (vector<XMLObject*>::const_iterator xo = response->getUnknownXMLObjects().begin(); xo != response->getUnknownXMLObjects().end(); ++xo) {
615 // Look for the RequestedSecurityToken element.
616 if (XMLString::equals((*xo)->getElementQName().getLocalPart(), RequestedSecurityToken)) {
617 response = dynamic_cast<const ElementProxy*>(*xo);
618 if (!response || !response->hasChildren())
619 throw FatalProfileException("Token wrapper element did not contain a security token.");
620 token = dynamic_cast<const Assertion*>(response->getUnknownXMLObjects().front());
621 if (!token || !token->getSignature())
622 throw FatalProfileException("Incoming message did not contain a signed SAML assertion.");
627 // Extract message and issuer details from assertion.
628 extractMessageDetails(*token, m_protocol.get(), policy);
630 // Populate recipient as audience.
631 const EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL;
632 policy.getAudiences().push_back(application.getRelyingParty(entity)->getXMLString("entityID").second);
634 // Run the policy over the assertion. Handles replay, freshness, and
635 // signature verification, assuming the relevant rules are configured,
636 // along with condition enforcement.
637 policy.evaluate(*token, &httpRequest);
639 // If no security is in place now, we kick it.
640 if (!policy.isAuthenticated())
641 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
643 saml1::NameIdentifier* saml1name=NULL;
644 saml2::NameID* saml2name=NULL;
645 const XMLCh* authMethod=NULL;
646 const XMLCh* authInstant=NULL;
647 time_t now = time(NULL), sessionExp = 0;
648 const PropertySet* sessionProps = application.getPropertySet("Sessions");
650 const saml1::Assertion* saml1token = dynamic_cast<const saml1::Assertion*>(token);
652 // Now do profile validation to ensure we can use it for SSO.
653 if (!saml1token->getConditions() || !saml1token->getConditions()->getNotBefore() || !saml1token->getConditions()->getNotOnOrAfter())
654 throw FatalProfileException("Assertion did not contain time conditions.");
655 else if (saml1token->getAuthenticationStatements().empty())
656 throw FatalProfileException("Assertion did not contain an authentication statement.");
658 // authnskew allows rejection of SSO if AuthnInstant is too old.
659 pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);
661 const saml1::AuthenticationStatement* ssoStatement=saml1token->getAuthenticationStatements().front();
662 if (authnskew.first && authnskew.second &&
663 ssoStatement->getAuthenticationInstant() && (now - ssoStatement->getAuthenticationInstantEpoch() > authnskew.second))
664 throw FatalProfileException("The gap between now and the time you logged into your identity provider exceeds the limit.");
667 saml1::SubjectLocality* locality = ssoStatement->getSubjectLocality();
668 if (locality && locality->getIPAddress()) {
669 auto_ptr_char ip(locality->getIPAddress());
670 checkAddress(application, httpRequest, ip.get());
673 saml1name = ssoStatement->getSubject()->getNameIdentifier();
674 authMethod = ssoStatement->getAuthenticationMethod();
675 if (ssoStatement->getAuthenticationInstant())
676 authInstant = ssoStatement->getAuthenticationInstant()->getRawData();
678 // Session expiration.
679 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
680 if (!lifetime.first || lifetime.second == 0)
681 lifetime.second = 28800;
682 sessionExp = now + lifetime.second;
685 const saml2::Assertion* saml2token = dynamic_cast<const saml2::Assertion*>(token);
687 throw FatalProfileException("Incoming message did not contain a recognized type of SAML assertion.");
689 // Now do profile validation to ensure we can use it for SSO.
690 if (!saml2token->getConditions() || !saml2token->getConditions()->getNotBefore() || !saml2token->getConditions()->getNotOnOrAfter())
691 throw FatalProfileException("Assertion did not contain time conditions.");
692 else if (saml2token->getAuthnStatements().empty())
693 throw FatalProfileException("Assertion did not contain an authentication statement.");
695 // authnskew allows rejection of SSO if AuthnInstant is too old.
696 pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);
698 const saml2::AuthnStatement* ssoStatement=saml2token->getAuthnStatements().front();
699 if (authnskew.first && authnskew.second &&
700 ssoStatement->getAuthnInstant() && (now - ssoStatement->getAuthnInstantEpoch() > authnskew.second))
701 throw FatalProfileException("The gap between now and the time you logged into your identity provider exceeds the limit.");
704 saml2::SubjectLocality* locality = ssoStatement->getSubjectLocality();
705 if (locality && locality->getAddress()) {
706 auto_ptr_char ip(locality->getAddress());
707 checkAddress(application, httpRequest, ip.get());
710 saml2name = saml2token->getSubject() ? saml2token->getSubject()->getNameID() : NULL;
711 if (ssoStatement->getAuthnContext() && ssoStatement->getAuthnContext()->getAuthnContextClassRef())
712 authMethod = ssoStatement->getAuthnContext()->getAuthnContextClassRef()->getReference();
713 if (ssoStatement->getAuthnInstant())
714 authInstant = ssoStatement->getAuthnInstant()->getRawData();
716 // Session expiration for SAML 2.0 is jointly IdP- and SP-driven.
717 sessionExp = ssoStatement->getSessionNotOnOrAfter() ? ssoStatement->getSessionNotOnOrAfterEpoch() : 0;
718 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
719 if (!lifetime.first || lifetime.second == 0)
720 lifetime.second = 28800;
722 sessionExp = now + lifetime.second; // IdP says nothing, calulate based on SP.
724 sessionExp = min(sessionExp, now + lifetime.second); // Use the lowest.
727 m_log.debug("ADFS profile processing completed successfully");
729 // We've successfully "accepted" the SSO token.
730 // To complete processing, we need to extract and resolve attributes and then create the session.
732 // Normalize a SAML 1.x NameIdentifier...
733 auto_ptr<saml2::NameID> nameid(saml1name ? saml2::NameIDBuilder::buildNameID() : NULL);
735 nameid->setName(saml1name->getName());
736 nameid->setFormat(saml1name->getFormat());
737 nameid->setNameQualifier(saml1name->getNameQualifier());
740 // The context will handle deleting attributes and new tokens.
741 vector<const Assertion*> tokens(1,token);
742 auto_ptr<ResolutionContext> ctx(
745 policy.getIssuerMetadata(),
748 (saml1name ? nameid.get() : saml2name),
756 // Copy over any new tokens, but leave them in the context for cleanup.
757 tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
760 application.getServiceProvider().getSessionCache()->insert(
767 (saml1name ? nameid.get() : saml2name),
773 ctx.get() ? &ctx->getResolvedAttributes() : NULL
779 pair<bool,long> ADFSLogoutInitiator::run(SPRequest& request, bool isHandler) const
781 // Normally we'd do notifications and session clearage here, but ADFS logout
782 // is missing the needed request/response features, so we have to rely on
783 // the IdP half to notify us back about the logout and do the work there.
784 // Basically we have no way to tell in the Logout receiving handler whether
785 // we initiated the logout or not.
787 Session* session = NULL;
789 session = request.getSession(false, true, false); // don't cache it and ignore all checks
791 return make_pair(false,0L);
793 // We only handle ADFS sessions.
794 if (!XMLString::equals(session->getProtocol(), WSFED_NS) || !session->getEntityID()) {
796 return make_pair(false,0L);
799 catch (exception& ex) {
800 m_log.error("error accessing current session: %s", ex.what());
801 return make_pair(false,0L);
804 string entityID(session->getEntityID());
807 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
808 // When out of process, we run natively.
809 return doRequest(request.getApplication(), request, request, session);
812 // When not out of process, we remote the request.
814 vector<string> headers(1,"Cookie");
815 DDF out,in = wrap(request,&headers);
816 DDFJanitor jin(in), jout(out);
817 out=request.getServiceProvider().getListenerService()->send(in);
818 return unwrap(request, out);
822 void ADFSLogoutInitiator::receive(DDF& in, ostream& out)
825 // Defer to base class for notifications
826 if (in["notify"].integer() == 1)
827 return LogoutHandler::receive(in, out);
830 const char* aid=in["application_id"].string();
831 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
833 // Something's horribly wrong.
834 m_log.error("couldn't find application (%s) for logout", aid ? aid : "(missing)");
835 throw ConfigurationException("Unable to locate application for logout, deleted?");
838 // Unpack the request.
839 auto_ptr<HTTPRequest> req(getRequest(in));
841 // Set up a response shim.
843 DDFJanitor jout(ret);
844 auto_ptr<HTTPResponse> resp(getResponse(ret));
846 Session* session = NULL;
848 session = app->getServiceProvider().getSessionCache()->find(*app, *req.get(), NULL, NULL);
850 catch (exception& ex) {
851 m_log.error("error accessing current session: %s", ex.what());
854 // With no session, we just skip the request and let it fall through to an empty struct return.
856 if (session->getEntityID()) {
857 // Since we're remoted, the result should either be a throw, which we pass on,
858 // a false/0 return, which we just return as an empty structure, or a response/redirect,
859 // which we capture in the facade and send back.
860 doRequest(*app, *req.get(), *resp.get(), session);
863 m_log.error("no issuing entityID found in session");
865 app->getServiceProvider().getSessionCache()->remove(*app, *req.get(), resp.get());
870 throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
874 pair<bool,long> ADFSLogoutInitiator::doRequest(
875 const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse, Session* session
878 // Do back channel notification.
879 vector<string> sessions(1, session->getID());
880 if (!notifyBackChannel(application, httpRequest.getRequestURL(), sessions, false)) {
882 application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
883 return sendLogoutPage(application, httpRequest, httpResponse, "partial");
887 pair<bool,long> ret = make_pair(false,0L);
890 // With a session in hand, we can create a request message, if we can find a compatible endpoint.
891 MetadataProvider* m=application.getMetadataProvider();
892 Locker metadataLocker(m);
893 MetadataProviderCriteria mc(application, session->getEntityID(), &IDPSSODescriptor::ELEMENT_QNAME, m_binding.get());
894 pair<const EntityDescriptor*,const RoleDescriptor*> entity=m->getEntityDescriptor(mc);
896 throw MetadataException(
897 "Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", session->getEntityID())
900 else if (!entity.second) {
901 throw MetadataException(
902 "Unable to locate ADFS IdP role for identity provider ($entityID).", namedparams(1, "entityID", session->getEntityID())
906 const EndpointType* ep = EndpointManager<SingleLogoutService>(
907 dynamic_cast<const IDPSSODescriptor*>(entity.second)->getSingleLogoutServices()
908 ).getByBinding(m_binding.get());
910 throw MetadataException(
911 "Unable to locate ADFS single logout service for identity provider ($entityID).",
912 namedparams(1, "entityID", session->getEntityID())
916 const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
917 const char* returnloc = httpRequest.getParameter("return");
918 auto_ptr_char dest(ep->getLocation());
919 string req=string(dest.get()) + (strchr(dest.get(),'?') ? '&' : '?') + "wa=wsignout1.0";
921 req += "&wreply=" + urlenc->encode(returnloc);
922 ret.second = httpResponse.sendRedirect(req.c_str());
925 catch (exception& ex) {
926 m_log.error("error issuing ADFS logout request: %s", ex.what());
932 application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
937 throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
941 pair<bool,long> ADFSLogout::run(SPRequest& request, bool isHandler) const
943 // Defer to base class for front-channel loop first.
944 // This won't initiate the loop, only continue/end it.
945 pair<bool,long> ret = LogoutHandler::run(request, isHandler);
949 // wa parameter indicates the "action" to perform
950 bool returning = false;
951 const char* param = request.getParameter("wa");
953 if (!strcmp(param, "wsignin1.0"))
954 return m_login.run(request, isHandler);
955 else if (strcmp(param, "wsignout1.0") && strcmp(param, "wsignoutcleanup1.0"))
956 throw FatalProfileException("Unsupported WS-Federation action paremeter ($1).", params(1, param));
958 else if (strcmp(request.getMethod(),"GET") || !request.getParameter("notifying"))
959 throw FatalProfileException("Unsupported request to ADFS protocol endpoint.");
963 param = request.getParameter("wreply");
964 const Application& app = request.getApplication();
967 // Pass control to the first front channel notification point, if any.
968 map<string,string> parammap;
970 parammap["wreply"] = param;
971 pair<bool,long> result = notifyFrontChannel(app, request, request, ¶mmap);
976 // Best effort on back channel and to remove the user agent's session.
977 string session_id = app.getServiceProvider().getSessionCache()->active(app, request);
978 if (!session_id.empty()) {
979 vector<string> sessions(1,session_id);
980 notifyBackChannel(app, request.getRequestURL(), sessions, false);
982 app.getServiceProvider().getSessionCache()->remove(app, request, &request);
984 catch (exception& ex) {
985 m_log.error("error removing session (%s): %s", session_id.c_str(), ex.what());
990 return make_pair(true, request.sendRedirect(param));
991 return sendLogoutPage(app, request, request, "global");