Rename authnskew.
[shibboleth/cpp-sp.git] / adfs / adfs.cpp
index 2f35433..7fee451 100644 (file)
  * limitations under the License.
  */
 
-/* adfs.cpp - bootstraps the ADFS extension library
+/**
+ * adfs.cpp
+ *
+ * ADFSv1 extension library
+ */
 
-   Scott Cantor
-   10/10/05
-*/
+#if defined (_MSC_VER) || defined(__BORLANDC__)
+# include "config_win32.h"
+#else
+# include "config.h"
+#endif
 
 #ifdef WIN32
+# define _CRT_NONSTDC_NO_DEPRECATE 1
+# define _CRT_SECURE_NO_DEPRECATE 1
 # define ADFS_EXPORTS __declspec(dllexport)
 #else
 # define ADFS_EXPORTS
 #endif
 
-#include "internal.h"
+#include <shibsp/base.h>
+#include <shibsp/exceptions.h>
+#include <shibsp/Application.h>
+#include <shibsp/ServiceProvider.h>
+#include <shibsp/SessionCache.h>
+#include <shibsp/SPConfig.h>
+#include <shibsp/handler/AssertionConsumerService.h>
+#include <shibsp/handler/LogoutHandler.h>
+#include <shibsp/handler/SessionInitiator.h>
+#include <xmltooling/logging.h>
+#include <xmltooling/util/NDC.h>
+#include <xmltooling/util/URLEncoder.h>
+#include <xmltooling/util/XMLHelper.h>
+#include <xercesc/util/XMLUniDefs.hpp>
+
+#ifndef SHIBSP_LITE
+# include <shibsp/attribute/resolver/ResolutionContext.h>
+# include <saml/SAMLConfig.h>
+# include <saml/saml1/core/Assertions.h>
+# include <saml/saml1/profile/AssertionValidator.h>
+# include <saml/saml2/core/Assertions.h>
+# include <saml/saml2/metadata/Metadata.h>
+# include <saml/saml2/metadata/EndpointManager.h>
+# include <xmltooling/impl/AnyElement.h>
+# include <xmltooling/validation/ValidatorSuite.h>
+using namespace opensaml::saml2md;
+#endif
+using namespace shibsp;
+using namespace opensaml;
+using namespace xmltooling::logging;
+using namespace xmltooling;
+using namespace xercesc;
+using namespace std;
 
-#include <xercesc/util/Base64.hpp>
+#define WSFED_NS "http://schemas.xmlsoap.org/ws/2003/07/secext"
+#define WSTRUST_NS "http://schemas.xmlsoap.org/ws/2005/02/trust"
 
