2 * Licensed to the University Corporation for Advanced Internet
3 * Development, Inc. (UCAID) under one or more contributor license
4 * agreements. See the NOTICE file distributed with this work for
5 * additional information regarding copyright ownership.
7 * UCAID licenses this file to you under the Apache License,
8 * Version 2.0 (the "License"); you may not use this file except
9 * in compliance with the License. You may obtain a copy of the
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17 * either express or implied. See the License for the specific
18 * language governing permissions and limitations under the License.
24 * ADFSv1 extension library.
27 #if defined (_MSC_VER) || defined(__BORLANDC__)
28 # include "config_win32.h"
34 # define _CRT_NONSTDC_NO_DEPRECATE 1
35 # define _CRT_SECURE_NO_DEPRECATE 1
36 # define ADFS_EXPORTS __declspec(dllexport)
41 #include <shibsp/base.h>
42 #include <shibsp/exceptions.h>
43 #include <shibsp/Application.h>
44 #include <shibsp/ServiceProvider.h>
45 #include <shibsp/SessionCache.h>
46 #include <shibsp/SPConfig.h>
47 #include <shibsp/SPRequest.h>
48 #include <shibsp/TransactionLog.h>
49 #include <shibsp/handler/AssertionConsumerService.h>
50 #include <shibsp/handler/LogoutInitiator.h>
51 #include <shibsp/handler/SessionInitiator.h>
52 #include <xmltooling/logging.h>
53 #include <xmltooling/util/DateTime.h>
54 #include <xmltooling/util/NDC.h>
55 #include <xmltooling/util/URLEncoder.h>
56 #include <xmltooling/util/XMLHelper.h>
60 # include <shibsp/attribute/resolver/ResolutionContext.h>
61 # include <shibsp/metadata/MetadataProviderCriteria.h>
62 # include <saml/SAMLConfig.h>
63 # include <saml/exceptions.h>
64 # include <saml/binding/SecurityPolicy.h>
65 # include <saml/saml1/core/Assertions.h>
66 # include <saml/saml2/core/Assertions.h>
67 # include <saml/saml2/metadata/Metadata.h>
68 # include <saml/saml2/metadata/EndpointManager.h>
69 # include <xmltooling/XMLToolingConfig.h>
70 # include <xmltooling/impl/AnyElement.h>
71 # include <xmltooling/util/ParserPool.h>
72 # include <xmltooling/validation/ValidatorSuite.h>
73 using namespace opensaml::saml2md;
75 # define min(a,b) (((a) < (b)) ? (a) : (b))
78 using namespace shibsp;
79 using namespace opensaml;
80 using namespace xmltooling::logging;
81 using namespace xmltooling;
82 using namespace xercesc;
83 using namespace boost;
86 #define WSFED_NS "http://schemas.xmlsoap.org/ws/2003/07/secext"
87 #define WSTRUST_NS "http://schemas.xmlsoap.org/ws/2005/02/trust"
92 class SHIBSP_DLLLOCAL ADFSDecoder : public MessageDecoder
96 ADFSDecoder() : m_ns(WSTRUST_NS) {}
97 virtual ~ADFSDecoder() {}
99 const XMLCh* getProtocolFamily() const {
103 XMLObject* decode(string& relayState, const GenericRequest& genericRequest, SecurityPolicy& policy) const;
106 void extractMessageDetails(
107 const XMLObject& message, const GenericRequest& req, const XMLCh* protocol, SecurityPolicy& policy
112 MessageDecoder* ADFSDecoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
114 return new ADFSDecoder();
118 #if defined (_MSC_VER)
119 #pragma warning( push )
120 #pragma warning( disable : 4250 )
123 class SHIBSP_DLLLOCAL ADFSSessionInitiator : public SessionInitiator, public AbstractHandler, public RemotedHandler
126 ADFSSessionInitiator(const DOMElement* e, const char* appId)
127 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator.ADFS"), nullptr, &m_remapper), m_appId(appId), m_binding(WSFED_NS) {
128 // If Location isn't set, defer address registration until the setParent call.
129 pair<bool,const char*> loc = getString("Location");
131 string address = m_appId + loc.second + "::run::ADFSSI";
132 setAddress(address.c_str());
135 virtual ~ADFSSessionInitiator() {}
137 void setParent(const PropertySet* parent) {
138 DOMPropertySet::setParent(parent);
139 pair<bool,const char*> loc = getString("Location");
141 string address = m_appId + loc.second + "::run::ADFSSI";
142 setAddress(address.c_str());
145 m_log.warn("no Location property in ADFS SessionInitiator (or parent), can't register as remoted handler");
149 void receive(DDF& in, ostream& out);
150 pair<bool,long> unwrap(SPRequest& request, DDF& out) const;
151 pair<bool,long> run(SPRequest& request, string& entityID, bool isHandler=true) const;
153 const XMLCh* getProtocolFamily() const {
154 return m_binding.get();
158 pair<bool,long> doRequest(
159 const Application& application,
160 const HTTPRequest* httpRequest,
161 HTTPResponse& httpResponse,
162 const char* entityID,
163 const char* acsLocation,
164 const char* authnContextClassRef,
168 auto_ptr_XMLCh m_binding;
171 class SHIBSP_DLLLOCAL ADFSConsumer : public shibsp::AssertionConsumerService
173 auto_ptr_XMLCh m_protocol;
175 ADFSConsumer(const DOMElement* e, const char* appId)
176 : shibsp::AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SSO.ADFS")), m_protocol(WSFED_NS) {}
177 virtual ~ADFSConsumer() {}
180 void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
181 AssertionConsumerService::generateMetadata(role, handlerURL);
182 role.addSupport(m_protocol.get());
186 void implementProtocol(
187 const Application& application,
188 const HTTPRequest& httpRequest,
189 HTTPResponse& httpResponse,
190 SecurityPolicy& policy,
192 const XMLObject& xmlObject
195 const XMLCh* getProtocolFamily() const {
196 return m_protocol.get();
201 class SHIBSP_DLLLOCAL ADFSLogoutInitiator : public AbstractHandler, public LogoutInitiator
204 ADFSLogoutInitiator(const DOMElement* e, const char* appId)
205 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".LogoutInitiator.ADFS")), m_appId(appId), m_binding(WSFED_NS) {
206 // If Location isn't set, defer address registration until the setParent call.
207 pair<bool,const char*> loc = getString("Location");
209 string address = m_appId + loc.second + "::run::ADFSLI";
210 setAddress(address.c_str());
213 virtual ~ADFSLogoutInitiator() {}
215 void setParent(const PropertySet* parent) {
216 DOMPropertySet::setParent(parent);
217 pair<bool,const char*> loc = getString("Location");
219 string address = m_appId + loc.second + "::run::ADFSLI";
220 setAddress(address.c_str());
223 m_log.warn("no Location property in ADFS LogoutInitiator (or parent), can't register as remoted handler");
227 void receive(DDF& in, ostream& out);
228 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
230 const XMLCh* getProtocolFamily() const {
231 return m_binding.get();
235 pair<bool,long> doRequest(const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse, Session* session) const;
238 auto_ptr_XMLCh m_binding;
241 class SHIBSP_DLLLOCAL ADFSLogout : public AbstractHandler, public LogoutHandler
244 ADFSLogout(const DOMElement* e, const char* appId)
245 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".Logout.ADFS")), m_login(e, appId) {
248 m_preserve.push_back("wreply");
249 string address = string(appId) + getString("Location").second + "::run::ADFSLO";
250 setAddress(address.c_str());
253 virtual ~ADFSLogout() {}
255 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
258 void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
259 m_login.generateMetadata(role, handlerURL);
260 const char* loc = getString("Location").second;
261 string hurl(handlerURL);
265 auto_ptr_XMLCh widen(hurl.c_str());
266 SingleLogoutService* ep = SingleLogoutServiceBuilder::buildSingleLogoutService();
267 ep->setLocation(widen.get());
268 ep->setBinding(m_login.getProtocolFamily());
269 role.getSingleLogoutServices().push_back(ep);
272 const char* getType() const {
273 return m_login.getType();
276 const XMLCh* getProtocolFamily() const {
277 return m_login.getProtocolFamily();
281 ADFSConsumer m_login;
284 #if defined (_MSC_VER)
285 #pragma warning( pop )
288 SessionInitiator* ADFSSessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
290 return new ADFSSessionInitiator(p.first, p.second);
293 Handler* ADFSLogoutFactory(const pair<const DOMElement*,const char*>& p)
295 return new ADFSLogout(p.first, p.second);
298 Handler* ADFSLogoutInitiatorFactory(const pair<const DOMElement*,const char*>& p)
300 return new ADFSLogoutInitiator(p.first, p.second);
303 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);
304 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);
307 extern "C" int ADFS_EXPORTS xmltooling_extension_init(void*)
309 SPConfig& conf=SPConfig::getConfig();
310 conf.SessionInitiatorManager.registerFactory("ADFS", ADFSSessionInitiatorFactory);
311 conf.LogoutInitiatorManager.registerFactory("ADFS", ADFSLogoutInitiatorFactory);
312 conf.AssertionConsumerServiceManager.registerFactory("ADFS", ADFSLogoutFactory);
313 conf.AssertionConsumerServiceManager.registerFactory(WSFED_NS, ADFSLogoutFactory);
315 SAMLConfig::getConfig().MessageDecoderManager.registerFactory(WSFED_NS, ADFSDecoderFactory);
316 XMLObjectBuilder::registerBuilder(xmltooling::QName(WSTRUST_NS,"RequestedSecurityToken"), new AnyElementBuilder());
317 XMLObjectBuilder::registerBuilder(xmltooling::QName(WSTRUST_NS,"RequestSecurityTokenResponse"), new AnyElementBuilder());
322 extern "C" void ADFS_EXPORTS xmltooling_extension_term()
324 /* should get unregistered during normal shutdown...
325 SPConfig& conf=SPConfig::getConfig();
326 conf.SessionInitiatorManager.deregisterFactory("ADFS");
327 conf.LogoutInitiatorManager.deregisterFactory("ADFS");
328 conf.AssertionConsumerServiceManager.deregisterFactory("ADFS");
329 conf.AssertionConsumerServiceManager.deregisterFactory(WSFED_NS);
331 SAMLConfig::getConfig().MessageDecoderManager.deregisterFactory(WSFED_NS);
336 pair<bool,long> ADFSSessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
338 // We have to know the IdP to function.
339 if (entityID.empty() || !checkCompatibility(request, isHandler))
340 return make_pair(false, 0L);
343 pair<bool,const char*> prop;
344 pair<bool,const char*> acClass;
345 const Handler* ACS = nullptr;
346 const Application& app = request.getApplication();
349 prop.second = request.getParameter("acsIndex");
350 if (prop.second && *prop.second) {
351 ACS = app.getAssertionConsumerServiceByIndex(atoi(prop.second));
353 request.log(SPRequest::SPWarn, "invalid acsIndex specified in request, using acsIndex property");
356 prop = getString("target", request);
358 target = prop.second;
360 // Since we're passing the ACS by value, we need to compute the return URL,
361 // so we'll need the target resource for real.
362 recoverRelayState(app, request, request, target, false);
363 app.limitRedirect(request, target.c_str());
365 acClass = getString("authnContextClassRef", request);
368 // Check for a hardwired target value in the map or handler.
369 prop = getString("target", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
371 target = prop.second;
373 target = request.getRequestURL();
375 acClass = getString("authnContextClassRef", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
379 pair<bool,unsigned int> index = getUnsignedInt("acsIndex", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
381 ACS = app.getAssertionConsumerServiceByIndex(index.second);
384 // Validate the ACS for use with this protocol.
385 if (!ACS || !XMLString::equals(getProtocolFamily(), ACS->getProtocolFamily())) {
387 request.log(SPRequest::SPWarn, "invalid acsIndex property, or non-ADFS ACS, using default ADFS ACS");
388 ACS = app.getAssertionConsumerServiceByProtocol(getProtocolFamily());
390 throw ConfigurationException("Unable to locate an ADFS-compatible ACS in the configuration.");
393 // Since we're not passing by index, we need to fully compute the return URL.
394 // Compute the ACS URL. We add the ACS location to the base handlerURL.
395 string ACSloc = request.getHandlerURL(target.c_str());
396 prop = ACS->getString("Location");
398 ACSloc += prop.second;
401 // We may already have RelayState set if we looped back here,
402 // but we've turned it back into a resource by this point, so if there's
403 // a target on the URL, reset to that value.
404 prop.second = request.getParameter("target");
405 if (prop.second && *prop.second)
406 target = prop.second;
409 m_log.debug("attempting to initiate session using ADFS with provider (%s)", entityID.c_str());
411 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
412 // Out of process means the POST data via the request can be exposed directly to the private method.
413 // The method will handle POST preservation if necessary *before* issuing the response, but only if
414 // it dispatches to an IdP.
415 return doRequest(app, &request, request, entityID.c_str(), ACSloc.c_str(), (acClass.first ? acClass.second : nullptr), target);
419 DDF out,in = DDF(m_address.c_str()).structure();
420 DDFJanitor jin(in), jout(out);
421 in.addmember("application_id").string(app.getId());
422 in.addmember("entity_id").string(entityID.c_str());
423 in.addmember("acsLocation").string(ACSloc.c_str());
425 in.addmember("RelayState").unsafe_string(target.c_str());
427 in.addmember("authnContextClassRef").string(acClass.second);
429 // Remote the processing.
430 out = request.getServiceProvider().getListenerService()->send(in);
431 return unwrap(request, out);
434 pair<bool,long> ADFSSessionInitiator::unwrap(SPRequest& request, DDF& out) const
436 // See if there's any response to send back.
437 if (!out["redirect"].isnull() || !out["response"].isnull()) {
438 // If so, we're responsible for handling the POST data, probably by dropping a cookie.
439 preservePostData(request.getApplication(), request, request, out["RelayState"].string());
441 return RemotedHandler::unwrap(request, out);
444 void ADFSSessionInitiator::receive(DDF& in, ostream& out)
447 const char* aid = in["application_id"].string();
448 const Application* app = aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
450 // Something's horribly wrong.
451 m_log.error("couldn't find application (%s) to generate ADFS request", aid ? aid : "(missing)");
452 throw ConfigurationException("Unable to locate application for new session, deleted?");
455 const char* entityID = in["entity_id"].string();
456 const char* acsLocation = in["acsLocation"].string();
457 if (!entityID || !acsLocation)
458 throw ConfigurationException("No entityID or acsLocation parameter supplied to remoted SessionInitiator.");
461 DDFJanitor jout(ret);
463 // Wrap the outgoing object with a Response facade.
464 scoped_ptr<HTTPResponse> http(getResponse(ret));
466 string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");
468 // Since we're remoted, the result should either be a throw, which we pass on,
469 // a false/0 return, which we just return as an empty structure, or a response/redirect,
470 // which we capture in the facade and send back.
471 doRequest(*app, nullptr, *http, entityID, acsLocation, in["authnContextClassRef"].string(), relayState);
474 ret.addmember("RelayState").unsafe_string(relayState.c_str());
478 pair<bool,long> ADFSSessionInitiator::doRequest(
479 const Application& app,
480 const HTTPRequest* httpRequest,
481 HTTPResponse& httpResponse,
482 const char* entityID,
483 const char* acsLocation,
484 const char* authnContextClassRef,
489 // Use metadata to invoke the SSO service directly.
490 MetadataProvider* m = app.getMetadataProvider();
492 MetadataProviderCriteria mc(app, entityID, &IDPSSODescriptor::ELEMENT_QNAME, m_binding.get());
493 pair<const EntityDescriptor*,const RoleDescriptor*> entity = m->getEntityDescriptor(mc);
495 m_log.warn("unable to locate metadata for provider (%s)", entityID);
496 throw MetadataException("Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", entityID));
498 else if (!entity.second) {
499 m_log.log(getParent() ? Priority::INFO : Priority::WARN, "unable to locate ADFS-aware identity provider role for provider (%s)", entityID);
501 return make_pair(false, 0L);
502 throw MetadataException("Unable to locate ADFS-aware identity provider role for provider ($entityID)", namedparams(1, "entityID", entityID));
504 const EndpointType* ep = EndpointManager<SingleSignOnService>(
505 dynamic_cast<const IDPSSODescriptor*>(entity.second)->getSingleSignOnServices()
506 ).getByBinding(m_binding.get());
508 m_log.warn("unable to locate compatible SSO service for provider (%s)", entityID);
510 return make_pair(false, 0L);
511 throw MetadataException("Unable to locate compatible SSO service for provider ($entityID)", namedparams(1, "entityID", entityID));
514 preserveRelayState(app, httpResponse, relayState);
516 scoped_ptr<AuthnRequestEvent> ar_event(newAuthnRequestEvent(app, httpRequest));
517 if (ar_event.get()) {
518 ar_event->m_binding = WSFED_NS;
519 ar_event->m_protocol = WSFED_NS;
520 ar_event->m_peer = entity.first;
521 app.getServiceProvider().getTransactionLog()->write(*ar_event);
525 time_t epoch=time(nullptr);
526 #ifndef HAVE_GMTIME_R
527 struct tm* ptime=gmtime(&epoch);
530 struct tm* ptime=gmtime_r(&epoch,&res);
533 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
535 auto_ptr_char dest(ep->getLocation());
536 const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
538 string req=string(dest.get()) + (strchr(dest.get(),'?') ? '&' : '?') + "wa=wsignin1.0&wreply=" + urlenc->encode(acsLocation) +
539 "&wct=" + urlenc->encode(timebuf) + "&wtrealm=" + urlenc->encode(app.getString("entityID").second);
540 if (authnContextClassRef)
541 req += "&wauth=" + urlenc->encode(authnContextClassRef);
542 if (!relayState.empty())
543 req += "&wctx=" + urlenc->encode(relayState.c_str());
546 // If the request object is available, we're responsible for the POST data.
547 preservePostData(app, *httpRequest, httpResponse, relayState.c_str());
550 return make_pair(true, httpResponse.sendRedirect(req.c_str()));
552 return make_pair(false, 0L);
558 XMLObject* ADFSDecoder::decode(string& relayState, const GenericRequest& genericRequest, SecurityPolicy& policy) const
561 xmltooling::NDC ndc("decode");
563 Category& log = Category::getInstance(SHIBSP_LOGCAT".MessageDecoder.ADFS");
565 log.debug("validating input");
566 const HTTPRequest* httpRequest=dynamic_cast<const HTTPRequest*>(&genericRequest);
568 throw BindingException("Unable to cast request object to HTTPRequest type.");
569 if (strcmp(httpRequest->getMethod(),"POST"))
570 throw BindingException("Invalid HTTP method ($1).", params(1, httpRequest->getMethod()));
571 const char* param = httpRequest->getParameter("wa");
572 if (!param || strcmp(param, "wsignin1.0"))
573 throw BindingException("Missing or invalid wa parameter (should be wsignin1.0).");
574 param = httpRequest->getParameter("wctx");
578 param = httpRequest->getParameter("wresult");
580 throw BindingException("Request missing wresult parameter.");
582 log.debug("decoded ADFS response:\n%s", param);
584 // Parse and bind the document into an XMLObject.
585 istringstream is(param);
586 DOMDocument* doc = (policy.getValidating() ? XMLToolingConfig::getConfig().getValidatingParser()
587 : XMLToolingConfig::getConfig().getParser()).parse(is);
588 XercesJanitor<DOMDocument> janitor(doc);
589 auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
592 if (!XMLString::equals(xmlObject->getElementQName().getLocalPart(), RequestSecurityTokenResponse)) {
593 log.error("unrecognized root element on message: %s", xmlObject->getElementQName().toString().c_str());
594 throw BindingException("Decoded message was not of the appropriate type.");
597 SchemaValidators.validate(xmlObject.get());
599 // Skip policy step here, there's no security in the wrapper.
600 // policy.evaluate(*xmlObject.get(), &genericRequest);
602 return xmlObject.release();
605 void ADFSConsumer::implementProtocol(
606 const Application& application,
607 const HTTPRequest& httpRequest,
608 HTTPResponse& httpResponse,
609 SecurityPolicy& policy,
611 const XMLObject& xmlObject
614 // Implementation of ADFS profile.
615 m_log.debug("processing message against ADFS Passive Requester profile");
617 // With ADFS, all the security comes from the assertion, which is two levels down in the message.
619 const ElementProxy* response = dynamic_cast<const ElementProxy*>(&xmlObject);
620 if (!response || !response->hasChildren())
621 throw FatalProfileException("Incoming message was not of the proper type or contains no security token.");
623 const Assertion* token = nullptr;
624 for (vector<XMLObject*>::const_iterator xo = response->getUnknownXMLObjects().begin(); xo != response->getUnknownXMLObjects().end(); ++xo) {
625 // Look for the RequestedSecurityToken element.
626 if (XMLString::equals((*xo)->getElementQName().getLocalPart(), RequestedSecurityToken)) {
627 response = dynamic_cast<const ElementProxy*>(*xo);
628 if (!response || !response->hasChildren())
629 throw FatalProfileException("Token wrapper element did not contain a security token.");
630 token = dynamic_cast<const Assertion*>(response->getUnknownXMLObjects().front());
631 if (!token || !token->getSignature())
632 throw FatalProfileException("Incoming message did not contain a signed SAML assertion.");
637 // Extract message and issuer details from assertion.
638 extractMessageDetails(*token, m_protocol.get(), policy);
640 // Populate recipient as audience.
641 const EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : nullptr;
642 policy.getAudiences().push_back(application.getRelyingParty(entity)->getXMLString("entityID").second);
644 // Run the policy over the assertion. Handles replay, freshness, and
645 // signature verification, assuming the relevant rules are configured,
646 // along with condition enforcement.
647 policy.evaluate(*token, &httpRequest);
649 // If no security is in place now, we kick it.
650 if (!policy.isAuthenticated())
651 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
653 const saml1::NameIdentifier* saml1name=nullptr;
654 const saml1::AuthenticationStatement* saml1statement=nullptr;
655 const saml2::NameID* saml2name=nullptr;
656 const saml2::AuthnStatement* saml2statement=nullptr;
657 const XMLCh* authMethod=nullptr;
658 const XMLCh* authInstant=nullptr;
659 time_t now = time(nullptr), sessionExp = 0;
660 const PropertySet* sessionProps = application.getPropertySet("Sessions");
662 const saml1::Assertion* saml1token = dynamic_cast<const saml1::Assertion*>(token);
664 // Now do profile validation to ensure we can use it for SSO.
665 if (!saml1token->getConditions() || !saml1token->getConditions()->getNotBefore() || !saml1token->getConditions()->getNotOnOrAfter())
666 throw FatalProfileException("Assertion did not contain time conditions.");
667 else if (saml1token->getAuthenticationStatements().empty())
668 throw FatalProfileException("Assertion did not contain an authentication statement.");
670 // authnskew allows rejection of SSO if AuthnInstant is too old.
671 pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);
673 saml1statement = saml1token->getAuthenticationStatements().front();
674 if (saml1statement->getAuthenticationInstant()) {
675 if (saml1statement->getAuthenticationInstantEpoch() - XMLToolingConfig::getConfig().clock_skew_secs > now) {
676 throw FatalProfileException("The login time at your identity provider was future-dated.");
678 else if (authnskew.first && authnskew.second && saml1statement->getAuthenticationInstantEpoch() <= now &&
679 (now - saml1statement->getAuthenticationInstantEpoch() > authnskew.second)) {
680 throw FatalProfileException("The gap between now and the time you logged into your identity provider exceeds the allowed limit.");
683 else if (authnskew.first && authnskew.second) {
684 throw FatalProfileException("Your identity provider did not supply a time of login, violating local policy.");
688 saml1::SubjectLocality* locality = saml1statement->getSubjectLocality();
689 if (locality && locality->getIPAddress()) {
690 auto_ptr_char ip(locality->getIPAddress());
691 checkAddress(application, httpRequest, ip.get());
694 saml1name = saml1statement->getSubject()->getNameIdentifier();
695 authMethod = saml1statement->getAuthenticationMethod();
696 if (saml1statement->getAuthenticationInstant())
697 authInstant = saml1statement->getAuthenticationInstant()->getRawData();
699 // Session expiration.
700 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
701 if (!lifetime.first || lifetime.second == 0)
702 lifetime.second = 28800;
703 sessionExp = now + lifetime.second;
706 const saml2::Assertion* saml2token = dynamic_cast<const saml2::Assertion*>(token);
708 throw FatalProfileException("Incoming message did not contain a recognized type of SAML assertion.");
710 // Now do profile validation to ensure we can use it for SSO.
711 if (!saml2token->getConditions() || !saml2token->getConditions()->getNotBefore() || !saml2token->getConditions()->getNotOnOrAfter())
712 throw FatalProfileException("Assertion did not contain time conditions.");
713 else if (saml2token->getAuthnStatements().empty())
714 throw FatalProfileException("Assertion did not contain an authentication statement.");
716 // authnskew allows rejection of SSO if AuthnInstant is too old.
717 pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);
719 saml2statement = saml2token->getAuthnStatements().front();
720 if (authnskew.first && authnskew.second &&
721 saml2statement->getAuthnInstant() && (now - saml2statement->getAuthnInstantEpoch() > authnskew.second))
722 throw FatalProfileException("The gap between now and the time you logged into your identity provider exceeds the limit.");
725 saml2::SubjectLocality* locality = saml2statement->getSubjectLocality();
726 if (locality && locality->getAddress()) {
727 auto_ptr_char ip(locality->getAddress());
728 checkAddress(application, httpRequest, ip.get());
731 saml2name = saml2token->getSubject() ? saml2token->getSubject()->getNameID() : nullptr;
732 if (saml2statement->getAuthnContext() && saml2statement->getAuthnContext()->getAuthnContextClassRef())
733 authMethod = saml2statement->getAuthnContext()->getAuthnContextClassRef()->getReference();
734 if (saml2statement->getAuthnInstant())
735 authInstant = saml2statement->getAuthnInstant()->getRawData();
737 // Session expiration for SAML 2.0 is jointly IdP- and SP-driven.
738 sessionExp = saml2statement->getSessionNotOnOrAfter() ? saml2statement->getSessionNotOnOrAfterEpoch() : 0;
739 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
740 if (!lifetime.first || lifetime.second == 0)
741 lifetime.second = 28800;
743 sessionExp = now + lifetime.second; // IdP says nothing, calulate based on SP.
745 sessionExp = min(sessionExp, now + lifetime.second); // Use the lowest.
748 m_log.debug("ADFS profile processing completed successfully");
750 // We've successfully "accepted" the SSO token.
751 // To complete processing, we need to extract and resolve attributes and then create the session.
753 // Normalize a SAML 1.x NameIdentifier...
754 scoped_ptr<saml2::NameID> nameid(saml1name ? saml2::NameIDBuilder::buildNameID() : nullptr);
756 nameid->setName(saml1name->getName());
757 nameid->setFormat(saml1name->getFormat());
758 nameid->setNameQualifier(saml1name->getNameQualifier());
761 // The context will handle deleting attributes and new tokens.
762 vector<const Assertion*> tokens(1,token);
763 scoped_ptr<ResolutionContext> ctx(
767 policy.getIssuerMetadata(),
772 (saml1name ? nameid.get() : saml2name),
781 // Copy over any new tokens, but leave them in the context for cleanup.
782 tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
786 application.getServiceProvider().getSessionCache()->insert(
794 (saml1name ? nameid.get() : saml2name),
800 ctx ? &ctx->getResolvedAttributes() : nullptr
803 scoped_ptr<LoginEvent> login_event(newLoginEvent(application, httpRequest));
805 login_event->m_sessionID = session_id.c_str();
806 login_event->m_peer = entity;
807 login_event->m_protocol = WSFED_NS;
808 login_event->m_binding = WSFED_NS;
809 login_event->m_saml1AuthnStatement = saml1statement;
810 login_event->m_nameID = (saml1name ? nameid.get() : saml2name);
811 login_event->m_saml2AuthnStatement = saml2statement;
813 login_event->m_attributes = &ctx->getResolvedAttributes();
814 application.getServiceProvider().getTransactionLog()->write(*login_event);
820 pair<bool,long> ADFSLogoutInitiator::run(SPRequest& request, bool isHandler) const
822 // Normally we'd do notifications and session clearage here, but ADFS logout
823 // is missing the needed request/response features, so we have to rely on
824 // the IdP half to notify us back about the logout and do the work there.
825 // Basically we have no way to tell in the Logout receiving handler whether
826 // we initiated the logout or not.
828 Session* session = nullptr;
830 session = request.getSession(false, true, false); // don't cache it and ignore all checks
832 return make_pair(false, 0L);
834 // We only handle ADFS sessions.
835 if (!XMLString::equals(session->getProtocol(), WSFED_NS) || !session->getEntityID()) {
837 return make_pair(false, 0L);
840 catch (std::exception& ex) {
841 m_log.error("error accessing current session: %s", ex.what());
842 return make_pair(false,0L);
845 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
846 // When out of process, we run natively.
847 return doRequest(request.getApplication(), request, request, session);
850 // When not out of process, we remote the request.
852 vector<string> headers(1,"Cookie");
853 headers.push_back("User-Agent");
854 DDF out,in = wrap(request, &headers);
855 DDFJanitor jin(in), jout(out);
856 out=request.getServiceProvider().getListenerService()->send(in);
857 return unwrap(request, out);
861 void ADFSLogoutInitiator::receive(DDF& in, ostream& out)
864 // Defer to base class for notifications
865 if (in["notify"].integer() == 1)
866 return LogoutHandler::receive(in, out);
869 const char* aid = in["application_id"].string();
870 const Application* app = aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
872 // Something's horribly wrong.
873 m_log.error("couldn't find application (%s) for logout", aid ? aid : "(missing)");
874 throw ConfigurationException("Unable to locate application for logout, deleted?");
877 // Unpack the request.
878 scoped_ptr<HTTPRequest> req(getRequest(in));
880 // Set up a response shim.
882 DDFJanitor jout(ret);
883 scoped_ptr<HTTPResponse> resp(getResponse(ret));
885 Session* session = nullptr;
887 session = app->getServiceProvider().getSessionCache()->find(*app, *req, nullptr, nullptr);
889 catch (std::exception& ex) {
890 m_log.error("error accessing current session: %s", ex.what());
893 // With no session, we just skip the request and let it fall through to an empty struct return.
895 if (session->getEntityID()) {
896 // Since we're remoted, the result should either be a throw, which we pass on,
897 // a false/0 return, which we just return as an empty structure, or a response/redirect,
898 // which we capture in the facade and send back.
899 doRequest(*app, *req, *resp, session);
902 m_log.error("no issuing entityID found in session");
904 app->getServiceProvider().getSessionCache()->remove(*app, *req, resp.get());
909 throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
913 pair<bool,long> ADFSLogoutInitiator::doRequest(
914 const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse, Session* session
917 Locker sessionLocker(session, false);
919 // Do back channel notification.
920 vector<string> sessions(1, session->getID());
921 if (!notifyBackChannel(application, httpRequest.getRequestURL(), sessions, false)) {
923 scoped_ptr<LogoutEvent> logout_event(newLogoutEvent(application, &httpRequest, session));
925 logout_event->m_logoutType = LogoutEvent::LOGOUT_EVENT_PARTIAL;
926 application.getServiceProvider().getTransactionLog()->write(*logout_event);
929 sessionLocker.assign();
931 application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
932 return sendLogoutPage(application, httpRequest, httpResponse, "partial");
936 pair<bool,long> ret = make_pair(false, 0L);
939 // With a session in hand, we can create a request message, if we can find a compatible endpoint.
940 MetadataProvider* m = application.getMetadataProvider();
941 Locker metadataLocker(m);
942 MetadataProviderCriteria mc(application, session->getEntityID(), &IDPSSODescriptor::ELEMENT_QNAME, m_binding.get());
943 pair<const EntityDescriptor*,const RoleDescriptor*> entity=m->getEntityDescriptor(mc);
945 throw MetadataException(
946 "Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", session->getEntityID())
949 else if (!entity.second) {
950 throw MetadataException(
951 "Unable to locate ADFS IdP role for identity provider ($entityID).", namedparams(1, "entityID", session->getEntityID())
955 const EndpointType* ep = EndpointManager<SingleLogoutService>(
956 dynamic_cast<const IDPSSODescriptor*>(entity.second)->getSingleLogoutServices()
957 ).getByBinding(m_binding.get());
959 throw MetadataException(
960 "Unable to locate ADFS single logout service for identity provider ($entityID).",
961 namedparams(1, "entityID", session->getEntityID())
965 const char* returnloc = httpRequest.getParameter("return");
967 application.limitRedirect(httpRequest, returnloc);
970 scoped_ptr<LogoutEvent> logout_event(newLogoutEvent(application, &httpRequest, session));
972 logout_event->m_logoutType = LogoutEvent::LOGOUT_EVENT_UNKNOWN;
973 application.getServiceProvider().getTransactionLog()->write(*logout_event);
976 auto_ptr_char dest(ep->getLocation());
977 string req=string(dest.get()) + (strchr(dest.get(),'?') ? '&' : '?') + "wa=wsignout1.0";
980 if (*returnloc == '/') {
982 httpRequest.absolutize(s);
983 req += XMLToolingConfig::getConfig().getURLEncoder()->encode(s.c_str());
986 req += XMLToolingConfig::getConfig().getURLEncoder()->encode(returnloc);
989 ret.second = httpResponse.sendRedirect(req.c_str());
993 sessionLocker.assign();
995 application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
998 catch (MetadataException& mex) {
999 // Less noise for IdPs that don't support logout
1000 m_log.info("unable to issue ADFS logout request: %s", mex.what());
1002 catch (std::exception& ex) {
1003 m_log.error("error issuing ADFS logout request: %s", ex.what());
1008 throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
1012 pair<bool,long> ADFSLogout::run(SPRequest& request, bool isHandler) const
1014 // Defer to base class for front-channel loop first.
1015 // This won't initiate the loop, only continue/end it.
1016 pair<bool,long> ret = LogoutHandler::run(request, isHandler);
1020 // wa parameter indicates the "action" to perform
1021 bool returning = false;
1022 const char* param = request.getParameter("wa");
1024 if (!strcmp(param, "wsignin1.0"))
1025 return m_login.run(request, isHandler);
1026 else if (strcmp(param, "wsignout1.0") && strcmp(param, "wsignoutcleanup1.0"))
1027 throw FatalProfileException("Unsupported WS-Federation action paremeter ($1).", params(1, param));
1029 else if (strcmp(request.getMethod(),"GET") || !request.getParameter("notifying"))
1030 throw FatalProfileException("Unsupported request to ADFS protocol endpoint.");
1034 param = request.getParameter("wreply");
1035 const Application& app = request.getApplication();
1038 // Pass control to the first front channel notification point, if any.
1039 map<string,string> parammap;
1041 parammap["wreply"] = param;
1042 pair<bool,long> result = notifyFrontChannel(app, request, request, ¶mmap);
1047 // Best effort on back channel and to remove the user agent's session.
1048 string session_id = app.getServiceProvider().getSessionCache()->active(app, request);
1049 if (!session_id.empty()) {
1050 vector<string> sessions(1,session_id);
1051 notifyBackChannel(app, request.getRequestURL(), sessions, false);
1053 app.getServiceProvider().getSessionCache()->remove(app, request, &request);
1055 catch (std::exception& ex) {
1056 m_log.error("error removing session (%s): %s", session_id.c_str(), ex.what());
1061 if (*param == '/') {
1063 request.absolutize(p);
1064 return make_pair(true, request.sendRedirect(p.c_str()));
1067 app.limitRedirect(request, param);
1068 return make_pair(true, request.sendRedirect(param));
1071 return sendLogoutPage(app, request, request, "global");