-/*
- * Copyright 2001-2005 Internet2
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* adfs.cpp - bootstraps the ADFS extension library
-
- Scott Cantor
- 10/10/05
-*/
-
-#ifdef WIN32
-# define ADFS_EXPORTS __declspec(dllexport)
-#else
-# define ADFS_EXPORTS
-#endif
-
-#include "internal.h"
-
-#include <xercesc/util/Base64.hpp>
-
-
-using namespace std;
-using namespace saml;
-using namespace shibboleth;
-using namespace adfs;
-using namespace log4cpp;
-
-// Plugin Factories
-PlugManager::Factory ADFSListenerFactory;
-PlugManager::Factory ADFSSessionInitiatorFactory;
-PlugManager::Factory ADFSHandlerFactory;
-
-
-extern "C" int ADFS_EXPORTS saml_extension_init(void*)
-{
- // Register extension schema.
- saml::XML::registerSchema(adfs::XML::WSTRUST_NS,adfs::XML::WSTRUST_SCHEMA_ID);
-
- // Register plugin factories (some override existing Shib functionality).
- SAMLConfig& conf=SAMLConfig::getConfig();
- conf.getPlugMgr().regFactory(shibtarget::XML::MemoryListenerType,&ADFSListenerFactory);
-
- auto_ptr_char temp1(Constants::SHIB_SESSIONINIT_PROFILE_URI);
- conf.getPlugMgr().regFactory(temp1.get(),&ADFSSessionInitiatorFactory);
-
- auto_ptr_char temp2(adfs::XML::WSFED_NS);
- conf.getPlugMgr().regFactory(temp2.get(),&ADFSHandlerFactory);
-
- return 0;
-}
-
-extern "C" void ADFS_EXPORTS saml_extension_term()
-{
- // Unregister metadata factories
- SAMLConfig& conf=SAMLConfig::getConfig();
- conf.getPlugMgr().unregFactory(shibtarget::XML::MemoryListenerType);
-
- auto_ptr_char temp1(Constants::SHIB_SESSIONINIT_PROFILE_URI);
- conf.getPlugMgr().unregFactory(temp1.get());
-
- auto_ptr_char temp2(adfs::XML::WSFED_NS);
- conf.getPlugMgr().unregFactory(temp2.get());
-}
-
-// For now, we'll just put the meat of the profile here.
-
-SAMLAuthenticationStatement* adfs::checkAssertionProfile(const SAMLAssertion* a)
-{
- // Is it signed?
- if (!a->isSigned())
- throw FatalProfileException("rejected unsigned ADFS assertion");
-
- // Is it valid?
- time_t now=time(NULL);
- SAMLConfig& config=SAMLConfig::getConfig();
- if (a->getIssueInstant()->getEpoch() < now-(2*config.clock_skew_secs))
- throw ExpiredAssertionException("rejected expired ADFS assertion");
-
- const SAMLDateTime* notBefore=a->getNotBefore();
- const SAMLDateTime* notOnOrAfter=a->getNotOnOrAfter();
- if (!notBefore || !notOnOrAfter)
- throw ExpiredAssertionException("rejected ADFS assertion without time conditions");
- if (now+config.clock_skew_secs < notBefore->getEpoch())
- throw ExpiredAssertionException("rejected ADFS assertion that is not yet valid");
- if (notOnOrAfter->getEpoch() <= now-config.clock_skew_secs)
- throw ExpiredAssertionException("rejected expired ADFS assertion");
-
- // Look for an authentication statement.
- SAMLAuthenticationStatement* as=NULL;
- for (Iterator<SAMLStatement*> statements=a->getStatements(); !as && statements.hasNext();)
- as=dynamic_cast<SAMLAuthenticationStatement*>(statements.next());
- if (!as)
- throw FatalProfileException("rejecting ADFS assertion without authentication statement");
-
- return as;
-}
-
-/*************************************************************************
- * CGI Parser implementation
- */
-
-CgiParse::CgiParse(const char* data, unsigned int len)
-{
- const char* pch = data;
- unsigned int cl = len;
-
- while (cl && pch) {
- char *name;
- char *value;
- value=fmakeword('&',&cl,&pch);
- plustospace(value);
- url_decode(value);
- name=makeword(value,'=');
- kvp_map[name]=value;
- free(name);
- }
-}
-
-CgiParse::~CgiParse()
-{
- for (map<string,char*>::iterator i=kvp_map.begin(); i!=kvp_map.end(); i++)
- free(i->second);
-}
-
-const char*
-CgiParse::get_value(const char* name) const
-{
- map<string,char*>::const_iterator i=kvp_map.find(name);
- if (i==kvp_map.end())
- return NULL;
- return i->second;
-}
-
-/* Parsing routines modified from NCSA source. */
-char *
-CgiParse::makeword(char *line, char stop)
-{
- int x = 0,y;
- char *word = (char *) malloc(sizeof(char) * (strlen(line) + 1));
-
- for(x=0;((line[x]) && (line[x] != stop));x++)
- word[x] = line[x];
-
- word[x] = '\0';
- if(line[x])
- ++x;
- y=0;
-
- while(line[x])
- line[y++] = line[x++];
- line[y] = '\0';
- return word;
-}
-
-char *
-CgiParse::fmakeword(char stop, unsigned int *cl, const char** ppch)
-{
- int wsize;
- char *word;
- int ll;
-
- wsize = 1024;
- ll=0;
- word = (char *) malloc(sizeof(char) * (wsize + 1));
-
- while(1)
- {
- word[ll] = *((*ppch)++);
- if(ll==wsize-1)
- {
- word[ll+1] = '\0';
- wsize+=1024;
- word = (char *)realloc(word,sizeof(char)*(wsize+1));
- }
- --(*cl);
- if((word[ll] == stop) || word[ll] == EOF || (!(*cl)))
- {
- if(word[ll] != stop)
- ll++;
- word[ll] = '\0';
- return word;
- }
- ++ll;
- }
-}
-
-void
-CgiParse::plustospace(char *str)
-{
- register int x;
-
- for(x=0;str[x];x++)
- if(str[x] == '+') str[x] = ' ';
-}
-
-char
-CgiParse::x2c(char *what)
-{
- register char digit;
-
- digit = (what[0] >= 'A' ? ((what[0] & 0xdf) - 'A')+10 : (what[0] - '0'));
- digit *= 16;
- digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A')+10 : (what[1] - '0'));
- return(digit);
-}
-
-void
-CgiParse::url_decode(char *url)
-{
- register int x,y;
-
- for(x=0,y=0;url[y];++x,++y)
- {
- if((url[x] = url[y]) == '%')
- {
- url[x] = x2c(&url[y+1]);
- y+=2;
- }
- }
- url[x] = '\0';
-}
-
-static inline char hexchar(unsigned short s)
-{
- return (s<=9) ? ('0' + s) : ('A' + s - 10);
-}
-
-string CgiParse::url_encode(const char* s)
-{
- static char badchars[]="\"\\+<>#%{}|^~[]`;/?:@=&";
-
- string ret;
- for (; *s; s++) {
- if (strchr(badchars,*s) || *s<=0x20 || *s>=0x7F) {
- ret+='%';
- ret+=hexchar(*s >> 4);
- ret+=hexchar(*s & 0x0F);
- }
- else
- ret+=*s;
- }
- return ret;
-}
-
-// CDC implementation
-
-const char CommonDomainCookie::CDCName[] = "_saml_idp";
-
-CommonDomainCookie::CommonDomainCookie(const char* cookie)
-{
- if (!cookie)
- return;
-
- Category& log=Category::getInstance(ADFS_LOGCAT".CommonDomainCookie");
-
- // Copy it so we can URL-decode it.
- char* b64=strdup(cookie);
- CgiParse::url_decode(b64);
-
- // Chop it up and save off elements.
- vector<string> templist;
- char* ptr=b64;
- while (*ptr) {
- while (*ptr && isspace(*ptr)) ptr++;
- char* end=ptr;
- while (*end && !isspace(*end)) end++;
- templist.push_back(string(ptr,end-ptr));
- ptr=end;
- }
- free(b64);
-
- // Now Base64 decode the list.
- for (vector<string>::iterator i=templist.begin(); i!=templist.end(); i++) {
- unsigned int len;
- XMLByte* decoded=Base64::decode(reinterpret_cast<const XMLByte*>(i->c_str()),&len);
- if (decoded && *decoded) {
- m_list.push_back(reinterpret_cast<char*>(decoded));
- XMLString::release(&decoded);
- }
- else
- log.warn("cookie element does not appear to be base64-encoded");
- }
-}
-
-const char* CommonDomainCookie::set(const char* providerId)
-{
- // First scan the list for this IdP.
- for (vector<string>::iterator i=m_list.begin(); i!=m_list.end(); i++) {
- if (*i == providerId) {
- m_list.erase(i);
- break;
- }
- }
-
- // Append it to the end.
- m_list.push_back(providerId);
-
- // Now rebuild the delimited list.
- string delimited;
- for (vector<string>::const_iterator j=m_list.begin(); j!=m_list.end(); j++) {
- if (!delimited.empty()) delimited += ' ';
-
- unsigned int len;
- XMLByte* b64=Base64::encode(reinterpret_cast<const XMLByte*>(j->c_str()),j->length(),&len);
- XMLByte *pos, *pos2;
- for (pos=b64, pos2=b64; *pos2; pos2++)
- if (isgraph(*pos2))
- *pos++=*pos2;
- *pos=0;
-
- delimited += reinterpret_cast<char*>(b64);
- XMLString::release(&b64);
- }
-
- m_encoded=CgiParse::url_encode(delimited.c_str());
- return m_encoded.c_str();
-}
+/**\r
+ * Licensed to the University Corporation for Advanced Internet\r
+ * Development, Inc. (UCAID) under one or more contributor license\r
+ * agreements. See the NOTICE file distributed with this work for\r
+ * additional information regarding copyright ownership.\r
+ *\r
+ * UCAID licenses this file to you under the Apache License,\r
+ * Version 2.0 (the "License"); you may not use this file except\r
+ * in compliance with the License. You may obtain a copy of the\r
+ * License at\r
+ *\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing,\r
+ * software distributed under the License is distributed on an\r
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\r
+ * either express or implied. See the License for the specific\r
+ * language governing permissions and limitations under the License.\r
+ */\r
+\r
+/**\r
+ * adfs.cpp\r
+ *\r
+ * ADFSv1 extension library.\r
+ */\r
+\r
+#if defined (_MSC_VER) || defined(__BORLANDC__)\r
+# include "config_win32.h"\r
+#else\r
+# include "config.h"\r
+#endif\r
+\r
+#ifdef WIN32\r
+# define _CRT_NONSTDC_NO_DEPRECATE 1\r
+# define _CRT_SECURE_NO_DEPRECATE 1\r
+# define ADFS_EXPORTS __declspec(dllexport)\r
+#else\r
+# define ADFS_EXPORTS\r
+#endif\r
+\r
+#include <shibsp/base.h>\r
+#include <shibsp/exceptions.h>\r
+#include <shibsp/Application.h>\r
+#include <shibsp/ServiceProvider.h>\r
+#include <shibsp/SessionCache.h>\r
+#include <shibsp/SPConfig.h>\r
+#include <shibsp/SPRequest.h>\r
+#include <shibsp/TransactionLog.h>\r
+#include <shibsp/handler/AssertionConsumerService.h>\r
+#include <shibsp/handler/LogoutInitiator.h>\r
+#include <shibsp/handler/SessionInitiator.h>\r
+#include <xmltooling/logging.h>\r
+#include <xmltooling/util/DateTime.h>\r
+#include <xmltooling/util/NDC.h>\r
+#include <xmltooling/util/URLEncoder.h>\r
+#include <xmltooling/util/XMLHelper.h>\r
+#include <memory>\r
+\r
+#ifndef SHIBSP_LITE\r
+# include <shibsp/attribute/resolver/ResolutionContext.h>\r
+# include <shibsp/metadata/MetadataProviderCriteria.h>\r
+# include <saml/SAMLConfig.h>\r
+# include <saml/exceptions.h>\r
+# include <saml/binding/SecurityPolicy.h>\r
+# include <saml/saml1/core/Assertions.h>\r
+# include <saml/saml2/core/Assertions.h>\r
+# include <saml/saml2/metadata/Metadata.h>\r
+# include <saml/saml2/metadata/EndpointManager.h>\r
+# include <xmltooling/XMLToolingConfig.h>\r
+# include <xmltooling/impl/AnyElement.h>\r
+# include <xmltooling/util/ParserPool.h>\r
+# include <xmltooling/validation/ValidatorSuite.h>\r
+using namespace opensaml::saml2md;\r
+# ifndef min\r
+# define min(a,b) (((a) < (b)) ? (a) : (b))\r
+# endif\r
+#endif\r
+using namespace shibsp;\r
+using namespace opensaml;\r
+using namespace xmltooling::logging;\r
+using namespace xmltooling;\r
+using namespace xercesc;\r
+using namespace boost;\r
+using namespace std;\r
+\r
+#define WSFED_NS "http://schemas.xmlsoap.org/ws/2003/07/secext"\r
+#define WSTRUST_NS "http://schemas.xmlsoap.org/ws/2005/02/trust"\r
+\r
+namespace {\r
+\r
+#ifndef SHIBSP_LITE\r
+ class SHIBSP_DLLLOCAL ADFSDecoder : public MessageDecoder\r
+ {\r
+ auto_ptr_XMLCh m_ns;\r
+ public:\r
+ ADFSDecoder() : m_ns(WSTRUST_NS) {}\r
+ virtual ~ADFSDecoder() {}\r
+\r
+ const XMLCh* getProtocolFamily() const {\r
+ return m_ns.get();\r
+ }\r
+\r
+ XMLObject* decode(string& relayState, const GenericRequest& genericRequest, SecurityPolicy& policy) const;\r
+\r
+ protected:\r
+ void extractMessageDetails(\r
+ const XMLObject& message, const GenericRequest& req, const XMLCh* protocol, SecurityPolicy& policy\r
+ ) const {\r
+ }\r
+ };\r
+\r
+ MessageDecoder* ADFSDecoderFactory(const pair<const DOMElement*,const XMLCh*>& p)\r
+ {\r
+ return new ADFSDecoder();\r
+ }\r
+#endif\r
+\r
+#if defined (_MSC_VER)\r
+ #pragma warning( push )\r
+ #pragma warning( disable : 4250 )\r
+#endif\r
+\r
+ class SHIBSP_DLLLOCAL ADFSSessionInitiator : public SessionInitiator, public AbstractHandler, public RemotedHandler\r
+ {\r
+ public:\r
+ ADFSSessionInitiator(const DOMElement* e, const char* appId)\r
+ : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT ".SessionInitiator.ADFS"), nullptr, &m_remapper), m_appId(appId), m_binding(WSFED_NS) {\r
+ // If Location isn't set, defer address registration until the setParent call.\r
+ pair<bool,const char*> loc = getString("Location");\r
+ if (loc.first) {\r
+ string address = m_appId + loc.second + "::run::ADFSSI";\r
+ setAddress(address.c_str());\r
+ }\r
+ }\r
+ virtual ~ADFSSessionInitiator() {}\r
+\r
+ void setParent(const PropertySet* parent) {\r
+ DOMPropertySet::setParent(parent);\r
+ pair<bool,const char*> loc = getString("Location");\r
+ if (loc.first) {\r
+ string address = m_appId + loc.second + "::run::ADFSSI";\r
+ setAddress(address.c_str());\r
+ }\r
+ else {\r
+ m_log.warn("no Location property in ADFS SessionInitiator (or parent), can't register as remoted handler");\r
+ }\r
+ }\r
+\r
+ void receive(DDF& in, ostream& out);\r
+ pair<bool,long> unwrap(SPRequest& request, DDF& out) const;\r
+ pair<bool,long> run(SPRequest& request, string& entityID, bool isHandler=true) const;\r
+\r
+ const XMLCh* getProtocolFamily() const {\r
+ return m_binding.get();\r
+ }\r
+\r
+#ifndef SHIBSP_LITE\r
+ void generateMetadata(saml2md::SPSSODescriptor& role, const char* handlerURL) const {\r
+ doGenerateMetadata(role, handlerURL);\r
+ }\r
+#endif\r
+\r
+ private:\r
+ pair<bool,long> doRequest(\r
+ const Application& application,\r
+ const HTTPRequest* httpRequest,\r
+ HTTPResponse& httpResponse,\r
+ const char* entityID,\r
+ const char* acsLocation,\r
+ const char* authnContextClassRef,\r
+ string& relayState\r
+ ) const;\r
+ string m_appId;\r
+ auto_ptr_XMLCh m_binding;\r
+ };\r
+\r
+ class SHIBSP_DLLLOCAL ADFSConsumer : public shibsp::AssertionConsumerService\r
+ {\r
+ auto_ptr_XMLCh m_protocol;\r
+ public:\r
+ ADFSConsumer(const DOMElement* e, const char* appId)\r
+ : shibsp::AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT ".SSO.ADFS")), m_protocol(WSFED_NS) {}\r
+ virtual ~ADFSConsumer() {}\r
+\r
+#ifndef SHIBSP_LITE\r
+ void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {\r
+ AssertionConsumerService::generateMetadata(role, handlerURL);\r
+ role.addSupport(m_protocol.get());\r
+ }\r
+\r
+ private:\r
+ void implementProtocol(\r
+ const Application& application,\r
+ const HTTPRequest& httpRequest,\r
+ HTTPResponse& httpResponse,\r
+ SecurityPolicy& policy,\r
+ const PropertySet*,\r
+ const XMLObject& xmlObject\r
+ ) const;\r
+#else\r
+ const XMLCh* getProtocolFamily() const {\r
+ return m_protocol.get();\r
+ }\r
+#endif\r
+ };\r
+\r
+ class SHIBSP_DLLLOCAL ADFSLogoutInitiator : public AbstractHandler, public LogoutInitiator\r
+ {\r
+ public:\r
+ ADFSLogoutInitiator(const DOMElement* e, const char* appId)\r
+ : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT ".LogoutInitiator.ADFS")), m_appId(appId), m_binding(WSFED_NS) {\r
+ // If Location isn't set, defer address registration until the setParent call.\r
+ pair<bool,const char*> loc = getString("Location");\r
+ if (loc.first) {\r
+ string address = m_appId + loc.second + "::run::ADFSLI";\r
+ setAddress(address.c_str());\r
+ }\r
+ }\r
+ virtual ~ADFSLogoutInitiator() {}\r
+\r
+ void setParent(const PropertySet* parent) {\r
+ DOMPropertySet::setParent(parent);\r
+ pair<bool,const char*> loc = getString("Location");\r
+ if (loc.first) {\r
+ string address = m_appId + loc.second + "::run::ADFSLI";\r
+ setAddress(address.c_str());\r
+ }\r
+ else {\r
+ m_log.warn("no Location property in ADFS LogoutInitiator (or parent), can't register as remoted handler");\r
+ }\r
+ }\r
+\r
+ void receive(DDF& in, ostream& out);\r
+ pair<bool,long> run(SPRequest& request, bool isHandler=true) const;\r
+\r
+ const XMLCh* getProtocolFamily() const {\r
+ return m_binding.get();\r
+ }\r
+\r
+ private:\r
+ pair<bool,long> doRequest(const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse, Session* session) const;\r
+\r
+ string m_appId;\r
+ auto_ptr_XMLCh m_binding;\r
+ };\r
+\r
+ class SHIBSP_DLLLOCAL ADFSLogout : public AbstractHandler, public LogoutHandler\r
+ {\r
+ public:\r
+ ADFSLogout(const DOMElement* e, const char* appId)\r
+ : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT ".Logout.ADFS")), m_login(e, appId) {\r
+ m_initiator = false;\r
+#ifndef SHIBSP_LITE\r
+ m_preserve.push_back("wreply");\r
+ string address = string(appId) + getString("Location").second + "::run::ADFSLO";\r
+ setAddress(address.c_str());\r
+#endif\r
+ }\r
+ virtual ~ADFSLogout() {}\r
+\r
+ pair<bool,long> run(SPRequest& request, bool isHandler=true) const;\r
+\r
+#ifndef SHIBSP_LITE\r
+ void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {\r
+ m_login.generateMetadata(role, handlerURL);\r
+ const char* loc = getString("Location").second;\r
+ string hurl(handlerURL);\r
+ if (*loc != '/')\r
+ hurl += '/';\r
+ hurl += loc;\r
+ auto_ptr_XMLCh widen(hurl.c_str());\r
+ SingleLogoutService* ep = SingleLogoutServiceBuilder::buildSingleLogoutService();\r
+ ep->setLocation(widen.get());\r
+ ep->setBinding(m_login.getProtocolFamily());\r
+ role.getSingleLogoutServices().push_back(ep);\r
+ }\r
+\r
+ const char* getType() const {\r
+ return m_login.getType();\r
+ }\r
+#endif\r
+ const XMLCh* getProtocolFamily() const {\r
+ return m_login.getProtocolFamily();\r
+ }\r
+\r
+ private:\r
+ ADFSConsumer m_login;\r
+ };\r
+\r
+#if defined (_MSC_VER)\r
+ #pragma warning( pop )\r
+#endif\r
+\r
+ SessionInitiator* ADFSSessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)\r
+ {\r
+ return new ADFSSessionInitiator(p.first, p.second);\r
+ }\r
+\r
+ Handler* ADFSLogoutFactory(const pair<const DOMElement*,const char*>& p)\r
+ {\r
+ return new ADFSLogout(p.first, p.second);\r
+ }\r
+\r
+ Handler* ADFSLogoutInitiatorFactory(const pair<const DOMElement*,const char*>& p)\r
+ {\r
+ return new ADFSLogoutInitiator(p.first, p.second);\r
+ }\r
+\r
+ 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
+ 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
+};\r
+\r
+extern "C" int ADFS_EXPORTS xmltooling_extension_init(void*)\r
+{\r
+ SPConfig& conf=SPConfig::getConfig();\r
+ conf.SessionInitiatorManager.registerFactory("ADFS", ADFSSessionInitiatorFactory);\r
+ conf.LogoutInitiatorManager.registerFactory("ADFS", ADFSLogoutInitiatorFactory);\r
+ conf.AssertionConsumerServiceManager.registerFactory("ADFS", ADFSLogoutFactory);\r
+ conf.AssertionConsumerServiceManager.registerFactory(WSFED_NS, ADFSLogoutFactory);\r
+#ifndef SHIBSP_LITE\r
+ SAMLConfig::getConfig().MessageDecoderManager.registerFactory(WSFED_NS, ADFSDecoderFactory);\r
+ XMLObjectBuilder::registerBuilder(xmltooling::QName(WSTRUST_NS,"RequestedSecurityToken"), new AnyElementBuilder());\r
+ XMLObjectBuilder::registerBuilder(xmltooling::QName(WSTRUST_NS,"RequestSecurityTokenResponse"), new AnyElementBuilder());\r
+#endif\r
+ return 0;\r
+}\r
+\r
+extern "C" void ADFS_EXPORTS xmltooling_extension_term()\r
+{\r
+ /* should get unregistered during normal shutdown...\r
+ SPConfig& conf=SPConfig::getConfig();\r
+ conf.SessionInitiatorManager.deregisterFactory("ADFS");\r
+ conf.LogoutInitiatorManager.deregisterFactory("ADFS");\r
+ conf.AssertionConsumerServiceManager.deregisterFactory("ADFS");\r
+ conf.AssertionConsumerServiceManager.deregisterFactory(WSFED_NS);\r
+#ifndef SHIBSP_LITE\r
+ SAMLConfig::getConfig().MessageDecoderManager.deregisterFactory(WSFED_NS);\r
+#endif\r
+ */\r
+}\r
+\r
+pair<bool,long> ADFSSessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const\r
+{\r
+ // We have to know the IdP to function.\r
+ if (entityID.empty() || !checkCompatibility(request, isHandler))\r
+ return make_pair(false, 0L);\r
+\r
+ string target;\r
+ pair<bool,const char*> prop;\r
+ pair<bool,const char*> acClass;\r
+ const Handler* ACS = nullptr;\r
+ const Application& app = request.getApplication();\r
+\r
+ if (isHandler) {\r
+ prop.second = request.getParameter("acsIndex");\r
+ if (prop.second && *prop.second) {\r
+ ACS = app.getAssertionConsumerServiceByIndex(atoi(prop.second));\r
+ if (!ACS)\r
+ request.log(SPRequest::SPWarn, "invalid acsIndex specified in request, using acsIndex property");\r
+ }\r
+\r
+ prop = getString("target", request);\r
+ if (prop.first)\r
+ target = prop.second;\r
+\r
+ // Since we're passing the ACS by value, we need to compute the return URL,\r
+ // so we'll need the target resource for real.\r
+ recoverRelayState(app, request, request, target, false);\r
+ app.limitRedirect(request, target.c_str());\r
+\r
+ acClass = getString("authnContextClassRef", request);\r
+ }\r
+ else {\r
+ // Check for a hardwired target value in the map or handler.\r
+ prop = getString("target", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);\r
+ if (prop.first)\r
+ target = prop.second;\r
+ else\r
+ target = request.getRequestURL();\r
+\r
+ acClass = getString("authnContextClassRef", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);\r
+ }\r
+\r
+ if (!ACS) {\r
+ pair<bool,unsigned int> index = getUnsignedInt("acsIndex", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);\r
+ if (index.first)\r
+ ACS = app.getAssertionConsumerServiceByIndex(index.second);\r
+ }\r
+\r
+ // Validate the ACS for use with this protocol.\r
+ if (!ACS || !XMLString::equals(getProtocolFamily(), ACS->getProtocolFamily())) {\r
+ if (ACS)\r
+ request.log(SPRequest::SPWarn, "invalid acsIndex property, or non-ADFS ACS, using default ADFS ACS");\r
+ ACS = app.getAssertionConsumerServiceByProtocol(getProtocolFamily());\r
+ if (!ACS)\r
+ throw ConfigurationException("Unable to locate an ADFS-compatible ACS in the configuration.");\r
+ }\r
+\r
+ // Since we're not passing by index, we need to fully compute the return URL.\r
+ // Compute the ACS URL. We add the ACS location to the base handlerURL.\r
+ string ACSloc = request.getHandlerURL(target.c_str());\r
+ prop = ACS->getString("Location");\r
+ if (prop.first)\r
+ ACSloc += prop.second;\r
+\r
+ if (isHandler) {\r
+ // We may already have RelayState set if we looped back here,\r
+ // but we've turned it back into a resource by this point, so if there's\r
+ // a target on the URL, reset to that value.\r
+ prop.second = request.getParameter("target");\r
+ if (prop.second && *prop.second)\r
+ target = prop.second;\r
+ }\r
+\r
+ m_log.debug("attempting to initiate session using ADFS with provider (%s)", entityID.c_str());\r
+\r
+ if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {\r
+ // Out of process means the POST data via the request can be exposed directly to the private method.\r
+ // The method will handle POST preservation if necessary *before* issuing the response, but only if\r
+ // it dispatches to an IdP.\r
+ return doRequest(app, &request, request, entityID.c_str(), ACSloc.c_str(), (acClass.first ? acClass.second : nullptr), target);\r
+ }\r
+\r
+ // Remote the call.\r
+ DDF out,in = DDF(m_address.c_str()).structure();\r
+ DDFJanitor jin(in), jout(out);\r
+ in.addmember("application_id").string(app.getId());\r
+ in.addmember("entity_id").string(entityID.c_str());\r
+ in.addmember("acsLocation").string(ACSloc.c_str());\r
+ if (!target.empty())\r
+ in.addmember("RelayState").unsafe_string(target.c_str());\r
+ if (acClass.first)\r
+ in.addmember("authnContextClassRef").string(acClass.second);\r
+\r
+ // Remote the processing.\r
+ out = request.getServiceProvider().getListenerService()->send(in);\r
+ return unwrap(request, out);\r
+}\r
+\r
+pair<bool,long> ADFSSessionInitiator::unwrap(SPRequest& request, DDF& out) const\r
+{\r
+ // See if there's any response to send back.\r
+ if (!out["redirect"].isnull() || !out["response"].isnull()) {\r
+ // If so, we're responsible for handling the POST data, probably by dropping a cookie.\r
+ preservePostData(request.getApplication(), request, request, out["RelayState"].string());\r
+ }\r
+ return RemotedHandler::unwrap(request, out);\r
+}\r
+\r
+void ADFSSessionInitiator::receive(DDF& in, ostream& out)\r
+{\r
+ // Find application.\r
+ const char* aid = in["application_id"].string();\r
+ const Application* app = aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;\r
+ if (!app) {\r
+ // Something's horribly wrong.\r
+ m_log.error("couldn't find application (%s) to generate ADFS request", aid ? aid : "(missing)");\r
+ throw ConfigurationException("Unable to locate application for new session, deleted?");\r
+ }\r
+\r
+ const char* entityID = in["entity_id"].string();\r
+ const char* acsLocation = in["acsLocation"].string();\r
+ if (!entityID || !acsLocation)\r
+ throw ConfigurationException("No entityID or acsLocation parameter supplied to remoted SessionInitiator.");\r
+\r
+ DDF ret(nullptr);\r
+ DDFJanitor jout(ret);\r
+\r
+ // Wrap the outgoing object with a Response facade.\r
+ scoped_ptr<HTTPResponse> http(getResponse(ret));\r
+\r
+ string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");\r
+\r
+ // Since we're remoted, the result should either be a throw, which we pass on,\r
+ // a false/0 return, which we just return as an empty structure, or a response/redirect,\r
+ // which we capture in the facade and send back.\r
+ doRequest(*app, nullptr, *http, entityID, acsLocation, in["authnContextClassRef"].string(), relayState);\r
+ if (!ret.isstruct())\r
+ ret.structure();\r
+ ret.addmember("RelayState").unsafe_string(relayState.c_str());\r
+ out << ret;\r
+}\r
+\r
+pair<bool,long> ADFSSessionInitiator::doRequest(\r
+ const Application& app,\r
+ const HTTPRequest* httpRequest,\r
+ HTTPResponse& httpResponse,\r
+ const char* entityID,\r
+ const char* acsLocation,\r
+ const char* authnContextClassRef,\r
+ string& relayState\r
+ ) const\r
+{\r
+#ifndef SHIBSP_LITE\r
+ // Use metadata to invoke the SSO service directly.\r
+ MetadataProvider* m = app.getMetadataProvider();\r
+ Locker locker(m);\r
+ MetadataProviderCriteria mc(app, entityID, &IDPSSODescriptor::ELEMENT_QNAME, m_binding.get());\r
+ pair<const EntityDescriptor*,const RoleDescriptor*> entity = m->getEntityDescriptor(mc);\r
+ if (!entity.first) {\r
+ m_log.warn("unable to locate metadata for provider (%s)", entityID);\r
+ throw MetadataException("Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", entityID));\r
+ }\r
+ else if (!entity.second) {\r
+ m_log.log(getParent() ? Priority::INFO : Priority::WARN, "unable to locate ADFS-aware identity provider role for provider (%s)", entityID);\r
+ if (getParent())\r
+ return make_pair(false, 0L);\r
+ throw MetadataException("Unable to locate ADFS-aware identity provider role for provider ($entityID)", namedparams(1, "entityID", entityID));\r
+ }\r
+ const EndpointType* ep = EndpointManager<SingleSignOnService>(\r
+ dynamic_cast<const IDPSSODescriptor*>(entity.second)->getSingleSignOnServices()\r
+ ).getByBinding(m_binding.get());\r
+ if (!ep) {\r
+ m_log.warn("unable to locate compatible SSO service for provider (%s)", entityID);\r
+ if (getParent())\r
+ return make_pair(false, 0L);\r
+ throw MetadataException("Unable to locate compatible SSO service for provider ($entityID)", namedparams(1, "entityID", entityID));\r
+ }\r
+\r
+ preserveRelayState(app, httpResponse, relayState);\r
+\r
+ scoped_ptr<AuthnRequestEvent> ar_event(newAuthnRequestEvent(app, httpRequest));\r
+ if (ar_event.get()) {\r
+ ar_event->m_binding = WSFED_NS;\r
+ ar_event->m_protocol = WSFED_NS;\r
+ ar_event->m_peer = entity.first;\r
+ app.getServiceProvider().getTransactionLog()->write(*ar_event);\r
+ }\r
+\r
+ // UTC timestamp\r
+ time_t epoch=time(nullptr);\r
+#ifndef HAVE_GMTIME_R\r
+ struct tm* ptime=gmtime(&epoch);\r
+#else\r
+ struct tm res;\r
+ struct tm* ptime=gmtime_r(&epoch,&res);\r
+#endif\r
+ char timebuf[32];\r
+ strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);\r
+\r
+ auto_ptr_char dest(ep->getLocation());\r
+ const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();\r
+\r
+ string req=string(dest.get()) + (strchr(dest.get(),'?') ? '&' : '?') + "wa=wsignin1.0&wreply=" + urlenc->encode(acsLocation) +\r
+ "&wct=" + urlenc->encode(timebuf) + "&wtrealm=" + urlenc->encode(app.getString("entityID").second);\r
+ if (authnContextClassRef)\r
+ req += "&wauth=" + urlenc->encode(authnContextClassRef);\r
+ if (!relayState.empty())\r
+ req += "&wctx=" + urlenc->encode(relayState.c_str());\r
+\r
+ if (httpRequest) {\r
+ // If the request object is available, we're responsible for the POST data.\r
+ preservePostData(app, *httpRequest, httpResponse, relayState.c_str());\r
+ }\r
+\r
+ return make_pair(true, httpResponse.sendRedirect(req.c_str()));\r
+#else\r
+ return make_pair(false, 0L);\r
+#endif\r
+}\r
+\r
+#ifndef SHIBSP_LITE\r
+\r
+XMLObject* ADFSDecoder::decode(string& relayState, const GenericRequest& genericRequest, SecurityPolicy& policy) const\r
+{\r
+#ifdef _DEBUG\r
+ xmltooling::NDC ndc("decode");\r
+#endif\r
+ Category& log = Category::getInstance(SHIBSP_LOGCAT ".MessageDecoder.ADFS");\r
+\r
+ log.debug("validating input");\r
+ const HTTPRequest* httpRequest=dynamic_cast<const HTTPRequest*>(&genericRequest);\r
+ if (!httpRequest)\r
+ throw BindingException("Unable to cast request object to HTTPRequest type.");\r
+ if (strcmp(httpRequest->getMethod(),"POST"))\r
+ throw BindingException("Invalid HTTP method ($1).", params(1, httpRequest->getMethod()));\r
+ const char* param = httpRequest->getParameter("wa");\r
+ if (!param || strcmp(param, "wsignin1.0"))\r
+ throw BindingException("Missing or invalid wa parameter (should be wsignin1.0).");\r
+ param = httpRequest->getParameter("wctx");\r
+ if (param)\r
+ relayState = param;\r
+\r
+ param = httpRequest->getParameter("wresult");\r
+ if (!param)\r
+ throw BindingException("Request missing wresult parameter.");\r
+\r
+ log.debug("decoded ADFS response:\n%s", param);\r
+\r
+ // Parse and bind the document into an XMLObject.\r
+ istringstream is(param);\r
+ DOMDocument* doc = (policy.getValidating() ? XMLToolingConfig::getConfig().getValidatingParser()\r
+ : XMLToolingConfig::getConfig().getParser()).parse(is);\r
+ XercesJanitor<DOMDocument> janitor(doc);\r
+ auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));\r
+ janitor.release();\r
+\r
+ if (!XMLString::equals(xmlObject->getElementQName().getLocalPart(), RequestSecurityTokenResponse)) {\r
+ log.error("unrecognized root element on message: %s", xmlObject->getElementQName().toString().c_str());\r
+ throw BindingException("Decoded message was not of the appropriate type.");\r
+ }\r
+\r
+ SchemaValidators.validate(xmlObject.get());\r
+\r
+ // Skip policy step here, there's no security in the wrapper.\r
+ // policy.evaluate(*xmlObject.get(), &genericRequest);\r
+\r
+ return xmlObject.release();\r
+}\r
+\r
+void ADFSConsumer::implementProtocol(\r
+ const Application& application,\r
+ const HTTPRequest& httpRequest,\r
+ HTTPResponse& httpResponse,\r
+ SecurityPolicy& policy,\r
+ const PropertySet*,\r
+ const XMLObject& xmlObject\r
+ ) const\r
+{\r
+ // Implementation of ADFS profile.\r
+ m_log.debug("processing message against ADFS Passive Requester profile");\r
+\r
+ // With ADFS, all the security comes from the assertion, which is two levels down in the message.\r
+\r
+ const ElementProxy* response = dynamic_cast<const ElementProxy*>(&xmlObject);\r
+ if (!response || !response->hasChildren())\r
+ throw FatalProfileException("Incoming message was not of the proper type or contains no security token.");\r
+\r
+ const Assertion* token = nullptr;\r
+ for (vector<XMLObject*>::const_iterator xo = response->getUnknownXMLObjects().begin(); xo != response->getUnknownXMLObjects().end(); ++xo) {\r
+ // Look for the RequestedSecurityToken element.\r
+ if (XMLString::equals((*xo)->getElementQName().getLocalPart(), RequestedSecurityToken)) {\r
+ response = dynamic_cast<const ElementProxy*>(*xo);\r
+ if (!response || !response->hasChildren())\r
+ throw FatalProfileException("Token wrapper element did not contain a security token.");\r
+ token = dynamic_cast<const Assertion*>(response->getUnknownXMLObjects().front());\r
+ if (!token || !token->getSignature())\r
+ throw FatalProfileException("Incoming message did not contain a signed SAML assertion.");\r
+ break;\r
+ }\r
+ }\r
+\r
+ // Extract message and issuer details from assertion.\r
+ extractMessageDetails(*token, m_protocol.get(), policy);\r
+\r
+ // Populate recipient as audience.\r
+ const EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : nullptr;\r
+ policy.getAudiences().push_back(application.getRelyingParty(entity)->getXMLString("entityID").second);\r
+\r
+ // Run the policy over the assertion. Handles replay, freshness, and\r
+ // signature verification, assuming the relevant rules are configured,\r
+ // along with condition enforcement.\r
+ policy.evaluate(*token, &httpRequest);\r
+\r
+ // If no security is in place now, we kick it.\r
+ if (!policy.isAuthenticated())\r
+ throw SecurityPolicyException("Unable to establish security of incoming assertion.");\r
+\r
+ const saml1::NameIdentifier* saml1name=nullptr;\r
+ const saml1::AuthenticationStatement* saml1statement=nullptr;\r
+ const saml2::NameID* saml2name=nullptr;\r
+ const saml2::AuthnStatement* saml2statement=nullptr;\r
+ const XMLCh* authMethod=nullptr;\r
+ const XMLCh* authInstant=nullptr;\r
+ time_t now = time(nullptr), sessionExp = 0;\r
+ const PropertySet* sessionProps = application.getPropertySet("Sessions");\r
+\r
+ const saml1::Assertion* saml1token = dynamic_cast<const saml1::Assertion*>(token);\r
+ if (saml1token) {\r
+ // Now do profile validation to ensure we can use it for SSO.\r
+ if (!saml1token->getConditions() || !saml1token->getConditions()->getNotBefore() || !saml1token->getConditions()->getNotOnOrAfter())\r
+ throw FatalProfileException("Assertion did not contain time conditions.");\r
+ else if (saml1token->getAuthenticationStatements().empty())\r
+ throw FatalProfileException("Assertion did not contain an authentication statement.");\r
+\r
+ // authnskew allows rejection of SSO if AuthnInstant is too old.\r
+ pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);\r
+\r
+ saml1statement = saml1token->getAuthenticationStatements().front();\r
+ if (saml1statement->getAuthenticationInstant()) {\r
+ if (saml1statement->getAuthenticationInstantEpoch() - XMLToolingConfig::getConfig().clock_skew_secs > now) {\r
+ throw FatalProfileException("The login time at your identity provider was future-dated.");\r
+ }\r
+ else if (authnskew.first && authnskew.second && saml1statement->getAuthenticationInstantEpoch() <= now &&\r
+ (now - saml1statement->getAuthenticationInstantEpoch() > authnskew.second)) {\r
+ throw FatalProfileException("The gap between now and the time you logged into your identity provider exceeds the allowed limit.");\r
+ }\r
+ }\r
+ else if (authnskew.first && authnskew.second) {\r
+ throw FatalProfileException("Your identity provider did not supply a time of login, violating local policy.");\r
+ }\r
+\r
+ // Address checking.\r
+ saml1::SubjectLocality* locality = saml1statement->getSubjectLocality();\r
+ if (locality && locality->getIPAddress()) {\r
+ auto_ptr_char ip(locality->getIPAddress());\r
+ checkAddress(application, httpRequest, ip.get());\r
+ }\r
+\r
+ saml1name = saml1statement->getSubject()->getNameIdentifier();\r
+ authMethod = saml1statement->getAuthenticationMethod();\r
+ if (saml1statement->getAuthenticationInstant())\r
+ authInstant = saml1statement->getAuthenticationInstant()->getRawData();\r
+\r
+ // Session expiration.\r
+ pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);\r
+ if (!lifetime.first || lifetime.second == 0)\r
+ lifetime.second = 28800;\r
+ sessionExp = now + lifetime.second;\r
+ }\r
+ else {\r
+ const saml2::Assertion* saml2token = dynamic_cast<const saml2::Assertion*>(token);\r
+ if (!saml2token)\r
+ throw FatalProfileException("Incoming message did not contain a recognized type of SAML assertion.");\r
+\r
+ // Now do profile validation to ensure we can use it for SSO.\r
+ if (!saml2token->getConditions() || !saml2token->getConditions()->getNotBefore() || !saml2token->getConditions()->getNotOnOrAfter())\r
+ throw FatalProfileException("Assertion did not contain time conditions.");\r
+ else if (saml2token->getAuthnStatements().empty())\r
+ throw FatalProfileException("Assertion did not contain an authentication statement.");\r
+\r
+ // authnskew allows rejection of SSO if AuthnInstant is too old.\r
+ pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);\r
+\r
+ saml2statement = saml2token->getAuthnStatements().front();\r
+ if (authnskew.first && authnskew.second &&\r
+ saml2statement->getAuthnInstant() && (now - saml2statement->getAuthnInstantEpoch() > authnskew.second))\r
+ throw FatalProfileException("The gap between now and the time you logged into your identity provider exceeds the limit.");\r
+\r
+ // Address checking.\r
+ saml2::SubjectLocality* locality = saml2statement->getSubjectLocality();\r
+ if (locality && locality->getAddress()) {\r
+ auto_ptr_char ip(locality->getAddress());\r
+ checkAddress(application, httpRequest, ip.get());\r
+ }\r
+\r
+ saml2name = saml2token->getSubject() ? saml2token->getSubject()->getNameID() : nullptr;\r
+ if (saml2statement->getAuthnContext() && saml2statement->getAuthnContext()->getAuthnContextClassRef())\r
+ authMethod = saml2statement->getAuthnContext()->getAuthnContextClassRef()->getReference();\r
+ if (saml2statement->getAuthnInstant())\r
+ authInstant = saml2statement->getAuthnInstant()->getRawData();\r
+\r
+ // Session expiration for SAML 2.0 is jointly IdP- and SP-driven.\r
+ sessionExp = saml2statement->getSessionNotOnOrAfter() ? saml2statement->getSessionNotOnOrAfterEpoch() : 0;\r
+ pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);\r
+ if (!lifetime.first || lifetime.second == 0)\r
+ lifetime.second = 28800;\r
+ if (sessionExp == 0)\r
+ sessionExp = now + lifetime.second; // IdP says nothing, calulate based on SP.\r
+ else\r
+ sessionExp = min(sessionExp, now + lifetime.second); // Use the lowest.\r
+ }\r
+\r
+ m_log.debug("ADFS profile processing completed successfully");\r
+\r
+ // We've successfully "accepted" the SSO token.\r
+ // To complete processing, we need to extract and resolve attributes and then create the session.\r
+\r
+ // Normalize a SAML 1.x NameIdentifier...\r
+ scoped_ptr<saml2::NameID> nameid(saml1name ? saml2::NameIDBuilder::buildNameID() : nullptr);\r
+ if (saml1name) {\r
+ nameid->setName(saml1name->getName());\r
+ nameid->setFormat(saml1name->getFormat());\r
+ nameid->setNameQualifier(saml1name->getNameQualifier());\r
+ }\r
+\r
+ // The context will handle deleting attributes and new tokens.\r
+ vector<const Assertion*> tokens(1,token);\r
+ scoped_ptr<ResolutionContext> ctx(\r
+ resolveAttributes(\r
+ application,\r
+ &httpRequest,\r
+ policy.getIssuerMetadata(),\r
+ m_protocol.get(),\r
+ nullptr,\r
+ saml1name,\r
+ saml1statement,\r
+ (saml1name ? nameid.get() : saml2name),\r
+ saml2statement,\r
+ authMethod,\r
+ nullptr,\r
+ &tokens\r
+ )\r
+ );\r
+\r
+ if (ctx.get()) {\r
+ // Copy over any new tokens, but leave them in the context for cleanup.\r
+ tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());\r
+ }\r
+\r
+ string session_id;\r
+ application.getServiceProvider().getSessionCache()->insert(\r
+ session_id,\r
+ application,\r
+ httpRequest,\r
+ httpResponse,\r
+ sessionExp,\r
+ entity,\r
+ m_protocol.get(),\r
+ (saml1name ? nameid.get() : saml2name),\r
+ authInstant,\r
+ nullptr,\r
+ authMethod,\r
+ nullptr,\r
+ &tokens,\r
+ ctx ? &ctx->getResolvedAttributes() : nullptr\r
+ );\r
+\r
+ scoped_ptr<LoginEvent> login_event(newLoginEvent(application, httpRequest));\r
+ if (login_event) {\r
+ login_event->m_sessionID = session_id.c_str();\r
+ login_event->m_peer = entity;\r
+ login_event->m_protocol = WSFED_NS;\r
+ login_event->m_binding = WSFED_NS;\r
+ login_event->m_saml1AuthnStatement = saml1statement;\r
+ login_event->m_nameID = (saml1name ? nameid.get() : saml2name);\r
+ login_event->m_saml2AuthnStatement = saml2statement;\r
+ if (ctx)\r
+ login_event->m_attributes = &ctx->getResolvedAttributes();\r
+ application.getServiceProvider().getTransactionLog()->write(*login_event);\r
+ }\r
+}\r
+\r
+#endif\r
+\r
+pair<bool,long> ADFSLogoutInitiator::run(SPRequest& request, bool isHandler) const\r
+{\r
+ // Normally we'd do notifications and session clearage here, but ADFS logout\r
+ // is missing the needed request/response features, so we have to rely on\r
+ // the IdP half to notify us back about the logout and do the work there.\r
+ // Basically we have no way to tell in the Logout receiving handler whether\r
+ // we initiated the logout or not.\r
+\r
+ Session* session = nullptr;\r
+ try {\r
+ session = request.getSession(false, true, false); // don't cache it and ignore all checks\r
+ if (!session)\r
+ return make_pair(false, 0L);\r
+\r
+ // We only handle ADFS sessions.\r
+ if (!XMLString::equals(session->getProtocol(), WSFED_NS) || !session->getEntityID()) {\r
+ session->unlock();\r
+ return make_pair(false, 0L);\r
+ }\r
+ }\r
+ catch (std::exception& ex) {\r
+ m_log.error("error accessing current session: %s", ex.what());\r
+ return make_pair(false,0L);\r
+ }\r
+\r
+ if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {\r
+ // When out of process, we run natively.\r
+ return doRequest(request.getApplication(), request, request, session);\r
+ }\r
+ else {\r
+ // When not out of process, we remote the request.\r
+ session->unlock();\r
+ vector<string> headers(1,"Cookie");\r
+ headers.push_back("User-Agent");\r
+ DDF out,in = wrap(request, &headers);\r
+ DDFJanitor jin(in), jout(out);\r
+ out=request.getServiceProvider().getListenerService()->send(in);\r
+ return unwrap(request, out);\r
+ }\r
+}\r
+\r
+void ADFSLogoutInitiator::receive(DDF& in, ostream& out)\r
+{\r
+#ifndef SHIBSP_LITE\r
+ // Defer to base class for notifications\r
+ if (in["notify"].integer() == 1)\r
+ return LogoutHandler::receive(in, out);\r
+\r
+ // Find application.\r
+ const char* aid = in["application_id"].string();\r
+ const Application* app = aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;\r
+ if (!app) {\r
+ // Something's horribly wrong.\r
+ m_log.error("couldn't find application (%s) for logout", aid ? aid : "(missing)");\r
+ throw ConfigurationException("Unable to locate application for logout, deleted?");\r
+ }\r
+\r
+ // Unpack the request.\r
+ scoped_ptr<HTTPRequest> req(getRequest(in));\r
+\r
+ // Set up a response shim.\r
+ DDF ret(nullptr);\r
+ DDFJanitor jout(ret);\r
+ scoped_ptr<HTTPResponse> resp(getResponse(ret));\r
+\r
+ Session* session = nullptr;\r
+ try {\r
+ session = app->getServiceProvider().getSessionCache()->find(*app, *req, nullptr, nullptr);\r
+ }\r
+ catch (std::exception& ex) {\r
+ m_log.error("error accessing current session: %s", ex.what());\r
+ }\r
+\r
+ // With no session, we just skip the request and let it fall through to an empty struct return.\r
+ if (session) {\r
+ if (session->getEntityID()) {\r
+ // Since we're remoted, the result should either be a throw, which we pass on,\r
+ // a false/0 return, which we just return as an empty structure, or a response/redirect,\r
+ // which we capture in the facade and send back.\r
+ doRequest(*app, *req, *resp, session);\r
+ }\r
+ else {\r
+ m_log.error("no issuing entityID found in session");\r
+ session->unlock();\r
+ app->getServiceProvider().getSessionCache()->remove(*app, *req, resp.get());\r
+ }\r
+ }\r
+ out << ret;\r
+#else\r
+ throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");\r
+#endif\r
+}\r
+\r
+pair<bool,long> ADFSLogoutInitiator::doRequest(\r
+ const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse, Session* session\r
+ ) const\r
+{\r
+ Locker sessionLocker(session, false);\r
+\r
+ // Do back channel notification.\r
+ vector<string> sessions(1, session->getID());\r
+ if (!notifyBackChannel(application, httpRequest.getRequestURL(), sessions, false)) {\r
+#ifndef SHIBSP_LITE\r
+ scoped_ptr<LogoutEvent> logout_event(newLogoutEvent(application, &httpRequest, session));\r
+ if (logout_event) {\r
+ logout_event->m_logoutType = LogoutEvent::LOGOUT_EVENT_PARTIAL;\r
+ application.getServiceProvider().getTransactionLog()->write(*logout_event);\r
+ }\r
+#endif\r
+ sessionLocker.assign();\r
+ session = nullptr;\r
+ application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);\r
+ return sendLogoutPage(application, httpRequest, httpResponse, "partial");\r
+ }\r
+\r
+#ifndef SHIBSP_LITE\r
+ pair<bool,long> ret = make_pair(false, 0L);\r
+\r
+ try {\r
+ // With a session in hand, we can create a request message, if we can find a compatible endpoint.\r
+ MetadataProvider* m = application.getMetadataProvider();\r
+ Locker metadataLocker(m);\r
+ MetadataProviderCriteria mc(application, session->getEntityID(), &IDPSSODescriptor::ELEMENT_QNAME, m_binding.get());\r
+ pair<const EntityDescriptor*,const RoleDescriptor*> entity=m->getEntityDescriptor(mc);\r
+ if (!entity.first) {\r
+ throw MetadataException(\r
+ "Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", session->getEntityID())\r
+ );\r
+ }\r
+ else if (!entity.second) {\r
+ throw MetadataException(\r
+ "Unable to locate ADFS IdP role for identity provider ($entityID).", namedparams(1, "entityID", session->getEntityID())\r
+ );\r
+ }\r
+\r
+ const EndpointType* ep = EndpointManager<SingleLogoutService>(\r
+ dynamic_cast<const IDPSSODescriptor*>(entity.second)->getSingleLogoutServices()\r
+ ).getByBinding(m_binding.get());\r
+ if (!ep) {\r
+ throw MetadataException(\r
+ "Unable to locate ADFS single logout service for identity provider ($entityID).",\r
+ namedparams(1, "entityID", session->getEntityID())\r
+ );\r
+ }\r
+\r
+ const char* returnloc = httpRequest.getParameter("return");\r
+ if (returnloc)\r
+ application.limitRedirect(httpRequest, returnloc);\r
+\r
+ // Log the request.\r
+ scoped_ptr<LogoutEvent> logout_event(newLogoutEvent(application, &httpRequest, session));\r
+ if (logout_event) {\r
+ logout_event->m_logoutType = LogoutEvent::LOGOUT_EVENT_UNKNOWN;\r
+ application.getServiceProvider().getTransactionLog()->write(*logout_event);\r
+ }\r
+\r
+ auto_ptr_char dest(ep->getLocation());\r
+ string req=string(dest.get()) + (strchr(dest.get(),'?') ? '&' : '?') + "wa=wsignout1.0";\r
+ if (returnloc) {\r
+ req += "&wreply=";\r
+ if (*returnloc == '/') {\r
+ string s(returnloc);\r
+ httpRequest.absolutize(s);\r
+ req += XMLToolingConfig::getConfig().getURLEncoder()->encode(s.c_str());\r
+ }\r
+ else {\r
+ req += XMLToolingConfig::getConfig().getURLEncoder()->encode(returnloc);\r
+ }\r
+ }\r
+ ret.second = httpResponse.sendRedirect(req.c_str());\r
+ ret.first = true;\r
+\r
+ if (session) {\r
+ sessionLocker.assign();\r
+ session = nullptr;\r
+ application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);\r
+ }\r
+ }\r
+ catch (MetadataException& mex) {\r
+ // Less noise for IdPs that don't support logout\r
+ m_log.info("unable to issue ADFS logout request: %s", mex.what());\r
+ }\r
+ catch (std::exception& ex) {\r
+ m_log.error("error issuing ADFS logout request: %s", ex.what());\r
+ }\r
+\r
+ return ret;\r
+#else\r
+ throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");\r
+#endif\r
+}\r
+\r
+pair<bool,long> ADFSLogout::run(SPRequest& request, bool isHandler) const\r
+{\r
+ // Defer to base class for front-channel loop first.\r
+ // This won't initiate the loop, only continue/end it.\r
+ pair<bool,long> ret = LogoutHandler::run(request, isHandler);\r
+ if (ret.first)\r
+ return ret;\r
+\r
+ // wa parameter indicates the "action" to perform\r
+ bool returning = false;\r
+ const char* param = request.getParameter("wa");\r
+ if (param) {\r
+ if (!strcmp(param, "wsignin1.0"))\r
+ return m_login.run(request, isHandler);\r
+ else if (strcmp(param, "wsignout1.0") && strcmp(param, "wsignoutcleanup1.0"))\r
+ throw FatalProfileException("Unsupported WS-Federation action parameter ($1).", params(1, param));\r
+ }\r
+ else if (strcmp(request.getMethod(),"GET") || !request.getParameter("notifying"))\r
+ throw FatalProfileException("Unsupported request to ADFS protocol endpoint.");\r
+ else\r
+ returning = true;\r
+\r
+ param = request.getParameter("wreply");\r
+ const Application& app = request.getApplication();\r
+\r
+ if (!returning) {\r
+ // Pass control to the first front channel notification point, if any.\r
+ map<string,string> parammap;\r
+ if (param)\r
+ parammap["wreply"] = param;\r
+ pair<bool,long> result = notifyFrontChannel(app, request, request, ¶mmap);\r
+ if (result.first)\r
+ return result;\r
+ }\r
+\r
+ // Best effort on back channel and to remove the user agent's session.\r
+ string session_id = app.getServiceProvider().getSessionCache()->active(app, request);\r
+ if (!session_id.empty()) {\r
+ vector<string> sessions(1,session_id);\r
+ notifyBackChannel(app, request.getRequestURL(), sessions, false);\r
+ try {\r
+ app.getServiceProvider().getSessionCache()->remove(app, request, &request);\r
+ }\r
+ catch (std::exception& ex) {\r
+ m_log.error("error removing session (%s): %s", session_id.c_str(), ex.what());\r
+ }\r
+ }\r
+\r
+ if (param) {\r
+ if (*param == '/') {\r
+ string p(param);\r
+ request.absolutize(p);\r
+ return make_pair(true, request.sendRedirect(p.c_str()));\r
+ }\r
+ else {\r
+ app.limitRedirect(request, param);\r
+ return make_pair(true, request.sendRedirect(param));\r
+ }\r
+ }\r
+ return sendLogoutPage(app, request, request, "global");\r
+}\r