+namespace {
 
-using namespace std;
-using namespace saml;
-using namespace shibboleth;
-using namespace adfs;
-using namespace log4cpp;
+#ifndef SHIBSP_LITE
+    class SHIBSP_DLLLOCAL ADFSDecoder : public MessageDecoder
+    {
+        auto_ptr_XMLCh m_ns;
+    public:
+        ADFSDecoder() : m_ns(WSTRUST_NS) {}
+        virtual ~ADFSDecoder() {}
+        
+        XMLObject* decode(string& relayState, const GenericRequest& genericRequest, SecurityPolicy& policy) const;
 
-// Plugin Factories
-PlugManager::Factory ADFSListenerFactory;
-PlugManager::Factory ADFSSessionInitiatorFactory;
-PlugManager::Factory ADFSHandlerFactory;
+    protected:
+        void extractMessageDetails(
+            const XMLObject& message, const GenericRequest& req, const XMLCh* protocol, SecurityPolicy& policy
+            ) const {
+        }
+    };
 
+    MessageDecoder* ADFSDecoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
+    {
+        return new ADFSDecoder();
+    }
+#endif
 
-extern "C" int ADFS_EXPORTS saml_extension_init(void*)
-{
-    // Register extension schema.
-    saml::XML::registerSchema(adfs::XML::WSTRUST_NS,adfs::XML::WSTRUST_SCHEMA_ID);
+#if defined (_MSC_VER)
+    #pragma warning( push )
+    #pragma warning( disable : 4250 )
+#endif
 
-    // Register plugin factories (some override existing Shib functionality).
-    SAMLConfig& conf=SAMLConfig::getConfig();
-    conf.getPlugMgr().regFactory(shibtarget::XML::MemoryListenerType,&ADFSListenerFactory);
+    class SHIBSP_DLLLOCAL ADFSSessionInitiator : public SessionInitiator, public AbstractHandler, public RemotedHandler
+    {
+    public:
+        ADFSSessionInitiator(const DOMElement* e, const char* appId)
+                : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator.ADFS")), m_appId(appId), m_binding(WSFED_NS) {
+            // If Location isn't set, defer address registration until the setParent call.
+            pair<bool,const char*> loc = getString("Location");
+            if (loc.first) {
+                string address = m_appId + loc.second + "::run::ADFSSI";
+                setAddress(address.c_str());
+            }
+        }
+        virtual ~ADFSSessionInitiator() {}
+        
+        void setParent(const PropertySet* parent) {
+            DOMPropertySet::setParent(parent);
+            pair<bool,const char*> loc = getString("Location");
+            if (loc.first) {
+                string address = m_appId + loc.second + "::run::ADFSSI";
+                setAddress(address.c_str());
+            }
+            else {
+                m_log.warn("no Location property in ADFS SessionInitiator (or parent), can't register as remoted handler");
+            }
+        }
 
-    auto_ptr_char temp1(Constants::SHIB_SESSIONINIT_PROFILE_URI);
-    conf.getPlugMgr().regFactory(temp1.get(),&ADFSSessionInitiatorFactory);
+        void receive(DDF& in, ostream& out);
+        pair<bool,long> run(SPRequest& request, const char* entityID=NULL, bool isHandler=true) const;
+
+    private:
+        pair<bool,long> doRequest(
+            const Application& application,
+            HTTPResponse& httpResponse,
+            const char* entityID,
+            const char* acsLocation,
+            string& relayState
+            ) const;
+        string m_appId;
+        auto_ptr_XMLCh m_binding;
+    };
+
+    class SHIBSP_DLLLOCAL ADFSConsumer : public shibsp::AssertionConsumerService
+    {
+    public:
+        ADFSConsumer(const DOMElement* e, const char* appId)
+            : shibsp::AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SSO.ADFS"))
+#ifndef SHIBSP_LITE
+                ,m_protocol(WSFED_NS)
+#endif
+            {}
+        virtual ~ADFSConsumer() {}
 
-    auto_ptr_char temp2(adfs::XML::WSFED_NS);
-    conf.getPlugMgr().regFactory(temp2.get(),&ADFSHandlerFactory);
+#ifndef SHIBSP_LITE
+        void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
+            AssertionConsumerService::generateMetadata(role, handlerURL);
+            role.addSupport(m_protocol.get());
+        }
 
-    return 0;
-}
+        auto_ptr_XMLCh m_protocol;
+
+    private:
+        void implementProtocol(
+            const Application& application,
+            const HTTPRequest& httpRequest,
+            HTTPResponse& httpResponse,
+            SecurityPolicy& policy,
+            const PropertySet* settings,
+            const XMLObject& xmlObject
+            ) const;
+#endif
+    };
 
-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());
-}
+    class SHIBSP_DLLLOCAL ADFSLogoutInitiator : public AbstractHandler, public RemotedHandler
+    {
+    public:
+        ADFSLogoutInitiator(const DOMElement* e, const char* appId)
+                : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".LogoutInitiator.ADFS")), m_appId(appId), m_binding(WSFED_NS) {
+            // If Location isn't set, defer address registration until the setParent call.
+            pair<bool,const char*> loc = getString("Location");
+            if (loc.first) {
+                string address = m_appId + loc.second + "::run::ADFSLI";
+                setAddress(address.c_str());
+            }
+        }
+        virtual ~ADFSLogoutInitiator() {}
+        
+        void setParent(const PropertySet* parent) {
+            DOMPropertySet::setParent(parent);
+            pair<bool,const char*> loc = getString("Location");
+            if (loc.first) {
+                string address = m_appId + loc.second + "::run::ADFSLI";
+                setAddress(address.c_str());
+            }
+            else {
+                m_log.warn("no Location property in ADFS LogoutInitiator (or parent), can't register as remoted handler");
+            }
+        }
 
-// For now, we'll just put the meat of the profile here.
+        void receive(DDF& in, ostream& out);
+        pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
 
-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;
-}
+#ifndef SHIBSP_LITE
+        const char* getType() const {
+            return "LogoutInitiator";
+        }
+#endif
 
-/*************************************************************************
- * CGI Parser implementation
- */
+    private:
+        pair<bool,long> doRequest(const Application& application, const char* entityID, HTTPResponse& httpResponse) const;
 
