2 * Copyright 2001-2005 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/handler/AssertionConsumerService.h>
44 #include <shibsp/handler/LogoutHandler.h>
45 #include <shibsp/handler/SessionInitiator.h>
46 #include <xmltooling/logging.h>
47 #include <xmltooling/util/NDC.h>
48 #include <xmltooling/util/URLEncoder.h>
49 #include <xmltooling/util/XMLHelper.h>
50 #include <xercesc/util/XMLUniDefs.hpp>
53 # include <shibsp/attribute/Attribute.h>
54 # include <shibsp/attribute/filtering/AttributeFilter.h>
55 # include <shibsp/attribute/filtering/BasicFilteringContext.h>
56 # include <shibsp/attribute/resolver/AttributeExtractor.h>
57 # include <shibsp/attribute/resolver/ResolutionContext.h>
58 # include <saml/SAMLConfig.h>
59 # include <saml/saml1/core/Assertions.h>
60 # include <saml/saml1/profile/AssertionValidator.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/impl/AnyElement.h>
65 # include <xmltooling/validation/ValidatorSuite.h>
66 using namespace opensaml::saml2md;
68 using namespace shibsp;
69 using namespace opensaml;
70 using namespace xmltooling::logging;
71 using namespace xmltooling;
72 using namespace xercesc;
75 #define WSFED_NS "http://schemas.xmlsoap.org/ws/2003/07/secext"
76 #define WSTRUST_NS "http://schemas.xmlsoap.org/ws/2005/02/trust"
81 class SHIBSP_DLLLOCAL ADFSDecoder : public MessageDecoder
85 ADFSDecoder() : m_ns(WSTRUST_NS) {}
86 virtual ~ADFSDecoder() {}
88 XMLObject* decode(string& relayState, const GenericRequest& genericRequest, SecurityPolicy& policy) const;
91 MessageDecoder* ADFSDecoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
93 return new ADFSDecoder();
96 class SHIBSP_DLLLOCAL ADFSMessageRule : public SecurityPolicyRule
99 ADFSMessageRule(const DOMElement* e) : m_protocol(WSFED_NS) {}
100 virtual ~ADFSMessageRule() {}
102 const char* getType() const {
103 return "ADFSMessage";
105 void evaluate(const XMLObject& message, const GenericRequest* request, const XMLCh* protocol, SecurityPolicy& policy) const;
107 auto_ptr_XMLCh m_protocol;
110 SecurityPolicyRule* ADFSMessageRuleFactory(const DOMElement* const & e)
112 return new ADFSMessageRule(e);
116 #if defined (_MSC_VER)
117 #pragma warning( push )
118 #pragma warning( disable : 4250 )
121 class SHIBSP_DLLLOCAL ADFSSessionInitiator : public SessionInitiator, public AbstractHandler, public RemotedHandler
124 ADFSSessionInitiator(const DOMElement* e, const char* appId)
125 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator")), m_appId(appId), m_binding(WSFED_NS) {
126 // If Location isn't set, defer address registration until the setParent call.
127 pair<bool,const char*> loc = getString("Location");
129 string address = m_appId + loc.second + "::run::ADFSSI";
130 setAddress(address.c_str());
133 virtual ~ADFSSessionInitiator() {}
135 void setParent(const PropertySet* parent) {
136 DOMPropertySet::setParent(parent);
137 pair<bool,const char*> loc = getString("Location");
139 string address = m_appId + loc.second + "::run::ADFSSI";
140 setAddress(address.c_str());
143 m_log.warn("no Location property in ADFS SessionInitiator (or parent), can't register as remoted handler");
147 void receive(DDF& in, ostream& out);
148 pair<bool,long> run(SPRequest& request, const char* entityID=NULL, bool isHandler=true) const;
151 pair<bool,long> doRequest(
152 const Application& application,
153 HTTPResponse& httpResponse,
154 const char* entityID,
155 const char* acsLocation,
159 auto_ptr_XMLCh m_binding;
162 class SHIBSP_DLLLOCAL ADFSConsumer : public shibsp::AssertionConsumerService
165 ADFSConsumer(const DOMElement* e, const char* appId)
166 : shibsp::AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SSO.ADFS"))
171 virtual ~ADFSConsumer() {}
175 string implementProtocol(
176 const Application& application,
177 const HTTPRequest& httpRequest,
178 SecurityPolicy& policy,
179 const PropertySet* settings,
180 const XMLObject& xmlObject
182 ADFSMessageRule m_messageRule;
186 class SHIBSP_DLLLOCAL ADFSLogoutInitiator : public AbstractHandler, public LogoutHandler
189 ADFSLogoutInitiator(const DOMElement* e, const char* appId)
190 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator")), m_appId(appId), m_binding(WSFED_NS) {
191 // If Location isn't set, defer address registration until the setParent call.
192 pair<bool,const char*> loc = getString("Location");
194 string address = m_appId + loc.second + "::run::ADFSLI";
195 setAddress(address.c_str());
198 virtual ~ADFSLogoutInitiator() {}
200 void setParent(const PropertySet* parent) {
201 DOMPropertySet::setParent(parent);
202 pair<bool,const char*> loc = getString("Location");
204 string address = m_appId + loc.second + "::run::ADFSLI";
205 setAddress(address.c_str());
208 m_log.warn("no Location property in ADFS LogoutInitiator (or parent), can't register as remoted handler");
212 void receive(DDF& in, ostream& out);
213 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
216 pair<bool,long> doRequest(
217 const Application& application, const char* requestURL, Session* session, HTTPResponse& httpResponse
221 auto_ptr_XMLCh m_binding;
224 class SHIBSP_DLLLOCAL ADFSLogout : public AbstractHandler, public LogoutHandler
227 ADFSLogout(const DOMElement* e, const char* appId)
228 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".Logout.ADFS")), m_login(e, appId) {
231 m_preserve.push_back("wreply");
232 string address = string(appId) + getString("Location").second + "::run::ADFSLO";
233 setAddress(address.c_str());
236 virtual ~ADFSLogout() {}
238 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
241 ADFSConsumer m_login;
244 #if defined (_MSC_VER)
245 #pragma warning( pop )
248 SessionInitiator* ADFSSessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
250 return new ADFSSessionInitiator(p.first, p.second);
253 Handler* ADFSLogoutFactory(const pair<const DOMElement*,const char*>& p)
255 return new ADFSLogout(p.first, p.second);
258 Handler* ADFSLogoutInitiatorFactory(const pair<const DOMElement*,const char*>& p)
260 return new ADFSLogoutInitiator(p.first, p.second);
263 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);
264 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);
267 extern "C" int ADFS_EXPORTS xmltooling_extension_init(void*)
269 SPConfig& conf=SPConfig::getConfig();
270 conf.SessionInitiatorManager.registerFactory("ADFS", ADFSSessionInitiatorFactory);
271 conf.LogoutInitiatorManager.registerFactory("ADFS", ADFSLogoutInitiatorFactory);
272 conf.AssertionConsumerServiceManager.registerFactory("ADFS", ADFSLogoutFactory);
273 conf.AssertionConsumerServiceManager.registerFactory(WSFED_NS, ADFSLogoutFactory);
275 SAMLConfig::getConfig().MessageDecoderManager.registerFactory(WSFED_NS, ADFSDecoderFactory);
276 SAMLConfig::getConfig().SecurityPolicyRuleManager.registerFactory("ADFSMessage", ADFSMessageRuleFactory);
277 XMLObjectBuilder::registerBuilder(QName(WSTRUST_NS,"RequestedSecurityToken"), new AnyElementBuilder());
278 XMLObjectBuilder::registerBuilder(QName(WSTRUST_NS,"RequestSecurityTokenResponse"), new AnyElementBuilder());
283 extern "C" void ADFS_EXPORTS xmltooling_extension_term()
285 /* should get unregistered during normal shutdown...
286 SPConfig& conf=SPConfig::getConfig();
287 conf.SessionInitiatorManager.deregisterFactory("ADFS");
288 conf.LogoutInitiatorManager.deregisterFactory("ADFS");
289 conf.AssertionConsumerServiceManager.deregisterFactory("ADFS");
290 conf.AssertionConsumerServiceManager.deregisterFactory(WSFED_NS);
292 SAMLConfig::getConfig().MessageDecoderManager.deregisterFactory(WSFED_NS);
293 SAMLConfig::getConfig().SecurityPolicyRuleManager.deregisterFactory("ADFSMessage");
298 pair<bool,long> ADFSSessionInitiator::run(SPRequest& request, const char* entityID, bool isHandler) const
300 // We have to know the IdP to function.
301 if (!entityID || !*entityID)
302 return make_pair(false,0);
305 const Handler* ACS=NULL;
307 const Application& app=request.getApplication();
310 option = request.getParameter("target");
314 // Since we're passing the ACS by value, we need to compute the return URL,
315 // so we'll need the target resource for real.
316 recoverRelayState(request.getApplication(), request, target, false);
319 // We're running as a "virtual handler" from within the filter.
320 // The target resource is the current one and everything else is defaulted.
321 target=request.getRequestURL();
324 // Since we're not passing by index, we need to fully compute the return URL.
326 // Get all the ADFS endpoints.
327 const vector<const Handler*>& handlers = app.getAssertionConsumerServicesByBinding(m_binding.get());
329 // Index comes from request, or default set in the handler, or we just pick the first endpoint.
330 pair<bool,unsigned int> index = make_pair(false,0);
332 option = request.getParameter("acsIndex");
334 index = make_pair(true, atoi(option));
337 index = getUnsignedInt("defaultACSIndex");
339 for (vector<const Handler*>::const_iterator h = handlers.begin(); !ACS && h!=handlers.end(); ++h) {
340 if (index.second == (*h)->getUnsignedInt("index").second)
344 else if (!handlers.empty()) {
345 ACS = handlers.front();
349 throw ConfigurationException("Unable to locate ADFS response endpoint.");
351 // Compute the ACS URL. We add the ACS location to the base handlerURL.
352 string ACSloc=request.getHandlerURL(target.c_str());
353 pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
354 if (loc.first) ACSloc+=loc.second;
357 // We may already have RelayState set if we looped back here,
358 // but just in case target is a resource, we reset it back.
360 option = request.getParameter("target");
365 m_log.debug("attempting to initiate session using ADFS with provider (%s)", entityID);
367 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess))
368 return doRequest(app, request, entityID, ACSloc.c_str(), target);
371 DDF out,in = DDF(m_address.c_str()).structure();
372 DDFJanitor jin(in), jout(out);
373 in.addmember("application_id").string(app.getId());
374 in.addmember("entity_id").string(entityID);
375 in.addmember("acsLocation").string(ACSloc.c_str());
377 in.addmember("RelayState").string(target.c_str());
379 // Remote the processing.
380 out = request.getServiceProvider().getListenerService()->send(in);
381 return unwrap(request, out);
384 void ADFSSessionInitiator::receive(DDF& in, ostream& out)
387 const char* aid=in["application_id"].string();
388 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
390 // Something's horribly wrong.
391 m_log.error("couldn't find application (%s) to generate ADFS request", aid ? aid : "(missing)");
392 throw ConfigurationException("Unable to locate application for new session, deleted?");
395 const char* entityID = in["entity_id"].string();
396 const char* acsLocation = in["acsLocation"].string();
397 if (!entityID || !acsLocation)
398 throw ConfigurationException("No entityID or acsLocation parameter supplied to remoted SessionInitiator.");
401 DDFJanitor jout(ret);
403 // Wrap the outgoing object with a Response facade.
404 auto_ptr<HTTPResponse> http(getResponse(ret));
406 string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");
408 // Since we're remoted, the result should either be a throw, which we pass on,
409 // a false/0 return, which we just return as an empty structure, or a response/redirect,
410 // which we capture in the facade and send back.
411 doRequest(*app, *http.get(), entityID, acsLocation, relayState);
415 pair<bool,long> ADFSSessionInitiator::doRequest(
416 const Application& app,
417 HTTPResponse& httpResponse,
418 const char* entityID,
419 const char* acsLocation,
424 // Use metadata to invoke the SSO service directly.
425 MetadataProvider* m=app.getMetadataProvider();
427 const EntityDescriptor* entity=m->getEntityDescriptor(entityID);
429 m_log.error("unable to locate metadata for provider (%s)", entityID);
430 throw MetadataException("Unable to locate metadata for identity provider ($entityID)",
431 namedparams(1, "entityID", entityID));
433 const IDPSSODescriptor* role=entity->getIDPSSODescriptor(m_binding.get());
435 m_log.error("unable to locate ADFS-aware identity provider role for provider (%s)", entityID);
436 return make_pair(false,0);
438 const EndpointType* ep=EndpointManager<SingleSignOnService>(role->getSingleSignOnServices()).getByBinding(m_binding.get());
440 m_log.error("unable to locate compatible SSO service for provider (%s)", entityID);
441 return make_pair(false,0);
444 preserveRelayState(app, httpResponse, relayState);
447 time_t epoch=time(NULL);
448 #ifndef HAVE_GMTIME_R
449 struct tm* ptime=gmtime(&epoch);
452 struct tm* ptime=gmtime_r(&epoch,&res);
455 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
457 auto_ptr_char dest(ep->getLocation());
458 const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
460 string req=string(dest.get()) + (strchr(dest.get(),'?') ? '&' : '?') + "wa=wsignin1.0&wreply=" + urlenc->encode(acsLocation) +
461 "&wct=" + urlenc->encode(timebuf) + "&wtrealm=" + urlenc->encode(app.getString("entityID").second);
462 if (!relayState.empty())
463 req += "&wctx=" + urlenc->encode(relayState.c_str());
465 return make_pair(true, httpResponse.sendRedirect(req.c_str()));
467 return make_pair(false,0);
473 XMLObject* ADFSDecoder::decode(string& relayState, const GenericRequest& genericRequest, SecurityPolicy& policy) const
476 xmltooling::NDC ndc("decode");
478 Category& log = Category::getInstance(SHIBSP_LOGCAT".MessageDecoder.ADFS");
480 log.debug("validating input");
481 const HTTPRequest* httpRequest=dynamic_cast<const HTTPRequest*>(&genericRequest);
483 throw BindingException("Unable to cast request object to HTTPRequest type.");
484 if (strcmp(httpRequest->getMethod(),"POST"))
485 throw BindingException("Invalid HTTP method ($1).", params(1, httpRequest->getMethod()));
486 const char* param = httpRequest->getParameter("wa");
487 if (!param || strcmp(param, "wsignin1.0"))
488 throw BindingException("Missing or invalid wa parameter (should be wsignin1.0).");
489 param = httpRequest->getParameter("wctx");
493 param = httpRequest->getParameter("wresult");
495 throw BindingException("Request missing wresult parameter.");
497 log.debug("decoded ADFS response:\n%s", param);
499 // Parse and bind the document into an XMLObject.
500 istringstream is(param);
501 DOMDocument* doc = (policy.getValidating() ? XMLToolingConfig::getConfig().getValidatingParser()
502 : XMLToolingConfig::getConfig().getParser()).parse(is);
503 XercesJanitor<DOMDocument> janitor(doc);
504 auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
507 if (!XMLHelper::isNodeNamed(xmlObject->getDOM(), m_ns.get(), RequestSecurityTokenResponse))
508 throw BindingException("Decoded message was not of the appropriate type.");
510 if (!policy.getValidating())
511 SchemaValidators.validate(xmlObject.get());
513 // Skip policy step here, there's no security in the wrapper.
514 // policy.evaluate(*xmlObject.get(), &genericRequest);
516 return xmlObject.release();
519 void ADFSMessageRule::evaluate(const XMLObject& message, const GenericRequest* request, const XMLCh* protocol, SecurityPolicy& policy) const
521 Category& log=Category::getInstance(SHIBSP_LOGCAT".SecurityPolicyRule.ADFSMessage");
523 if (!XMLString::equals(protocol, m_protocol.get()))
526 const QName& q = message.getElementQName();
527 if (!XMLString::equals(q.getNamespaceURI(), samlconstants::SAML1_NS) ||
528 !XMLString::equals(q.getLocalPart(), saml1::Assertion::LOCAL_NAME))
532 const saml1::Assertion& token = dynamic_cast<const saml1::Assertion&>(message);
533 policy.setMessageID(token.getAssertionID());
534 policy.setIssueInstant(token.getIssueInstantEpoch());
536 log.debug("extracting issuer from message");
538 policy.setIssuer(token.getIssuer());
540 if (log.isDebugEnabled()) {
541 auto_ptr_char iname(token.getIssuer());
542 log.debug("message from (%s)", iname.get());
545 if (policy.getIssuerMetadata()) {
546 log.debug("metadata for issuer already set, leaving in place");
550 if (policy.getMetadataProvider() && policy.getRole()) {
551 log.debug("searching metadata for message issuer...");
552 const EntityDescriptor* entity = policy.getMetadataProvider()->getEntityDescriptor(token.getIssuer());
554 auto_ptr_char temp(token.getIssuer());
555 log.warn("no metadata found, can't establish identity of issuer (%s)", temp.get());
559 log.debug("matched message issuer against metadata, searching for applicable role...");
560 const RoleDescriptor* roledesc=entity->getRoleDescriptor(*policy.getRole(), m_protocol.get());
562 log.warn("unable to find compatible role (%s) in metadata", policy.getRole()->toString().c_str());
565 policy.setIssuerMetadata(roledesc);
570 log.warn("caught a bad_cast while examining message");
574 string ADFSConsumer::implementProtocol(
575 const Application& application,
576 const HTTPRequest& httpRequest,
577 SecurityPolicy& policy,
578 const PropertySet* settings,
579 const XMLObject& xmlObject
582 // Implementation of ADFS profile.
583 m_log.debug("processing message against ADFS Passive Requester profile");
585 // With ADFS, all the security comes from the assertion, which is two levels down in the message.
587 const ElementProxy* response = dynamic_cast<const ElementProxy*>(&xmlObject);
588 if (!response || !response->hasChildren())
589 throw FatalProfileException("Incoming message was not of the proper type or contains no security token.");
590 response = dynamic_cast<const ElementProxy*>(response->getUnknownXMLObjects().front());
591 if (!response || !response->hasChildren())
592 throw FatalProfileException("Token wrapper element did not contain a security token.");
593 const saml1::Assertion* token = dynamic_cast<const saml1::Assertion*>(response->getUnknownXMLObjects().front());
594 if (!token || !token->getSignature())
595 throw FatalProfileException("Incoming message did not contain a signed SAML 1.1 assertion.");
597 // Run the policy over the assertion. Handles issuer consistency, replay, freshness,
598 // and signature verification, assuming the relevant rules are configured.
599 policy.getRules().insert(policy.getRules().begin(), &m_messageRule);
600 policy.evaluate(*token, NULL, m_messageRule.m_protocol.get());
602 // If no security is in place now, we kick it.
603 if (!policy.isSecure())
604 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
606 // Now do profile and core semantic validation to ensure we can use it for SSO.
607 // Profile validator.
608 time_t now = time(NULL);
609 saml1::AssertionValidator ssoValidator(application.getAudiences(), now);
610 ssoValidator.validateAssertion(*token);
611 if (!token->getConditions() || !token->getConditions()->getNotBefore() || !token->getConditions()->getNotOnOrAfter())
612 throw FatalProfileException("Assertion did not contain time conditions.");
613 else if (token->getAuthenticationStatements().empty())
614 throw FatalProfileException("Assertion did not contain an authentication statement.");
616 // With ADFS, we only have one token, but we need to put it in a vector.
617 vector<const Assertion*> tokens(1,token);
618 const saml1::AuthenticationStatement* ssoStatement=token->getAuthenticationStatements().front();
621 saml1::SubjectLocality* locality = ssoStatement->getSubjectLocality();
622 if (locality && locality->getIPAddress()) {
623 auto_ptr_char ip(locality->getIPAddress());
624 checkAddress(application, httpRequest, ip.get());
627 m_log.debug("ADFS profile processing completed successfully");
629 saml1::NameIdentifier* n = ssoStatement->getSubject()->getNameIdentifier();
631 // Now we have to extract the authentication details for attribute and session setup.
633 // Session expiration for ADFS is purely SP-driven, and the method is mapped to a ctx class.
634 const PropertySet* sessionProps = application.getPropertySet("Sessions");
635 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
636 if (!lifetime.first || lifetime.second == 0)
637 lifetime.second = 28800;
639 // We've successfully "accepted" the SSO token.
640 // To complete processing, we need to extract and resolve attributes and then create the session.
641 vector<Attribute*> resolvedAttributes;
642 AttributeExtractor* extractor = application.getAttributeExtractor();
644 m_log.debug("extracting pushed attributes...");
645 Locker extlocker(extractor);
648 extractor->extractAttributes(application, policy.getIssuerMetadata(), *n, resolvedAttributes);
650 catch (exception& ex) {
651 m_log.error("caught exception extracting attributes: %s", ex.what());
655 extractor->extractAttributes(application, policy.getIssuerMetadata(), *token, resolvedAttributes);
657 catch (exception& ex) {
658 m_log.error("caught exception extracting attributes: %s", ex.what());
661 AttributeFilter* filter = application.getAttributeFilter();
662 if (filter && !resolvedAttributes.empty()) {
663 BasicFilteringContext fc(application, resolvedAttributes, policy.getIssuerMetadata(), ssoStatement->getAuthenticationMethod());
664 Locker filtlocker(filter);
666 filter->filterAttributes(fc, resolvedAttributes);
668 catch (exception& ex) {
669 m_log.error("caught exception filtering attributes: %s", ex.what());
670 m_log.error("dumping extracted attributes due to filtering exception");
671 for_each(resolvedAttributes.begin(), resolvedAttributes.end(), xmltooling::cleanup<shibsp::Attribute>());
672 resolvedAttributes.clear();
677 // Normalize the SAML 1.x NameIdentifier...
678 auto_ptr<saml2::NameID> nameid(n ? saml2::NameIDBuilder::buildNameID() : NULL);
680 nameid->setName(n->getName());
681 nameid->setFormat(n->getFormat());
682 nameid->setNameQualifier(n->getNameQualifier());
685 const EntityDescriptor* issuerMetadata =
686 policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL;
687 auto_ptr<ResolutionContext> ctx(
691 m_messageRule.m_protocol.get(),
693 ssoStatement->getAuthenticationMethod(),
701 // Copy over any new tokens, but leave them in the context for cleanup.
702 tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
704 // Copy over new attributes, and transfer ownership.
705 resolvedAttributes.insert(resolvedAttributes.end(), ctx->getResolvedAttributes().begin(), ctx->getResolvedAttributes().end());
706 ctx->getResolvedAttributes().clear();
710 string key = application.getServiceProvider().getSessionCache()->insert(
711 now + lifetime.second,
713 httpRequest.getRemoteAddr().c_str(),
715 m_messageRule.m_protocol.get(),
717 ssoStatement->getAuthenticationInstant() ? ssoStatement->getAuthenticationInstant()->getRawData() : NULL,
719 ssoStatement->getAuthenticationMethod(),
724 for_each(resolvedAttributes.begin(), resolvedAttributes.end(), xmltooling::cleanup<shibsp::Attribute>());
728 for_each(resolvedAttributes.begin(), resolvedAttributes.end(), xmltooling::cleanup<shibsp::Attribute>());
735 pair<bool,long> ADFSLogoutInitiator::run(SPRequest& request, bool isHandler) const
737 // Defer to base class for front-channel loop first.
738 pair<bool,long> ret = LogoutHandler::run(request, isHandler);
742 // At this point we know the front-channel is handled.
743 // We need the session to do any other work.
745 Session* session = NULL;
747 session = request.getSession(false, true, false); // don't cache it and ignore all checks
749 return make_pair(false,0);
751 // We only handle SAML 2.0 sessions.
752 if (!XMLString::equals(session->getProtocol(), WSFED_NS)) {
754 return make_pair(false,0);
757 catch (exception& ex) {
758 m_log.error("error accessing current session: %s", ex.what());
759 return make_pair(false,0);
762 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
763 // When out of process, we run natively.
764 return doRequest(request.getApplication(), request.getRequestURL(), session, request);
767 // When not out of process, we remote the request.
768 Locker locker(session);
769 DDF out,in(m_address.c_str());
770 DDFJanitor jin(in), jout(out);
771 in.addmember("application_id").string(request.getApplication().getId());
772 in.addmember("session_id").string(session->getID());
773 in.addmember("url").string(request.getRequestURL());
774 out=request.getServiceProvider().getListenerService()->send(in);
775 return unwrap(request, out);
779 void ADFSLogoutInitiator::receive(DDF& in, ostream& out)
783 const char* aid=in["application_id"].string();
784 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
786 // Something's horribly wrong.
787 m_log.error("couldn't find application (%s) for logout", aid ? aid : "(missing)");
788 throw ConfigurationException("Unable to locate application for logout, deleted?");
791 // Set up a response shim.
793 DDFJanitor jout(ret);
794 auto_ptr<HTTPResponse> resp(getResponse(ret));
796 Session* session = NULL;
798 session = app->getServiceProvider().getSessionCache()->find(in["session_id"].string(), *app, NULL, NULL);
800 catch (exception& ex) {
801 m_log.error("error accessing current session: %s", ex.what());
804 // With no session, we just skip the request and let it fall through to an empty struct return.
806 if (session->getEntityID()) {
807 // Since we're remoted, the result should either be a throw, which we pass on,
808 // a false/0 return, which we just return as an empty structure, or a response/redirect,
809 // which we capture in the facade and send back.
810 doRequest(*app, in["url"].string(), session, *resp.get());
813 m_log.error("no issuing entityID found in session");
816 app->getServiceProvider().getSessionCache()->remove(in["session_id"].string(), *app);
821 throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
825 pair<bool,long> ADFSLogoutInitiator::doRequest(
826 const Application& application, const char* requestURL, Session* session, HTTPResponse& response
829 string entityID(session->getEntityID());
830 vector<string> sessions(1, session->getID());
832 // Do back channel notification.
833 if (!notifyBackChannel(application, requestURL, sessions, false)) {
835 application.getServiceProvider().getSessionCache()->remove(sessions.front().c_str(), application);
836 return sendLogoutPage(application, response, true, "Partial logout failure.");
840 application.getServiceProvider().getSessionCache()->remove(sessions.front().c_str(), application);
844 // With a session in hand, we can create a request message, if we can find a compatible endpoint.
845 Locker metadataLocker(application.getMetadataProvider());
846 const EntityDescriptor* entity = application.getMetadataProvider()->getEntityDescriptor(entityID.c_str());
848 throw MetadataException(
849 "Unable to locate metadata for identity provider ($entityID)",
850 namedparams(1, "entityID", entityID.c_str())
853 const IDPSSODescriptor* role = entity->getIDPSSODescriptor(m_binding.get());
855 throw MetadataException(
856 "Unable to locate ADFS IdP role for identity provider ($entityID).",
857 namedparams(1, "entityID", entityID.c_str())
861 const EndpointType* ep = EndpointManager<SingleLogoutService>(role->getSingleLogoutServices()).getByBinding(m_binding.get());
863 throw MetadataException(
864 "Unable to locate ADFS single logout service for identity provider ($entityID).",
865 namedparams(1, "entityID", entityID.c_str())
869 auto_ptr_char dest(ep->getLocation());
871 string req=string(dest.get()) + (strchr(dest.get(),'?') ? '&' : '?') + "wa=wsignout1.0";
872 return make_pair(true,response.sendRedirect(req.c_str()));
874 catch (exception& ex) {
875 m_log.error("error issuing ADFS logout request: %s", ex.what());
878 return make_pair(false,0);
880 throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
884 pair<bool,long> ADFSLogout::run(SPRequest& request, bool isHandler) const
886 // Defer to base class for front-channel loop first.
887 // This won't initiate the loop, only continue/end it.
888 pair<bool,long> ret = LogoutHandler::run(request, isHandler);
892 // wa parameter indicates the "action" to perform
893 bool returning = false;
894 const char* param = request.getParameter("wa");
896 if (!strcmp(param, "wsignin1.0"))
897 return m_login.run(request, isHandler);
898 else if (strcmp(param, "wsignout1.0") && strcmp(param, "wsignoutcleanup1.0"))
899 throw FatalProfileException("Unsupported WS-Federation action paremeter ($1).", params(1, param));
901 else if (strcmp(request.getMethod(),"GET") || !request.getParameter("notifying"))
902 throw FatalProfileException("Unsupported request to ADFS protocol endpoint.");
906 param = request.getParameter("wreply");
907 const Application& app = request.getApplication();
909 // Get the session_id.
910 pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_");
911 const char* session_id = request.getCookie(shib_cookie.first.c_str());
914 // Pass control to the first front channel notification point, if any.
915 map<string,string> parammap;
917 parammap["wreply"] = param;
918 pair<bool,long> result = notifyFrontChannel(app, request, request, ¶mmap);
923 // Best effort on back channel and to remove the user agent's session.
925 vector<string> sessions(1,session_id);
926 notifyBackChannel(app, request.getRequestURL(), sessions, false);
928 app.getServiceProvider().getSessionCache()->remove(session_id, app);
930 catch (exception& ex) {
931 m_log.error("error removing session (%s): %s", session_id, ex.what());
936 return make_pair(true, request.sendRedirect(param));
937 return sendLogoutPage(app, request, false, "Logout complete.");