2 * Copyright 2001-2005 Internet2
\r
4 * Licensed under the Apache License, Version 2.0 (the "License");
\r
5 * you may not use this file except in compliance with the License.
\r
6 * You may obtain a copy of the License at
\r
8 * http://www.apache.org/licenses/LICENSE-2.0
\r
10 * Unless required by applicable law or agreed to in writing, software
\r
11 * distributed under the License is distributed on an "AS IS" BASIS,
\r
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
\r
13 * See the License for the specific language governing permissions and
\r
14 * limitations under the License.
\r
20 * ADFSv1 extension library
\r
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)
\r
34 # define ADFS_EXPORTS
\r
37 #include <shibsp/base.h>
\r
38 #include <shibsp/exceptions.h>
\r
39 #include <shibsp/Application.h>
\r
40 #include <shibsp/ServiceProvider.h>
\r
41 #include <shibsp/SessionCache.h>
\r
42 #include <shibsp/SPConfig.h>
\r
43 #include <shibsp/handler/AssertionConsumerService.h>
\r
44 #include <shibsp/handler/LogoutHandler.h>
\r
45 #include <shibsp/handler/SessionInitiator.h>
46 #include <xmltooling/util/NDC.h>
47 #include <xmltooling/util/URLEncoder.h>
48 #include <xmltooling/util/XMLHelper.h>
49 #include <log4cpp/Category.hh>
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>
\r
59 # include <saml/saml1/core/Assertions.h>
\r
60 # include <saml/saml1/profile/AssertionValidator.h>
\r
61 # include <saml/saml2/core/Assertions.h>
\r
62 # include <saml/saml2/metadata/Metadata.h>
\r
63 # include <saml/saml2/metadata/EndpointManager.h>
64 # include <xmltooling/impl/AnyElement.h>
65 # include <xmltooling/validation/ValidatorSuite.h>
\r
66 using namespace opensaml::saml2md;
\r
68 using namespace shibsp;
\r
69 using namespace opensaml;
\r
70 using namespace xmltooling;
\r
71 using namespace xercesc;
\r
72 using namespace log4cpp;
\r
73 using namespace std;
\r
75 #define WSFED_NS "http://schemas.xmlsoap.org/ws/2003/07/secext"
\r
76 #define WSTRUST_NS "http://schemas.xmlsoap.org/ws/2005/02/trust"
\r
80 #if defined (_MSC_VER)
81 #pragma warning( push )
82 #pragma warning( disable : 4250 )
85 class SHIBSP_DLLLOCAL ADFSSessionInitiator : public SessionInitiator, public AbstractHandler, public RemotedHandler
88 ADFSSessionInitiator(const DOMElement* e, const char* appId)
89 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator")), m_appId(appId), m_binding(WSFED_NS) {
90 // If Location isn't set, defer address registration until the setParent call.
91 pair<bool,const char*> loc = getString("Location");
93 string address = m_appId + loc.second + "::run::ADFSSI";
94 setAddress(address.c_str());
97 virtual ~ADFSSessionInitiator() {}
99 void setParent(const PropertySet* parent) {
100 DOMPropertySet::setParent(parent);
101 pair<bool,const char*> loc = getString("Location");
103 string address = m_appId + loc.second + "::run::ADFSSI";
104 setAddress(address.c_str());
107 m_log.warn("no Location property in ADFS SessionInitiator (or parent), can't register as remoted handler");
111 void receive(DDF& in, ostream& out);
112 pair<bool,long> run(SPRequest& request, const char* entityID=NULL, bool isHandler=true) const;
115 pair<bool,long> doRequest(
116 const Application& application,
117 HTTPResponse& httpResponse,
118 const char* entityID,
119 const char* acsLocation,
123 auto_ptr_XMLCh m_binding;
126 class SHIBSP_DLLLOCAL ADFSConsumer : public shibsp::AssertionConsumerService
129 ADFSConsumer(const DOMElement* e, const char* appId)
130 : shibsp::AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SSO.ADFS"))
135 virtual ~ADFSConsumer() {}
139 string implementProtocol(
140 const Application& application,
141 const HTTPRequest& httpRequest,
142 SecurityPolicy& policy,
143 const PropertySet* settings,
144 const XMLObject& xmlObject
146 auto_ptr_XMLCh m_binding;
150 class SHIBSP_DLLLOCAL ADFSLogoutInitiator : public AbstractHandler, public LogoutHandler
153 ADFSLogoutInitiator(const DOMElement* e, const char* appId)
154 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator")), m_appId(appId), m_binding(WSFED_NS) {
155 // If Location isn't set, defer address registration until the setParent call.
156 pair<bool,const char*> loc = getString("Location");
158 string address = m_appId + loc.second + "::run::ADFSLI";
159 setAddress(address.c_str());
162 virtual ~ADFSLogoutInitiator() {}
164 void setParent(const PropertySet* parent) {
165 DOMPropertySet::setParent(parent);
166 pair<bool,const char*> loc = getString("Location");
168 string address = m_appId + loc.second + "::run::ADFSLI";
169 setAddress(address.c_str());
172 m_log.warn("no Location property in ADFS LogoutInitiator (or parent), can't register as remoted handler");
176 void receive(DDF& in, ostream& out);
177 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
180 pair<bool,long> doRequest(
181 const Application& application, const char* requestURL, Session* session, HTTPResponse& httpResponse
185 auto_ptr_XMLCh m_binding;
188 class SHIBSP_DLLLOCAL ADFSLogout : public AbstractHandler, public LogoutHandler
191 ADFSLogout(const DOMElement* e, const char* appId)
192 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".Logout.ADFS")), m_login(e, appId) {
195 m_preserve.push_back("wreply");
196 string address = string(appId) + getString("Location").second + "::run::ADFSLO";
197 setAddress(address.c_str());
200 virtual ~ADFSLogout() {}
202 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
205 ADFSConsumer m_login;
208 #if defined (_MSC_VER)
209 #pragma warning( pop )
213 class ADFSDecoder : public MessageDecoder
\r
217 ADFSDecoder() : m_ns(WSTRUST_NS) {}
\r
218 virtual ~ADFSDecoder() {}
\r
220 XMLObject* decode(string& relayState, const GenericRequest& genericRequest, SecurityPolicy& policy) const;
\r
223 MessageDecoder* ADFSDecoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
\r
225 return new ADFSDecoder();
\r
229 SessionInitiator* ADFSSessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
231 return new ADFSSessionInitiator(p.first, p.second);
234 Handler* ADFSLogoutFactory(const pair<const DOMElement*,const char*>& p)
236 return new ADFSLogout(p.first, p.second);
239 Handler* ADFSLogoutInitiatorFactory(const pair<const DOMElement*,const char*>& p)
241 return new ADFSLogoutInitiator(p.first, p.second);
244 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);
\r
245 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);
\r
248 extern "C" int ADFS_EXPORTS xmltooling_extension_init(void*)
\r
250 SPConfig& conf=SPConfig::getConfig();
251 conf.SessionInitiatorManager.registerFactory("ADFS", ADFSSessionInitiatorFactory);
252 conf.LogoutInitiatorManager.registerFactory("ADFS", ADFSLogoutInitiatorFactory);
253 conf.AssertionConsumerServiceManager.registerFactory("ADFS", ADFSLogoutFactory);
254 conf.AssertionConsumerServiceManager.registerFactory(WSFED_NS, ADFSLogoutFactory);
256 SAMLConfig::getConfig().MessageDecoderManager.registerFactory(WSFED_NS, ADFSDecoderFactory);
257 XMLObjectBuilder::registerBuilder(QName(WSTRUST_NS,"RequestedSecurityToken"), new AnyElementBuilder());
258 XMLObjectBuilder::registerBuilder(QName(WSTRUST_NS,"RequestedSecurityTokenResponse"), new AnyElementBuilder());
263 extern "C" void ADFS_EXPORTS xmltooling_extension_term()
\r
265 /* should get unregistered during normal shutdown...
\r
266 SPConfig& conf=SPConfig::getConfig();
\r
267 conf.SessionInitiatorManager.deregisterFactory("ADFS");
\r
268 conf.LogoutInitiatorManager.deregisterFactory("ADFS");
\r
269 conf.AssertionConsumerServiceManager.deregisterFactory("ADFS");
\r
270 conf.AssertionConsumerServiceManager.deregisterFactory(WSFED_NS);
\r
272 SAMLConfig::getConfig().MessageDecoderManager.deregisterFactory(WSFED_NS);
277 pair<bool,long> ADFSSessionInitiator::run(SPRequest& request, const char* entityID, bool isHandler) const
279 // We have to know the IdP to function.
280 if (!entityID || !*entityID)
281 return make_pair(false,0);
284 const Handler* ACS=NULL;
286 const Application& app=request.getApplication();
289 option = request.getParameter("target");
293 // Since we're passing the ACS by value, we need to compute the return URL,
294 // so we'll need the target resource for real.
295 recoverRelayState(request.getApplication(), request, target, false);
298 // We're running as a "virtual handler" from within the filter.
299 // The target resource is the current one and everything else is defaulted.
300 target=request.getRequestURL();
303 // Since we're not passing by index, we need to fully compute the return URL.
305 // Get all the ADFS endpoints.
306 const vector<const Handler*>& handlers = app.getAssertionConsumerServicesByBinding(m_binding.get());
308 // Index comes from request, or default set in the handler, or we just pick the first endpoint.
309 pair<bool,unsigned int> index = make_pair(false,0);
311 option = request.getParameter("acsIndex");
313 index = make_pair(true, atoi(option));
316 index = getUnsignedInt("defaultACSIndex");
318 for (vector<const Handler*>::const_iterator h = handlers.begin(); !ACS && h!=handlers.end(); ++h) {
319 if (index.second == (*h)->getUnsignedInt("index").second)
323 else if (!handlers.empty()) {
324 ACS = handlers.front();
328 throw ConfigurationException("Unable to locate ADFS response endpoint.");
330 // Compute the ACS URL. We add the ACS location to the base handlerURL.
331 string ACSloc=request.getHandlerURL(target.c_str());
332 pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
333 if (loc.first) ACSloc+=loc.second;
336 // We may already have RelayState set if we looped back here,
337 // but just in case target is a resource, we reset it back.
339 option = request.getParameter("target");
344 m_log.debug("attempting to initiate session using ADFS with provider (%s)", entityID);
346 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess))
347 return doRequest(app, request, entityID, ACSloc.c_str(), target);
350 DDF out,in = DDF(m_address.c_str()).structure();
351 DDFJanitor jin(in), jout(out);
352 in.addmember("application_id").string(app.getId());
353 in.addmember("entity_id").string(entityID);
354 in.addmember("acsLocation").string(ACSloc.c_str());
356 in.addmember("RelayState").string(target.c_str());
358 // Remote the processing.
359 out = request.getServiceProvider().getListenerService()->send(in);
360 return unwrap(request, out);
363 void ADFSSessionInitiator::receive(DDF& in, ostream& out)
366 const char* aid=in["application_id"].string();
367 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
369 // Something's horribly wrong.
370 m_log.error("couldn't find application (%s) to generate ADFS request", aid ? aid : "(missing)");
371 throw ConfigurationException("Unable to locate application for new session, deleted?");
374 const char* entityID = in["entity_id"].string();
375 const char* acsLocation = in["acsLocation"].string();
376 if (!entityID || !acsLocation)
377 throw ConfigurationException("No entityID or acsLocation parameter supplied to remoted SessionInitiator.");
380 DDFJanitor jout(ret);
382 // Wrap the outgoing object with a Response facade.
383 auto_ptr<HTTPResponse> http(getResponse(ret));
385 string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");
387 // Since we're remoted, the result should either be a throw, which we pass on,
388 // a false/0 return, which we just return as an empty structure, or a response/redirect,
389 // which we capture in the facade and send back.
390 doRequest(*app, *http.get(), entityID, acsLocation, relayState);
394 pair<bool,long> ADFSSessionInitiator::doRequest(
395 const Application& app,
396 HTTPResponse& httpResponse,
397 const char* entityID,
398 const char* acsLocation,
403 // Use metadata to invoke the SSO service directly.
404 MetadataProvider* m=app.getMetadataProvider();
406 const EntityDescriptor* entity=m->getEntityDescriptor(entityID);
408 m_log.error("unable to locate metadata for provider (%s)", entityID);
409 throw MetadataException("Unable to locate metadata for identity provider ($entityID)",
410 namedparams(1, "entityID", entityID));
412 const IDPSSODescriptor* role=entity->getIDPSSODescriptor(m_binding.get());
414 m_log.error("unable to locate ADFS-aware identity provider role for provider (%s)", entityID);
415 return make_pair(false,0);
417 const EndpointType* ep=EndpointManager<SingleSignOnService>(role->getSingleSignOnServices()).getByBinding(m_binding.get());
419 m_log.error("unable to locate compatible SSO service for provider (%s)", entityID);
420 return make_pair(false,0);
423 preserveRelayState(app, httpResponse, relayState);
426 #ifndef HAVE_GMTIME_R
\r
427 time_t epoch=time(NULL);
\r
428 struct tm* ptime=gmtime(&epoch);
\r
431 struct tm* ptime=gmtime_r(&epoch,&res);
\r
434 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
\r
436 auto_ptr_char dest(ep->getLocation());
437 const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
439 string req=string(dest.get()) + (strchr(dest.get(),'?') ? '&' : '?') + "wa=wsignin1.0&wreply=" + urlenc->encode(acsLocation) +
440 "&wct=" + urlenc->encode(timebuf) + "&wtrealm=" + urlenc->encode(app.getString("entityID").second);
441 if (!relayState.empty())
442 req += "&wctx=" + urlenc->encode(relayState.c_str());
444 return make_pair(true, httpResponse.sendRedirect(req.c_str()));
446 return make_pair(false,0);
452 XMLObject* ADFSDecoder::decode(string& relayState, const GenericRequest& genericRequest, SecurityPolicy& policy) const
\r
455 xmltooling::NDC ndc("decode");
\r
457 Category& log = Category::getInstance(SHIBSP_LOGCAT".MessageDecoder.ADFS");
\r
459 log.debug("validating input");
\r
460 const HTTPRequest* httpRequest=dynamic_cast<const HTTPRequest*>(&genericRequest);
\r
462 throw BindingException("Unable to cast request object to HTTPRequest type.");
\r
463 if (strcmp(httpRequest->getMethod(),"POST"))
\r
464 throw BindingException("Invalid HTTP method ($1).", params(1, httpRequest->getMethod()));
\r
465 const char* param = httpRequest->getParameter("wa");
\r
466 if (!param || strcmp(param, "wsignin1.0"))
\r
467 throw BindingException("Missing or invalid wa parameter (should be wsignin1.0).");
\r
468 param = httpRequest->getParameter("wctx");
\r
470 relayState = param;
\r
472 param = httpRequest->getParameter("wresult");
\r
474 throw BindingException("Request missing wresult parameter.");
\r
476 log.debug("decoded ADFS response:\n%s", param);
\r
478 // Parse and bind the document into an XMLObject.
\r
479 istringstream is(param);
\r
480 DOMDocument* doc = (policy.getValidating() ? XMLToolingConfig::getConfig().getValidatingParser()
\r
481 : XMLToolingConfig::getConfig().getParser()).parse(is);
\r
482 XercesJanitor<DOMDocument> janitor(doc);
\r
483 auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
\r
486 if (!XMLHelper::isNodeNamed(xmlObject->getDOM(), m_ns.get(), RequestSecurityTokenResponse))
\r
487 throw BindingException("Decoded message was not of the appropriate type.");
\r
489 if (!policy.getValidating())
\r
490 SchemaValidators.validate(xmlObject.get());
\r
492 // Run through the policy.
\r
493 policy.evaluate(*xmlObject.get(), &genericRequest);
\r
495 return xmlObject.release();
\r
498 string ADFSConsumer::implementProtocol(
499 const Application& application,
500 const HTTPRequest& httpRequest,
501 SecurityPolicy& policy,
502 const PropertySet* settings,
503 const XMLObject& xmlObject
506 // Implementation of ADFS profile.
507 m_log.debug("processing message against ADFS Passive Requester profile");
509 // With ADFS, all the security comes from the assertion, which is two levels down in the message.
511 const ElementProxy* response = dynamic_cast<const ElementProxy*>(&xmlObject);
512 if (!response || !response->hasChildren())
513 throw FatalProfileException("Incoming message was not of the proper type or contains no security token.");
514 response = dynamic_cast<const ElementProxy*>(response->getUnknownXMLObjects().front());
515 if (!response || !response->hasChildren())
516 throw FatalProfileException("Token wrapper element did not contain a security token.");
517 const saml1::Assertion* token = dynamic_cast<const saml1::Assertion*>(response->getUnknownXMLObjects().front());
518 if (!token || !token->getSignature())
519 throw FatalProfileException("Incoming message did not contain a signed SAML 1.1 assertion.");
521 // Run the policy over the assertion. Handles issuer consistency, replay, freshness,
522 // and signature verification, assuming the relevant rules are configured.
523 policy.evaluate(*token);
525 // If no security is in place now, we kick it.
526 if (!policy.isSecure())
527 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
529 // Now do profile and core semantic validation to ensure we can use it for SSO.
530 // Profile validator.
531 time_t now = time(NULL);
532 saml1::AssertionValidator ssoValidator(application.getAudiences(), now);
533 ssoValidator.validateAssertion(*token);
534 if (!token->getConditions() || !token->getConditions()->getNotBefore() || !token->getConditions()->getNotOnOrAfter())
535 throw FatalProfileException("Assertion did not contain time conditions.");
536 else if (token->getAuthenticationStatements().empty())
537 throw FatalProfileException("Assertion did not contain an authentication statement.");
539 // With ADFS, we only have one token, but we need to put it in a vector.
540 vector<const Assertion*> tokens(1,token);
541 const saml1::AuthenticationStatement* ssoStatement=token->getAuthenticationStatements().front();
544 saml1::SubjectLocality* locality = ssoStatement->getSubjectLocality();
545 if (locality && locality->getIPAddress()) {
546 auto_ptr_char ip(locality->getIPAddress());
547 checkAddress(application, httpRequest, ip.get());
550 m_log.debug("ADFS profile processing completed successfully");
552 saml1::NameIdentifier* n = ssoStatement->getSubject()->getNameIdentifier();
554 // Now we have to extract the authentication details for attribute and session setup.
556 // Session expiration for ADFS is purely SP-driven, and the method is mapped to a ctx class.
557 const PropertySet* sessionProps = application.getPropertySet("Sessions");
558 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
559 if (!lifetime.first || lifetime.second == 0)
560 lifetime.second = 28800;
562 // We've successfully "accepted" the SSO token.
563 // To complete processing, we need to extract and resolve attributes and then create the session.
564 multimap<string,Attribute*> resolvedAttributes;
565 AttributeExtractor* extractor = application.getAttributeExtractor();
567 m_log.debug("extracting pushed attributes...");
568 Locker extlocker(extractor);
571 extractor->extractAttributes(application, policy.getIssuerMetadata(), *n, resolvedAttributes);
573 catch (exception& ex) {
574 m_log.error("caught exception extracting attributes: %s", ex.what());
578 extractor->extractAttributes(application, policy.getIssuerMetadata(), *token, resolvedAttributes);
580 catch (exception& ex) {
581 m_log.error("caught exception extracting attributes: %s", ex.what());
584 AttributeFilter* filter = application.getAttributeFilter();
585 if (filter && !resolvedAttributes.empty()) {
586 BasicFilteringContext fc(application, resolvedAttributes, policy.getIssuerMetadata(), ssoStatement->getAuthenticationMethod());
587 Locker filtlocker(filter);
589 filter->filterAttributes(fc, resolvedAttributes);
591 catch (exception& ex) {
592 m_log.error("caught exception filtering attributes: %s", ex.what());
593 m_log.error("dumping extracted attributes due to filtering exception");
594 for_each(resolvedAttributes.begin(), resolvedAttributes.end(), cleanup_pair<string,shibsp::Attribute>());
595 resolvedAttributes.clear();
600 // Normalize the SAML 1.x NameIdentifier...
601 auto_ptr<saml2::NameID> nameid(n ? saml2::NameIDBuilder::buildNameID() : NULL);
603 nameid->setName(n->getName());
604 nameid->setFormat(n->getFormat());
605 nameid->setNameQualifier(n->getNameQualifier());
608 const EntityDescriptor* issuerMetadata =
609 policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL;
610 auto_ptr<ResolutionContext> ctx(
616 ssoStatement->getAuthenticationMethod(),
624 // Copy over any new tokens, but leave them in the context for cleanup.
625 tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
627 // Copy over new attributes, and transfer ownership.
628 resolvedAttributes.insert(ctx->getResolvedAttributes().begin(), ctx->getResolvedAttributes().end());
629 ctx->getResolvedAttributes().clear();
633 string key = application.getServiceProvider().getSessionCache()->insert(
634 now + lifetime.second,
636 httpRequest.getRemoteAddr().c_str(),
640 ssoStatement->getAuthenticationInstant() ? ssoStatement->getAuthenticationInstant()->getRawData() : NULL,
642 ssoStatement->getAuthenticationMethod(),
647 for_each(resolvedAttributes.begin(), resolvedAttributes.end(), cleanup_pair<string,Attribute>());
651 for_each(resolvedAttributes.begin(), resolvedAttributes.end(), cleanup_pair<string,Attribute>());
658 pair<bool,long> ADFSLogoutInitiator::run(SPRequest& request, bool isHandler) const
660 // Defer to base class for front-channel loop first.
661 pair<bool,long> ret = LogoutHandler::run(request, isHandler);
665 // At this point we know the front-channel is handled.
666 // We need the session to do any other work.
668 Session* session = NULL;
670 session = request.getSession(false, true, false); // don't cache it and ignore all checks
672 return make_pair(false,0);
674 // We only handle SAML 2.0 sessions.
675 if (!XMLString::equals(session->getProtocol(), WSFED_NS)) {
677 return make_pair(false,0);
680 catch (exception& ex) {
681 m_log.error("error accessing current session: %s", ex.what());
682 return make_pair(false,0);
685 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
686 // When out of process, we run natively.
687 return doRequest(request.getApplication(), request.getRequestURL(), session, request);
690 // When not out of process, we remote the request.
691 Locker locker(session);
692 DDF out,in(m_address.c_str());
693 DDFJanitor jin(in), jout(out);
694 in.addmember("application_id").string(request.getApplication().getId());
695 in.addmember("session_id").string(session->getID());
696 in.addmember("url").string(request.getRequestURL());
697 out=request.getServiceProvider().getListenerService()->send(in);
698 return unwrap(request, out);
702 void ADFSLogoutInitiator::receive(DDF& in, ostream& out)
706 const char* aid=in["application_id"].string();
707 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
709 // Something's horribly wrong.
710 m_log.error("couldn't find application (%s) for logout", aid ? aid : "(missing)");
711 throw ConfigurationException("Unable to locate application for logout, deleted?");
714 // Set up a response shim.
716 DDFJanitor jout(ret);
717 auto_ptr<HTTPResponse> resp(getResponse(ret));
719 Session* session = NULL;
721 session = app->getServiceProvider().getSessionCache()->find(in["session_id"].string(), *app, NULL, NULL);
723 catch (exception& ex) {
724 m_log.error("error accessing current session: %s", ex.what());
727 // With no session, we just skip the request and let it fall through to an empty struct return.
729 if (session->getEntityID()) {
730 // Since we're remoted, the result should either be a throw, which we pass on,
731 // a false/0 return, which we just return as an empty structure, or a response/redirect,
732 // which we capture in the facade and send back.
733 doRequest(*app, in["url"].string(), session, *resp.get());
736 m_log.error("no issuing entityID found in session");
739 app->getServiceProvider().getSessionCache()->remove(in["session_id"].string(), *app);
744 throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
748 pair<bool,long> ADFSLogoutInitiator::doRequest(
749 const Application& application, const char* requestURL, Session* session, HTTPResponse& response
752 string entityID(session->getEntityID());
753 vector<string> sessions(1, session->getID());
755 // Do back channel notification.
756 if (!notifyBackChannel(application, requestURL, sessions, false)) {
758 application.getServiceProvider().getSessionCache()->remove(sessions.front().c_str(), application);
759 return sendLogoutPage(application, response, true, "Partial logout failure.");
763 application.getServiceProvider().getSessionCache()->remove(sessions.front().c_str(), application);
767 // With a session in hand, we can create a request message, if we can find a compatible endpoint.
768 Locker metadataLocker(application.getMetadataProvider());
769 const EntityDescriptor* entity = application.getMetadataProvider()->getEntityDescriptor(entityID.c_str());
771 throw MetadataException(
772 "Unable to locate metadata for identity provider ($entityID)",
773 namedparams(1, "entityID", entityID.c_str())
776 const IDPSSODescriptor* role = entity->getIDPSSODescriptor(m_binding.get());
778 throw MetadataException(
779 "Unable to locate ADFS IdP role for identity provider ($entityID).",
780 namedparams(1, "entityID", entityID.c_str())
784 const EndpointType* ep = EndpointManager<SingleLogoutService>(role->getSingleLogoutServices()).getByBinding(m_binding.get());
786 throw MetadataException(
787 "Unable to locate ADFS single logout service for identity provider ($entityID).",
788 namedparams(1, "entityID", entityID.c_str())
792 auto_ptr_char dest(ep->getLocation());
794 string req=string(dest.get()) + (strchr(dest.get(),'?') ? '&' : '?') + "wa=wsignout1.0";
795 return make_pair(true,response.sendRedirect(req.c_str()));
797 catch (exception& ex) {
798 m_log.error("error issuing ADFS logout request: %s", ex.what());
801 return make_pair(false,0);
803 throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
807 pair<bool,long> ADFSLogout::run(SPRequest& request, bool isHandler) const
809 // Defer to base class for front-channel loop first.
810 // This won't initiate the loop, only continue/end it.
811 pair<bool,long> ret = LogoutHandler::run(request, isHandler);
815 // wa parameter indicates the "action" to perform
816 bool returning = false;
817 const char* param = request.getParameter("wa");
819 if (!strcmp(param, "wsignin1.0"))
820 return m_login.run(request, isHandler);
821 else if (strcmp(param, "wsignout1.0") && strcmp(param, "wsignoutcleanup1.0"))
822 throw FatalProfileException("Unsupported WS-Federation action paremeter ($1).", params(1, param));
824 else if (strcmp(request.getMethod(),"GET") || !request.getParameter("notifying"))
825 throw FatalProfileException("Unsupported request to ADFS protocol endpoint.");
829 param = request.getParameter("wreply");
830 const Application& app = request.getApplication();
832 // Get the session_id.
833 pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_");
834 const char* session_id = request.getCookie(shib_cookie.first.c_str());
837 // Pass control to the first front channel notification point, if any.
838 map<string,string> parammap;
840 parammap["wreply"] = param;
841 pair<bool,long> result = notifyFrontChannel(app, request, request, ¶mmap);
846 // Best effort on back channel and to remove the user agent's session.
848 vector<string> sessions(1,session_id);
849 notifyBackChannel(app, request.getRequestURL(), sessions, false);
851 app.getServiceProvider().getSessionCache()->remove(session_id, app);
853 catch (exception& ex) {
854 m_log.error("error removing session (%s): %s", session_id, ex.what());
859 return make_pair(true, request.sendRedirect(param));
860 return sendLogoutPage(app, request, false, "Logout complete.");