-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);
+        string m_appId;
+        auto_ptr_XMLCh m_binding;
+    };
+
+    class SHIBSP_DLLLOCAL ADFSLogout : public AbstractHandler, public LogoutHandler
+    {
+    public:
+        ADFSLogout(const DOMElement* e, const char* appId)
+                : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".Logout.ADFS")), m_login(e, appId) {
+#ifndef SHIBSP_LITE
+            m_initiator = false;
+            m_preserve.push_back("wreply");
+            string address = string(appId) + getString("Location").second + "::run::ADFSLO";
+            setAddress(address.c_str());
+#endif
+        }
+        virtual ~ADFSLogout() {}
+
+        pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
+
+#ifndef SHIBSP_LITE
+        void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
+            m_login.generateMetadata(role, handlerURL);
+            const char* loc = getString("Location").second;
+            string hurl(handlerURL);
+            if (*loc != '/')
+                hurl += '/';
+            hurl += loc;
+            auto_ptr_XMLCh widen(hurl.c_str());
+            SingleLogoutService* ep = SingleLogoutServiceBuilder::buildSingleLogoutService();
+            ep->setLocation(widen.get());
+            ep->setBinding(m_login.m_protocol.get());
+            role.getSingleLogoutServices().push_back(ep);
+        }
+
+        const char* getType() const {
+            return m_login.getType();
+        }
+#endif
+
+    private:
+        ADFSConsumer m_login;
+    };
+
+#if defined (_MSC_VER)
+    #pragma warning( pop )
+#endif
+
+    SessionInitiator* ADFSSessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
+    {
+        return new ADFSSessionInitiator(p.first, p.second);
     }
-}
 
-CgiParse::~CgiParse()
+    Handler* ADFSLogoutFactory(const pair<const DOMElement*,const char*>& p)
+    {
+        return new ADFSLogout(p.first, p.second);
+    }
+
+    Handler* ADFSLogoutInitiatorFactory(const pair<const DOMElement*,const char*>& p)
+    {
+        return new ADFSLogoutInitiator(p.first, p.second);
+    }
+
+    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);
+    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);
+};
+
+extern "C" int ADFS_EXPORTS xmltooling_extension_init(void*)
 {
-    for (map<string,char*>::iterator i=kvp_map.begin(); i!=kvp_map.end(); i++)
-        free(i->second);
+    SPConfig& conf=SPConfig::getConfig();
+    conf.SessionInitiatorManager.registerFactory("ADFS", ADFSSessionInitiatorFactory);
+    conf.LogoutInitiatorManager.registerFactory("ADFS", ADFSLogoutInitiatorFactory);
+    conf.AssertionConsumerServiceManager.registerFactory("ADFS", ADFSLogoutFactory);
+    conf.AssertionConsumerServiceManager.registerFactory(WSFED_NS, ADFSLogoutFactory);
+#ifndef SHIBSP_LITE
+    SAMLConfig::getConfig().MessageDecoderManager.registerFactory(WSFED_NS, ADFSDecoderFactory);
+    XMLObjectBuilder::registerBuilder(QName(WSTRUST_NS,"RequestedSecurityToken"), new AnyElementBuilder());
+    XMLObjectBuilder::registerBuilder(QName(WSTRUST_NS,"RequestSecurityTokenResponse"), new AnyElementBuilder());
+#endif
+    return 0;
 }
 
-const char*
-CgiParse::get_value(const char* name) const
+extern "C" void ADFS_EXPORTS xmltooling_extension_term()
 {
-    map<string,char*>::const_iterator i=kvp_map.find(name);
-    if (i==kvp_map.end())
-        return NULL;
-    return i->second;
+    /* should get unregistered during normal shutdown...
+    SPConfig& conf=SPConfig::getConfig();
+    conf.SessionInitiatorManager.deregisterFactory("ADFS");
+    conf.LogoutInitiatorManager.deregisterFactory("ADFS");
+    conf.AssertionConsumerServiceManager.deregisterFactory("ADFS");
+    conf.AssertionConsumerServiceManager.deregisterFactory(WSFED_NS);
+#ifndef SHIBSP_LITE
+    SAMLConfig::getConfig().MessageDecoderManager.deregisterFactory(WSFED_NS);
+#endif
+    */
 }
 
