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/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 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 LogoutHandler
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;
225 const char* getType() const {
226 return "LogoutInitiator";
229 const XMLCh* getProtocolFamily() const {
230 return m_binding.get();
234 pair<bool,long> doRequest(const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse, Session* session) const;
237 auto_ptr_XMLCh m_binding;
240 class SHIBSP_DLLLOCAL ADFSLogout : public AbstractHandler, public LogoutHandler
243 ADFSLogout(const DOMElement* e, const char* appId)
244 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".Logout.ADFS")), m_login(e, appId) {
247 m_preserve.push_back("wreply");
248 string address = string(appId) + getString("Location").second + "::run::ADFSLO";
249 setAddress(address.c_str());
252 virtual ~ADFSLogout() {}
254 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
257 void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
258 m_login.generateMetadata(role, handlerURL);
259 const char* loc = getString("Location").second;
260 string hurl(handlerURL);
264 auto_ptr_XMLCh widen(hurl.c_str());
265 SingleLogoutService* ep = SingleLogoutServiceBuilder::buildSingleLogoutService();
266 ep->setLocation(widen.get());
267 ep->setBinding(m_login.getProtocolFamily());
268 role.getSingleLogoutServices().push_back(ep);
271 const char* getType() const {
272 return m_login.getType();
275 const XMLCh* getProtocolFamily() const {
276 return m_login.getProtocolFamily();
280 ADFSConsumer m_login;
283 #if defined (_MSC_VER)
284 #pragma warning( pop )
287 SessionInitiator* ADFSSessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
289 return new ADFSSessionInitiator(p.first, p.second);
292 Handler* ADFSLogoutFactory(const pair<const DOMElement*,const char*>& p)
294 return new ADFSLogout(p.first, p.second);
297 Handler* ADFSLogoutInitiatorFactory(const pair<const DOMElement*,const char*>& p)
299 return new ADFSLogoutInitiator(p.first, p.second);
302 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);
303 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);
306 extern "C" int ADFS_EXPORTS xmltooling_extension_init(void*)
308 SPConfig& conf=SPConfig::getConfig();
309 conf.SessionInitiatorManager.registerFactory("ADFS", ADFSSessionInitiatorFactory);
310 conf.LogoutInitiatorManager.registerFactory("ADFS", ADFSLogoutInitiatorFactory);
311 conf.AssertionConsumerServiceManager.registerFactory("ADFS", ADFSLogoutFactory);
312 conf.AssertionConsumerServiceManager.registerFactory(WSFED_NS, ADFSLogoutFactory);
314 SAMLConfig::getConfig().MessageDecoderManager.registerFactory(WSFED_NS, ADFSDecoderFactory);
315 XMLObjectBuilder::registerBuilder(xmltooling::QName(WSTRUST_NS,"RequestedSecurityToken"), new AnyElementBuilder());
316 XMLObjectBuilder::registerBuilder(xmltooling::QName(WSTRUST_NS,"RequestSecurityTokenResponse"), new AnyElementBuilder());
321 extern "C" void ADFS_EXPORTS xmltooling_extension_term()
323 /* should get unregistered during normal shutdown...
324 SPConfig& conf=SPConfig::getConfig();
325 conf.SessionInitiatorManager.deregisterFactory("ADFS");
326 conf.LogoutInitiatorManager.deregisterFactory("ADFS");
327 conf.AssertionConsumerServiceManager.deregisterFactory("ADFS");
328 conf.AssertionConsumerServiceManager.deregisterFactory(WSFED_NS);
330 SAMLConfig::getConfig().MessageDecoderManager.deregisterFactory(WSFED_NS);
335 pair<bool,long> ADFSSessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
337 // We have to know the IdP to function.
338 if (entityID.empty() || !checkCompatibility(request, isHandler))
339 return make_pair(false,0L);
342 pair<bool,const char*> prop;
343 pair<bool,const char*> acClass;
344 const Handler* ACS=nullptr;
345 const Application& app=request.getApplication();
348 prop.second = request.getParameter("acsIndex");
349 if (prop.second && *prop.second) {
350 ACS = app.getAssertionConsumerServiceByIndex(atoi(prop.second));
352 request.log(SPRequest::SPWarn, "invalid acsIndex specified in request, using acsIndex property");
355 prop = getString("target", request);
357 target = prop.second;
359 // Since we're passing the ACS by value, we need to compute the return URL,
360 // so we'll need the target resource for real.
361 recoverRelayState(app, request, request, target, false);
363 acClass = getString("authnContextClassRef", request);
366 // Check for a hardwired target value in the map or handler.
367 prop = getString("target", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
369 target = prop.second;
371 target = request.getRequestURL();
373 acClass = getString("authnContextClassRef", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
377 pair<bool,unsigned int> index = getUnsignedInt("acsIndex", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
379 ACS = app.getAssertionConsumerServiceByIndex(index.second);
381 request.log(SPRequest::SPWarn, "invalid acsIndex property, using default ACS location");
384 const vector<const Handler*>& endpoints = app.getAssertionConsumerServicesByBinding(m_binding.get());
385 if (endpoints.empty()) {
386 m_log.error("unable to locate a compatible ACS");
387 throw ConfigurationException("Unable to locate an ADFS-compatible ACS in the configuration.");
389 ACS = endpoints.front();
393 // Validate the ACS for use with this protocol.
394 if (!XMLString::equals(getProtocolFamily(), ACS->getProtocolFamily())) {
395 m_log.error("configured or requested ACS has non-ADFS binding");
396 throw ConfigurationException("Configured or requested ACS has non-ADFS binding ($1).", params(1, ACS->getString("Binding").second));
399 // Since we're not passing by index, we need to fully compute the return URL.
400 // Compute the ACS URL. We add the ACS location to the base handlerURL.
401 string ACSloc=request.getHandlerURL(target.c_str());
402 prop = ACS->getString("Location");
404 ACSloc += prop.second;
407 // We may already have RelayState set if we looped back here,
408 // but we've turned it back into a resource by this point, so if there's
409 // a target on the URL, reset to that value.
410 prop.second = request.getParameter("target");
411 if (prop.second && *prop.second)
412 target = prop.second;
415 m_log.debug("attempting to initiate session using ADFS with provider (%s)", entityID.c_str());
417 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
418 // Out of process means the POST data via the request can be exposed directly to the private method.
419 // The method will handle POST preservation if necessary *before* issuing the response, but only if
420 // it dispatches to an IdP.
421 return doRequest(app, &request, request, entityID.c_str(), ACSloc.c_str(), (acClass.first ? acClass.second : nullptr), target);
425 DDF out,in = DDF(m_address.c_str()).structure();
426 DDFJanitor jin(in), jout(out);
427 in.addmember("application_id").string(app.getId());
428 in.addmember("entity_id").string(entityID.c_str());
429 in.addmember("acsLocation").string(ACSloc.c_str());
431 in.addmember("RelayState").unsafe_string(target.c_str());
433 in.addmember("authnContextClassRef").string(acClass.second);
435 // Remote the processing.
436 out = request.getServiceProvider().getListenerService()->send(in);
437 return unwrap(request, out);
440 pair<bool,long> ADFSSessionInitiator::unwrap(SPRequest& request, DDF& out) const
442 // See if there's any response to send back.
443 if (!out["redirect"].isnull() || !out["response"].isnull()) {
444 // If so, we're responsible for handling the POST data, probably by dropping a cookie.
445 preservePostData(request.getApplication(), request, request, out["RelayState"].string());
447 return RemotedHandler::unwrap(request, out);
450 void ADFSSessionInitiator::receive(DDF& in, ostream& out)
453 const char* aid=in["application_id"].string();
454 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
456 // Something's horribly wrong.
457 m_log.error("couldn't find application (%s) to generate ADFS request", aid ? aid : "(missing)");
458 throw ConfigurationException("Unable to locate application for new session, deleted?");
461 const char* entityID = in["entity_id"].string();
462 const char* acsLocation = in["acsLocation"].string();
463 if (!entityID || !acsLocation)
464 throw ConfigurationException("No entityID or acsLocation parameter supplied to remoted SessionInitiator.");
467 DDFJanitor jout(ret);
469 // Wrap the outgoing object with a Response facade.
470 auto_ptr<HTTPResponse> http(getResponse(ret));
472 string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");
474 // Since we're remoted, the result should either be a throw, which we pass on,
475 // a false/0 return, which we just return as an empty structure, or a response/redirect,
476 // which we capture in the facade and send back.
477 doRequest(*app, nullptr, *http.get(), entityID, acsLocation, in["authnContextClassRef"].string(), relayState);
480 ret.addmember("RelayState").unsafe_string(relayState.c_str());
484 pair<bool,long> ADFSSessionInitiator::doRequest(
485 const Application& app,
486 const HTTPRequest* httpRequest,
487 HTTPResponse& httpResponse,
488 const char* entityID,
489 const char* acsLocation,
490 const char* authnContextClassRef,
495 // Use metadata to invoke the SSO service directly.
496 MetadataProvider* m=app.getMetadataProvider();
498 MetadataProviderCriteria mc(app, entityID, &IDPSSODescriptor::ELEMENT_QNAME, m_binding.get());
499 pair<const EntityDescriptor*,const RoleDescriptor*> entity=m->getEntityDescriptor(mc);
501 m_log.warn("unable to locate metadata for provider (%s)", entityID);
502 throw MetadataException("Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", entityID));
504 else if (!entity.second) {
505 m_log.log(getParent() ? Priority::INFO : Priority::WARN, "unable to locate ADFS-aware identity provider role for provider (%s)", entityID);
507 return make_pair(false,0L);
508 throw MetadataException("Unable to locate ADFS-aware identity provider role for provider ($entityID)", namedparams(1, "entityID", entityID));
510 const EndpointType* ep = EndpointManager<SingleSignOnService>(
511 dynamic_cast<const IDPSSODescriptor*>(entity.second)->getSingleSignOnServices()
512 ).getByBinding(m_binding.get());
514 m_log.warn("unable to locate compatible SSO service for provider (%s)", entityID);
516 return make_pair(false,0L);
517 throw MetadataException("Unable to locate compatible SSO service for provider ($entityID)", namedparams(1, "entityID", entityID));
520 preserveRelayState(app, httpResponse, relayState);
523 time_t epoch=time(nullptr);
524 #ifndef HAVE_GMTIME_R
525 struct tm* ptime=gmtime(&epoch);
528 struct tm* ptime=gmtime_r(&epoch,&res);
531 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
533 auto_ptr_char dest(ep->getLocation());
534 const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
536 string req=string(dest.get()) + (strchr(dest.get(),'?') ? '&' : '?') + "wa=wsignin1.0&wreply=" + urlenc->encode(acsLocation) +
537 "&wct=" + urlenc->encode(timebuf) + "&wtrealm=" + urlenc->encode(app.getString("entityID").second);
538 if (authnContextClassRef)
539 req += "&wauth=" + urlenc->encode(authnContextClassRef);
540 if (!relayState.empty())
541 req += "&wctx=" + urlenc->encode(relayState.c_str());
544 // If the request object is available, we're responsible for the POST data.
545 preservePostData(app, *httpRequest, httpResponse, relayState.c_str());
548 return make_pair(true, httpResponse.sendRedirect(req.c_str()));
550 return make_pair(false,0L);
556 XMLObject* ADFSDecoder::decode(string& relayState, const GenericRequest& genericRequest, SecurityPolicy& policy) const
559 xmltooling::NDC ndc("decode");
561 Category& log = Category::getInstance(SHIBSP_LOGCAT".MessageDecoder.ADFS");
563 log.debug("validating input");
564 const HTTPRequest* httpRequest=dynamic_cast<const HTTPRequest*>(&genericRequest);
566 throw BindingException("Unable to cast request object to HTTPRequest type.");
567 if (strcmp(httpRequest->getMethod(),"POST"))
568 throw BindingException("Invalid HTTP method ($1).", params(1, httpRequest->getMethod()));
569 const char* param = httpRequest->getParameter("wa");
570 if (!param || strcmp(param, "wsignin1.0"))
571 throw BindingException("Missing or invalid wa parameter (should be wsignin1.0).");
572 param = httpRequest->getParameter("wctx");
576 param = httpRequest->getParameter("wresult");
578 throw BindingException("Request missing wresult parameter.");
580 log.debug("decoded ADFS response:\n%s", param);
582 // Parse and bind the document into an XMLObject.
583 istringstream is(param);
584 DOMDocument* doc = (policy.getValidating() ? XMLToolingConfig::getConfig().getValidatingParser()
585 : XMLToolingConfig::getConfig().getParser()).parse(is);
586 XercesJanitor<DOMDocument> janitor(doc);
587 auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
590 if (!XMLString::equals(xmlObject->getElementQName().getLocalPart(), RequestSecurityTokenResponse)) {
591 log.error("unrecognized root element on message: %s", xmlObject->getElementQName().toString().c_str());
592 throw BindingException("Decoded message was not of the appropriate type.");
595 SchemaValidators.validate(xmlObject.get());
597 // Skip policy step here, there's no security in the wrapper.
598 // policy.evaluate(*xmlObject.get(), &genericRequest);
600 return xmlObject.release();
603 void ADFSConsumer::implementProtocol(
604 const Application& application,
605 const HTTPRequest& httpRequest,
606 HTTPResponse& httpResponse,
607 SecurityPolicy& policy,
609 const XMLObject& xmlObject
612 // Implementation of ADFS profile.
613 m_log.debug("processing message against ADFS Passive Requester profile");
615 // With ADFS, all the security comes from the assertion, which is two levels down in the message.
617 const ElementProxy* response = dynamic_cast<const ElementProxy*>(&xmlObject);
618 if (!response || !response->hasChildren())
619 throw FatalProfileException("Incoming message was not of the proper type or contains no security token.");
621 const Assertion* token = nullptr;
622 for (vector<XMLObject*>::const_iterator xo = response->getUnknownXMLObjects().begin(); xo != response->getUnknownXMLObjects().end(); ++xo) {
623 // Look for the RequestedSecurityToken element.
624 if (XMLString::equals((*xo)->getElementQName().getLocalPart(), RequestedSecurityToken)) {
625 response = dynamic_cast<const ElementProxy*>(*xo);
626 if (!response || !response->hasChildren())
627 throw FatalProfileException("Token wrapper element did not contain a security token.");
628 token = dynamic_cast<const Assertion*>(response->getUnknownXMLObjects().front());
629 if (!token || !token->getSignature())
630 throw FatalProfileException("Incoming message did not contain a signed SAML assertion.");
635 // Extract message and issuer details from assertion.
636 extractMessageDetails(*token, m_protocol.get(), policy);
638 // Populate recipient as audience.
639 const EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : nullptr;
640 policy.getAudiences().push_back(application.getRelyingParty(entity)->getXMLString("entityID").second);
642 // Run the policy over the assertion. Handles replay, freshness, and
643 // signature verification, assuming the relevant rules are configured,
644 // along with condition enforcement.
645 policy.evaluate(*token, &httpRequest);
647 // If no security is in place now, we kick it.
648 if (!policy.isAuthenticated())
649 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
651 saml1::NameIdentifier* saml1name=nullptr;
652 saml2::NameID* saml2name=nullptr;
653 const XMLCh* authMethod=nullptr;
654 const XMLCh* authInstant=nullptr;
655 time_t now = time(nullptr), sessionExp = 0;
656 const PropertySet* sessionProps = application.getPropertySet("Sessions");
658 const saml1::Assertion* saml1token = dynamic_cast<const saml1::Assertion*>(token);
660 // Now do profile validation to ensure we can use it for SSO.
661 if (!saml1token->getConditions() || !saml1token->getConditions()->getNotBefore() || !saml1token->getConditions()->getNotOnOrAfter())
662 throw FatalProfileException("Assertion did not contain time conditions.");
663 else if (saml1token->getAuthenticationStatements().empty())
664 throw FatalProfileException("Assertion did not contain an authentication statement.");
666 // authnskew allows rejection of SSO if AuthnInstant is too old.
667 pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);
669 const saml1::AuthenticationStatement* ssoStatement=saml1token->getAuthenticationStatements().front();
670 if (authnskew.first && authnskew.second &&
671 ssoStatement->getAuthenticationInstant() && (now - ssoStatement->getAuthenticationInstantEpoch() > authnskew.second))
672 throw FatalProfileException("The gap between now and the time you logged into your identity provider exceeds the limit.");
675 saml1::SubjectLocality* locality = ssoStatement->getSubjectLocality();
676 if (locality && locality->getIPAddress()) {
677 auto_ptr_char ip(locality->getIPAddress());
678 checkAddress(application, httpRequest, ip.get());
681 saml1name = ssoStatement->getSubject()->getNameIdentifier();
682 authMethod = ssoStatement->getAuthenticationMethod();
683 if (ssoStatement->getAuthenticationInstant())
684 authInstant = ssoStatement->getAuthenticationInstant()->getRawData();
686 // Session expiration.
687 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
688 if (!lifetime.first || lifetime.second == 0)
689 lifetime.second = 28800;
690 sessionExp = now + lifetime.second;
693 const saml2::Assertion* saml2token = dynamic_cast<const saml2::Assertion*>(token);
695 throw FatalProfileException("Incoming message did not contain a recognized type of SAML assertion.");
697 // Now do profile validation to ensure we can use it for SSO.
698 if (!saml2token->getConditions() || !saml2token->getConditions()->getNotBefore() || !saml2token->getConditions()->getNotOnOrAfter())
699 throw FatalProfileException("Assertion did not contain time conditions.");
700 else if (saml2token->getAuthnStatements().empty())
701 throw FatalProfileException("Assertion did not contain an authentication statement.");
703 // authnskew allows rejection of SSO if AuthnInstant is too old.
704 pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);
706 const saml2::AuthnStatement* ssoStatement=saml2token->getAuthnStatements().front();
707 if (authnskew.first && authnskew.second &&
708 ssoStatement->getAuthnInstant() && (now - ssoStatement->getAuthnInstantEpoch() > authnskew.second))
709 throw FatalProfileException("The gap between now and the time you logged into your identity provider exceeds the limit.");
712 saml2::SubjectLocality* locality = ssoStatement->getSubjectLocality();
713 if (locality && locality->getAddress()) {
714 auto_ptr_char ip(locality->getAddress());
715 checkAddress(application, httpRequest, ip.get());
718 saml2name = saml2token->getSubject() ? saml2token->getSubject()->getNameID() : nullptr;
719 if (ssoStatement->getAuthnContext() && ssoStatement->getAuthnContext()->getAuthnContextClassRef())
720 authMethod = ssoStatement->getAuthnContext()->getAuthnContextClassRef()->getReference();
721 if (ssoStatement->getAuthnInstant())
722 authInstant = ssoStatement->getAuthnInstant()->getRawData();
724 // Session expiration for SAML 2.0 is jointly IdP- and SP-driven.
725 sessionExp = ssoStatement->getSessionNotOnOrAfter() ? ssoStatement->getSessionNotOnOrAfterEpoch() : 0;
726 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
727 if (!lifetime.first || lifetime.second == 0)
728 lifetime.second = 28800;
730 sessionExp = now + lifetime.second; // IdP says nothing, calulate based on SP.
732 sessionExp = min(sessionExp, now + lifetime.second); // Use the lowest.
735 m_log.debug("ADFS profile processing completed successfully");
737 // We've successfully "accepted" the SSO token.
738 // To complete processing, we need to extract and resolve attributes and then create the session.
740 // Normalize a SAML 1.x NameIdentifier...
741 auto_ptr<saml2::NameID> nameid(saml1name ? saml2::NameIDBuilder::buildNameID() : nullptr);
743 nameid->setName(saml1name->getName());
744 nameid->setFormat(saml1name->getFormat());
745 nameid->setNameQualifier(saml1name->getNameQualifier());
748 // The context will handle deleting attributes and new tokens.
749 vector<const Assertion*> tokens(1,token);
750 auto_ptr<ResolutionContext> ctx(
753 policy.getIssuerMetadata(),
756 (saml1name ? nameid.get() : saml2name),
764 // Copy over any new tokens, but leave them in the context for cleanup.
765 tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
768 application.getServiceProvider().getSessionCache()->insert(
775 (saml1name ? nameid.get() : saml2name),
781 ctx.get() ? &ctx->getResolvedAttributes() : nullptr
787 pair<bool,long> ADFSLogoutInitiator::run(SPRequest& request, bool isHandler) const
789 // Normally we'd do notifications and session clearage here, but ADFS logout
790 // is missing the needed request/response features, so we have to rely on
791 // the IdP half to notify us back about the logout and do the work there.
792 // Basically we have no way to tell in the Logout receiving handler whether
793 // we initiated the logout or not.
795 Session* session = nullptr;
797 session = request.getSession(false, true, false); // don't cache it and ignore all checks
799 return make_pair(false,0L);
801 // We only handle ADFS sessions.
802 if (!XMLString::equals(session->getProtocol(), WSFED_NS) || !session->getEntityID()) {
804 return make_pair(false,0L);
807 catch (exception& ex) {
808 m_log.error("error accessing current session: %s", ex.what());
809 return make_pair(false,0L);
812 string entityID(session->getEntityID());
815 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
816 // When out of process, we run natively.
817 return doRequest(request.getApplication(), request, request, session);
820 // When not out of process, we remote the request.
822 vector<string> headers(1,"Cookie");
823 DDF out,in = wrap(request,&headers);
824 DDFJanitor jin(in), jout(out);
825 out=request.getServiceProvider().getListenerService()->send(in);
826 return unwrap(request, out);
830 void ADFSLogoutInitiator::receive(DDF& in, ostream& out)
833 // Defer to base class for notifications
834 if (in["notify"].integer() == 1)
835 return LogoutHandler::receive(in, out);
838 const char* aid=in["application_id"].string();
839 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
841 // Something's horribly wrong.
842 m_log.error("couldn't find application (%s) for logout", aid ? aid : "(missing)");
843 throw ConfigurationException("Unable to locate application for logout, deleted?");
846 // Unpack the request.
847 auto_ptr<HTTPRequest> req(getRequest(in));
849 // Set up a response shim.
851 DDFJanitor jout(ret);
852 auto_ptr<HTTPResponse> resp(getResponse(ret));
854 Session* session = nullptr;
856 session = app->getServiceProvider().getSessionCache()->find(*app, *req.get(), nullptr, nullptr);
858 catch (exception& ex) {
859 m_log.error("error accessing current session: %s", ex.what());
862 // With no session, we just skip the request and let it fall through to an empty struct return.
864 if (session->getEntityID()) {
865 // Since we're remoted, the result should either be a throw, which we pass on,
866 // a false/0 return, which we just return as an empty structure, or a response/redirect,
867 // which we capture in the facade and send back.
868 doRequest(*app, *req.get(), *resp.get(), session);
871 m_log.error("no issuing entityID found in session");
873 app->getServiceProvider().getSessionCache()->remove(*app, *req.get(), resp.get());
878 throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
882 pair<bool,long> ADFSLogoutInitiator::doRequest(
883 const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse, Session* session
886 // Do back channel notification.
887 vector<string> sessions(1, session->getID());
888 if (!notifyBackChannel(application, httpRequest.getRequestURL(), sessions, false)) {
890 application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
891 return sendLogoutPage(application, httpRequest, httpResponse, "partial");
895 pair<bool,long> ret = make_pair(false,0L);
898 // With a session in hand, we can create a request message, if we can find a compatible endpoint.
899 MetadataProvider* m=application.getMetadataProvider();
900 Locker metadataLocker(m);
901 MetadataProviderCriteria mc(application, session->getEntityID(), &IDPSSODescriptor::ELEMENT_QNAME, m_binding.get());
902 pair<const EntityDescriptor*,const RoleDescriptor*> entity=m->getEntityDescriptor(mc);
904 throw MetadataException(
905 "Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", session->getEntityID())
908 else if (!entity.second) {
909 throw MetadataException(
910 "Unable to locate ADFS IdP role for identity provider ($entityID).", namedparams(1, "entityID", session->getEntityID())
914 const EndpointType* ep = EndpointManager<SingleLogoutService>(
915 dynamic_cast<const IDPSSODescriptor*>(entity.second)->getSingleLogoutServices()
916 ).getByBinding(m_binding.get());
918 throw MetadataException(
919 "Unable to locate ADFS single logout service for identity provider ($entityID).",
920 namedparams(1, "entityID", session->getEntityID())
924 const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
925 const char* returnloc = httpRequest.getParameter("return");
926 auto_ptr_char dest(ep->getLocation());
927 string req=string(dest.get()) + (strchr(dest.get(),'?') ? '&' : '?') + "wa=wsignout1.0";
929 req += "&wreply=" + urlenc->encode(returnloc);
930 ret.second = httpResponse.sendRedirect(req.c_str());
933 catch (exception& ex) {
934 m_log.error("error issuing ADFS logout request: %s", ex.what());
940 application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
945 throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
949 pair<bool,long> ADFSLogout::run(SPRequest& request, bool isHandler) const
951 // Defer to base class for front-channel loop first.
952 // This won't initiate the loop, only continue/end it.
953 pair<bool,long> ret = LogoutHandler::run(request, isHandler);
957 // wa parameter indicates the "action" to perform
958 bool returning = false;
959 const char* param = request.getParameter("wa");
961 if (!strcmp(param, "wsignin1.0"))
962 return m_login.run(request, isHandler);
963 else if (strcmp(param, "wsignout1.0") && strcmp(param, "wsignoutcleanup1.0"))
964 throw FatalProfileException("Unsupported WS-Federation action paremeter ($1).", params(1, param));
966 else if (strcmp(request.getMethod(),"GET") || !request.getParameter("notifying"))
967 throw FatalProfileException("Unsupported request to ADFS protocol endpoint.");
971 param = request.getParameter("wreply");
972 const Application& app = request.getApplication();
975 // Pass control to the first front channel notification point, if any.
976 map<string,string> parammap;
978 parammap["wreply"] = param;
979 pair<bool,long> result = notifyFrontChannel(app, request, request, ¶mmap);
984 // Best effort on back channel and to remove the user agent's session.
985 string session_id = app.getServiceProvider().getSessionCache()->active(app, request);
986 if (!session_id.empty()) {
987 vector<string> sessions(1,session_id);
988 notifyBackChannel(app, request.getRequestURL(), sessions, false);
990 app.getServiceProvider().getSessionCache()->remove(app, request, &request);
992 catch (exception& ex) {
993 m_log.error("error removing session (%s): %s", session_id.c_str(), ex.what());
998 return make_pair(true, request.sendRedirect(param));
999 return sendLogoutPage(app, request, request, "global");