-/* Parsing routines modified from NCSA source. */
-char *
-CgiParse::makeword(char *line, char stop)
+pair<bool,long> ADFSSessionInitiator::run(SPRequest& request, const char* entityID, bool isHandler) const
 {
-    int x = 0,y;
-    char *word = (char *) malloc(sizeof(char) * (strlen(line) + 1));
+    // We have to know the IdP to function.
+    if (!entityID || !*entityID)
+        return make_pair(false,0L);
+
+    string target;
+    const Handler* ACS=NULL;
+    const char* option;
+    const Application& app=request.getApplication();
+
+    if (isHandler) {
+        option = request.getParameter("target");
+        if (option)
+            target = option;
+
+        // Since we're passing the ACS by value, we need to compute the return URL,
+        // so we'll need the target resource for real.
+        recoverRelayState(request.getApplication(), request, request, target, false);
+    }
+    else {
+        // We're running as a "virtual handler" from within the filter.
+        // The target resource is the current one and everything else is defaulted.
+        target=request.getRequestURL();
+    }
+
+    // Since we're not passing by index, we need to fully compute the return URL.
+    // Get all the ADFS endpoints.
+    const vector<const Handler*>& handlers = app.getAssertionConsumerServicesByBinding(m_binding.get());
+
+    // Index comes from request, or default set in the handler, or we just pick the first endpoint.
+    pair<bool,unsigned int> index(false,0);
+    if (isHandler) {
+        option = request.getParameter("acsIndex");
+        if (option)
+            index = pair<bool,unsigned int>(true, atoi(option));
+    }
+    if (!index.first)
+        index = getUnsignedInt("defaultACSIndex");
+    if (index.first) {
+        for (vector<const Handler*>::const_iterator h = handlers.begin(); !ACS && h!=handlers.end(); ++h) {
+            if (index.second == (*h)->getUnsignedInt("index").second)
+                ACS = *h;
+        }
+    }
+    else if (!handlers.empty()) {
+        ACS = handlers.front();
+    }
+    if (!ACS)
+        throw ConfigurationException("Unable to locate ADFS response endpoint.");
+
+    // Compute the ACS URL. We add the ACS location to the base handlerURL.
+    string ACSloc=request.getHandlerURL(target.c_str());
+    pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
+    if (loc.first) ACSloc+=loc.second;
+
+    if (isHandler) {
+        // We may already have RelayState set if we looped back here,
+        // but just in case target is a resource, we reset it back.
+        target.erase();
+        option = request.getParameter("target");
+        if (option)
+            target = option;
+    }
 
-    for(x=0;((line[x]) && (line[x] != stop));x++)
-        word[x] = line[x];
+    m_log.debug("attempting to initiate session using ADFS with provider (%s)", entityID);
 
-    word[x] = '\0';
-    if(line[x])
-        ++x;
-    y=0;
+    if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess))
+        return doRequest(app, request, entityID, ACSloc.c_str(), target);
 
-    while(line[x])
-      line[y++] = line[x++];
-    line[y] = '\0';
-    return word;
+    // Remote the call.
+    DDF out,in = DDF(m_address.c_str()).structure();
+    DDFJanitor jin(in), jout(out);
+    in.addmember("application_id").string(app.getId());
+    in.addmember("entity_id").string(entityID);
+    in.addmember("acsLocation").string(ACSloc.c_str());
+    if (!target.empty())
+        in.addmember("RelayState").string(target.c_str());
+
+    // Remote the processing.
+    out = request.getServiceProvider().getListenerService()->send(in);
+    return unwrap(request, out);
 }
 
-char *
-CgiParse::fmakeword(char stop, unsigned int *cl, const char** ppch)
+void ADFSSessionInitiator::receive(DDF& in, ostream& out)
 {
-    int wsize;
-    char *word;
-    int ll;
+    // Find application.
+    const char* aid=in["application_id"].string();
+    const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
+    if (!app) {
+        // Something's horribly wrong.
+        m_log.error("couldn't find application (%s) to generate ADFS request", aid ? aid : "(missing)");
+        throw ConfigurationException("Unable to locate application for new session, deleted?");
+    }
 
-    wsize = 1024;
-    ll=0;
-    word = (char *) malloc(sizeof(char) * (wsize + 1));
+    const char* entityID = in["entity_id"].string();
+    const char* acsLocation = in["acsLocation"].string();
+    if (!entityID || !acsLocation)
+        throw ConfigurationException("No entityID or acsLocation parameter supplied to remoted SessionInitiator.");
 
-    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;
-    }
+    DDF ret(NULL);
+    DDFJanitor jout(ret);
+
+    // Wrap the outgoing object with a Response facade.
+    auto_ptr<HTTPResponse> http(getResponse(ret));
+
+    string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");
+
+    // Since we're remoted, the result should either be a throw, which we pass on,
+    // a false/0 return, which we just return as an empty structure, or a response/redirect,
+    // which we capture in the facade and send back.
+    doRequest(*app, *http.get(), entityID, acsLocation, relayState);
+    out << ret;
 }
 
-void
-CgiParse::plustospace(char *str)
+pair<bool,long> ADFSSessionInitiator::doRequest(
+    const Application& app,
+    HTTPResponse& httpResponse,
+    const char* entityID,
+    const char* acsLocation,
+    string& relayState
+    ) const
 {
-    register int x;
+#ifndef SHIBSP_LITE
+    // Use metadata to invoke the SSO service directly.
+    MetadataProvider* m=app.getMetadataProvider();
+    Locker locker(m);
+    MetadataProvider::Criteria mc(entityID, &IDPSSODescriptor::ELEMENT_QNAME, m_binding.get());
+    pair<const EntityDescriptor*,const RoleDescriptor*> entity=m->getEntityDescriptor(mc);
+    if (!entity.first) {
+        m_log.warn("unable to locate metadata for provider (%s)", entityID);
+        throw MetadataException("Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", entityID));
+    }
+    else if (!entity.second) {
+        m_log.warn("unable to locate ADFS-aware identity provider role for provider (%s)", entityID);
+        if (getParent())
+            return make_pair(false,0L);
+        throw MetadataException("Unable to locate ADFS-aware identity provider role for provider ($entityID)", namedparams(1, "entityID", entityID));
+    }
+    const EndpointType* ep = EndpointManager<SingleSignOnService>(
+        dynamic_cast<const IDPSSODescriptor*>(entity.second)->getSingleSignOnServices()
+        ).getByBinding(m_binding.get());
+    if (!ep) {
+        m_log.warn("unable to locate compatible SSO service for provider (%s)", entityID);
+        if (getParent())
+            return make_pair(false,0L);
+        throw MetadataException("Unable to locate compatible SSO service for provider ($entityID)", namedparams(1, "entityID", entityID));
+    }
+
+    preserveRelayState(app, httpResponse, relayState);
 
-    for(x=0;str[x];x++)
-        if(str[x] == '+') str[x] = ' ';
+    // UTC timestamp
+    time_t epoch=time(NULL);
+#ifndef HAVE_GMTIME_R
+    struct tm* ptime=gmtime(&epoch);
+#else
+    struct tm res;
+    struct tm* ptime=gmtime_r(&epoch,&res);
+#endif
+    char timebuf[32];
+    strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
+
+    auto_ptr_char dest(ep->getLocation());
+    const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
+
+    string req=string(dest.get()) + (strchr(dest.get(),'?') ? '&' : '?') + "wa=wsignin1.0&wreply=" + urlenc->encode(acsLocation) +
+        "&wct=" + urlenc->encode(timebuf) + "&wtrealm=" + urlenc->encode(app.getString("entityID").second);
+    if (!relayState.empty())
+        req += "&wctx=" + urlenc->encode(relayState.c_str());
+
+    return make_pair(true, httpResponse.sendRedirect(req.c_str()));
+#else
+    return make_pair(false,0L);
+#endif
 }
 
-char
-CgiParse::x2c(char *what)
-{
-    register char digit;
+#ifndef SHIBSP_LITE
 
-    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);
+XMLObject* ADFSDecoder::decode(string& relayState, const GenericRequest& genericRequest, SecurityPolicy& policy) const
+{
+#ifdef _DEBUG
+    xmltooling::NDC ndc("decode");
+#endif
+    Category& log = Category::getInstance(SHIBSP_LOGCAT".MessageDecoder.ADFS");
+
+    log.debug("validating input");
+    const HTTPRequest* httpRequest=dynamic_cast<const HTTPRequest*>(&genericRequest);
+    if (!httpRequest)
+        throw BindingException("Unable to cast request object to HTTPRequest type.");
+    if (strcmp(httpRequest->getMethod(),"POST"))
+        throw BindingException("Invalid HTTP method ($1).", params(1, httpRequest->getMethod()));
+    const char* param = httpRequest->getParameter("wa");
+    if (!param || strcmp(param, "wsignin1.0"))
+        throw BindingException("Missing or invalid wa parameter (should be wsignin1.0).");
+    param = httpRequest->getParameter("wctx");
+    if (param)
+        relayState = param;
+
+    param = httpRequest->getParameter("wresult");
+    if (!param)
+        throw BindingException("Request missing wresult parameter.");
+
+    log.debug("decoded ADFS response:\n%s", param);
+
+    // Parse and bind the document into an XMLObject.
+    istringstream is(param);
+    DOMDocument* doc = (policy.getValidating() ? XMLToolingConfig::getConfig().getValidatingParser()
+        : XMLToolingConfig::getConfig().getParser()).parse(is); 
+    XercesJanitor<DOMDocument> janitor(doc);
+    auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
+    janitor.release();
+
+    if (!XMLHelper::isNodeNamed(xmlObject->getDOM(), m_ns.get(), RequestSecurityTokenResponse))
+        throw BindingException("Decoded message was not of the appropriate type.");
+
+    if (!policy.getValidating())
+        SchemaValidators.validate(xmlObject.get());
+
+    // Skip policy step here, there's no security in the wrapper.
+    // policy.evaluate(*xmlObject.get(), &genericRequest);
+    
+    return xmlObject.release();
 }
 
-void
-CgiParse::url_decode(char *url)
+void ADFSConsumer::implementProtocol(
+    const Application& application,
+    const HTTPRequest& httpRequest,
+    HTTPResponse& httpResponse,
+    SecurityPolicy& policy,
+    const PropertySet* settings,
+    const XMLObject& xmlObject
+    ) const
 {
-    register int x,y;
+    // Implementation of ADFS profile.
+    m_log.debug("processing message against ADFS Passive Requester profile");
+
+    // With ADFS, all the security comes from the assertion, which is two levels down in the message.
+
+    const ElementProxy* response = dynamic_cast<const ElementProxy*>(&xmlObject);
+    if (!response || !response->hasChildren())
+        throw FatalProfileException("Incoming message was not of the proper type or contains no security token.");
+    response = dynamic_cast<const ElementProxy*>(response->getUnknownXMLObjects().front());
+    if (!response || !response->hasChildren())
+        throw FatalProfileException("Token wrapper element did not contain a security token.");
+    const saml1::Assertion* token = dynamic_cast<const saml1::Assertion*>(response->getUnknownXMLObjects().front());
+    if (!token || !token->getSignature())
+        throw FatalProfileException("Incoming message did not contain a signed SAML 1.1 assertion.");
+
+    // Extract message and issuer details from assertion.
+    extractMessageDetails(*token, m_protocol.get(), policy);
+
+    // Run the policy over the assertion. Handles replay, freshness, and
+    // signature verification, assuming the relevant rules are configured.
+    policy.evaluate(*token);
+    
+    // If no security is in place now, we kick it.
+    if (!policy.isAuthenticated())
+        throw SecurityPolicyException("Unable to establish security of incoming assertion.");
+
+    // Now do profile and core semantic validation to ensure we can use it for SSO.
+    // Profile validator.
+    time_t now = time(NULL);
+    saml1::AssertionValidator ssoValidator(application.getAudiences(), now);
+    ssoValidator.validateAssertion(*token);
+    if (!token->getConditions() || !token->getConditions()->getNotBefore() || !token->getConditions()->getNotOnOrAfter())
+        throw FatalProfileException("Assertion did not contain time conditions.");
+    else if (token->getAuthenticationStatements().empty())
+        throw FatalProfileException("Assertion did not contain an authentication statement.");
+    
 
-    for(x=0,y=0;url[y];++x,++y)
-    {
-        if((url[x] = url[y]) == '%')
-        {
-            url[x] = x2c(&url[y+1]);
-            y+=2;
-        }
+    // With ADFS, we only have one token, but we need to put it in a vector.
+    vector<const Assertion*> tokens(1,token);
+    const saml1::AuthenticationStatement* ssoStatement=token->getAuthenticationStatements().front();
+
+    // authnskew allows rejection of SSO if AuthnInstant is too old.
+    const PropertySet* sessionProps = application.getPropertySet("Sessions");
+    pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);
+
+    if (authnskew.first && authnskew.second &&
+            ssoStatement->getAuthenticationInstant() && (now - ssoStatement->getAuthenticationInstantEpoch() > authnskew.second))
+        throw FatalProfileException("The gap between now and the time you logged into your identity provider exceeds the limit.");
+
+    // Address checking.
+    saml1::SubjectLocality* locality = ssoStatement->getSubjectLocality();
+    if (locality && locality->getIPAddress()) {
+        auto_ptr_char ip(locality->getIPAddress());
+        checkAddress(application, httpRequest, ip.get());
     }
-    url[x] = '\0';
-}
 
-static inline char hexchar(unsigned short s)
-{
-    return (s<=9) ? ('0' + s) : ('A' + s - 10);
+    m_log.debug("ADFS profile processing completed successfully");
+
+    saml1::NameIdentifier* n = ssoStatement->getSubject()->getNameIdentifier();
+
+    // Now we have to extract the authentication details for attribute and session setup.
+
+    // Session expiration for ADFS is purely SP-driven, and the method is mapped to a ctx class.
+    pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
+    if (!lifetime.first || lifetime.second == 0)
+        lifetime.second = 28800;
+
+    // We've successfully "accepted" the SSO token.
+    // To complete processing, we need to extract and resolve attributes and then create the session.
+
+    // Normalize the SAML 1.x NameIdentifier...
+    auto_ptr<saml2::NameID> nameid(n ? saml2::NameIDBuilder::buildNameID() : NULL);
+    if (n) {
+        nameid->setName(n->getName());
+        nameid->setFormat(n->getFormat());
+        nameid->setNameQualifier(n->getNameQualifier());
+    }
+
+    // The context will handle deleting attributes and new tokens.
+    auto_ptr<ResolutionContext> ctx(
+        resolveAttributes(
+            application,
+            policy.getIssuerMetadata(),
+            m_protocol.get(),
+            n,
+            nameid.get(),
+            ssoStatement->getAuthenticationMethod(),
+            NULL,
+            &tokens
+            )
+        );
+
+    if (ctx.get()) {
+        // Copy over any new tokens, but leave them in the context for cleanup.
+        tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
+    }
+
+    application.getServiceProvider().getSessionCache()->insert(
+        application,
+        httpRequest,
+        httpResponse,
+        now + lifetime.second,
+        policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL,
+        m_protocol.get(),
+        nameid.get(),
+        ssoStatement->getAuthenticationInstant() ? ssoStatement->getAuthenticationInstant()->getRawData() : NULL,
+        NULL,
+        ssoStatement->getAuthenticationMethod(),
+        NULL,
+        &tokens,
+        ctx.get() ? &ctx->getResolvedAttributes() : NULL
+        );
 }
 
-string CgiParse::url_encode(const char* s)
+#endif
+
+pair<bool,long> ADFSLogoutInitiator::run(SPRequest& request, bool isHandler) const
 {
-    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);
+    // Normally we'd do notifications and session clearage here, but ADFS logout
+    // is missing the needed request/response features, so we have to rely on
+    // the IdP half to notify us back about the logout and do the work there.
+    // Basically we have no way to tell in the Logout receiving handler whether
+    // we initiated the logout or not.
+
+    Session* session = NULL;
+    try {
+        session = request.getSession(false, true, false);  // don't cache it and ignore all checks
+        if (!session)
+            return make_pair(false,0L);
+
+        // We only handle ADFS sessions.
+        if (!XMLString::equals(session->getProtocol(), WSFED_NS) || !session->getEntityID()) {
+            session->unlock();
+            return make_pair(false,0L);
         }
-        else
-            ret+=*s;
     }
-    return ret;
-}
+    catch (exception& ex) {
+        m_log.error("error accessing current session: %s", ex.what());
+        return make_pair(false,0L);
+    }
 
-// CDC implementation
+    string entityID(session->getEntityID());
+    session->unlock();
 
-const char CommonDomainCookie::CDCName[] = "_saml_idp";
+    if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
+        // When out of process, we run natively.
+        return doRequest(request.getApplication(), entityID.c_str(), request);
+    }
+    else {
+        // When not out of process, we remote the request.
+        Locker locker(session, false);
+        DDF out,in(m_address.c_str());
+        DDFJanitor jin(in), jout(out);
+        in.addmember("application_id").string(request.getApplication().getId());
+        in.addmember("entity_id").string(entityID.c_str());
+        out=request.getServiceProvider().getListenerService()->send(in);
+        return unwrap(request, out);
+    }
+}
 
-CommonDomainCookie::CommonDomainCookie(const char* cookie)
+void ADFSLogoutInitiator::receive(DDF& in, ostream& out)
 {
-    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;
+#ifndef SHIBSP_LITE
+    // Find application.
+    const char* aid=in["application_id"].string();
+    const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
+    if (!app) {
+        // Something's horribly wrong.
+        m_log.error("couldn't find application (%s) for logout", aid ? aid : "(missing)");
+        throw ConfigurationException("Unable to locate application for logout, deleted?");
     }
-    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);
+    
+    // Set up a response shim.
+    DDF ret(NULL);
+    DDFJanitor jout(ret);
+    auto_ptr<HTTPResponse> resp(getResponse(ret));
+    
+    // Since we're remoted, the result should either be a throw, which we pass on,
+    // a false/0 return, which we just return as an empty structure, or a response/redirect,
+    // which we capture in the facade and send back.
+    doRequest(*app, in["entity_id"].string(), *resp.get());
+
+    out << ret;
+#else
+    throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
+#endif
+}
+
+pair<bool,long> ADFSLogoutInitiator::doRequest(const Application& application, const char* entityID, HTTPResponse& response) const
+{
+#ifndef SHIBSP_LITE
+    try {
+        if (!entityID)
+            throw ConfigurationException("Missing entityID parameter.");
+
+        // With a session in hand, we can create a request message, if we can find a compatible endpoint.
+        MetadataProvider* m=application.getMetadataProvider();
+        Locker locker(m);
+        MetadataProvider::Criteria mc(entityID, &IDPSSODescriptor::ELEMENT_QNAME, m_binding.get());
+        pair<const EntityDescriptor*,const RoleDescriptor*> entity=m->getEntityDescriptor(mc);
+        if (!entity.first)
+            throw MetadataException("Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", entityID));
+        else if (!entity.second)
+            throw MetadataException("Unable to locate ADFS IdP role for identity provider ($entityID).", namedparams(1, "entityID", entityID));
+
+        const EndpointType* ep = EndpointManager<SingleLogoutService>(
+            dynamic_cast<const IDPSSODescriptor*>(entity.second)->getSingleLogoutServices()
+            ).getByBinding(m_binding.get());
+        if (!ep) {
+            throw MetadataException(
+                "Unable to locate ADFS single logout service for identity provider ($entityID).",
+                namedparams(1, "entityID", entityID)
+                );
         }
-        else
-            log.warn("cookie element does not appear to be base64-encoded");
+
+        auto_ptr_char dest(ep->getLocation());
+
+        string req=string(dest.get()) + (strchr(dest.get(),'?') ? '&' : '?') + "wa=wsignout1.0";
+        return make_pair(true,response.sendRedirect(req.c_str()));
     }
+    catch (exception& ex) {
+        m_log.error("error issuing ADFS logout request: %s", ex.what());
+    }
+
+    return make_pair(false,0L);
+#else
+    throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
+#endif
 }
 
-const char* CommonDomainCookie::set(const char* providerId)
+pair<bool,long> ADFSLogout::run(SPRequest& request, bool isHandler) const
 {
-    // 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;
-        }
+    // Defer to base class for front-channel loop first.
+    // This won't initiate the loop, only continue/end it.
+    pair<bool,long> ret = LogoutHandler::run(request, isHandler);
+    if (ret.first)
+        return ret;
+
+    // wa parameter indicates the "action" to perform
+    bool returning = false;
+    const char* param = request.getParameter("wa");
+    if (param) {
+        if (!strcmp(param, "wsignin1.0"))
+            return m_login.run(request, isHandler);
+        else if (strcmp(param, "wsignout1.0") && strcmp(param, "wsignoutcleanup1.0"))
+            throw FatalProfileException("Unsupported WS-Federation action paremeter ($1).", params(1, param));
     }
-    
-    // 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);
+    else if (strcmp(request.getMethod(),"GET") || !request.getParameter("notifying"))
+        throw FatalProfileException("Unsupported request to ADFS protocol endpoint.");
+    else
+        returning = true;
+
+    param = request.getParameter("wreply");
+    const Application& app = request.getApplication();
+
+    if (!returning) {
+        // Pass control to the first front channel notification point, if any.
+        map<string,string> parammap;
+        if (param)
+            parammap["wreply"] = param;
+        pair<bool,long> result = notifyFrontChannel(app, request, request, &parammap);
+        if (result.first)
+            return result;
     }
-    
-    m_encoded=CgiParse::url_encode(delimited.c_str());
-    return m_encoded.c_str();
+
+    // Best effort on back channel and to remove the user agent's session.
+    string session_id = app.getServiceProvider().getSessionCache()->active(app, request);
+    if (!session_id.empty()) {
+        vector<string> sessions(1,session_id);
+        notifyBackChannel(app, request.getRequestURL(), sessions, false);
+        try {
+            app.getServiceProvider().getSessionCache()->remove(app, request, &request);
+        }
+        catch (exception& ex) {
+            m_log.error("error removing session (%s): %s", session_id.c_str(), ex.what());
+        }
+    }
+
+    if (param)
+        return make_pair(true, request.sendRedirect(param));
+    return sendLogoutPage(app, request, request, false, "Logout complete.");
 }