Fix backslashes in SHIBSP_PREFIX variable by manually creating it during the script...
[shibboleth/sp.git] / nsapi_shib / nsapi_shib.cpp
index 71514be..d1efdc4 100644 (file)
@@ -1,5 +1,5 @@
 /*
- *  Copyright 2001-2005 Internet2
+ *  Copyright 2001-2007 Internet2
  * 
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -20,6 +20,8 @@
  * Shibboleth NSAPI filter
  */
 
+#define SHIBSP_LITE
+
 #if defined (_MSC_VER) || defined(__BORLANDC__)
 # include "config_win32.h"
 #else
 # define _CRT_SECURE_NO_DEPRECATE 1
 #endif
 
+#include <shibsp/AbstractSPRequest.h>
 #include <shibsp/RequestMapper.h>
 #include <shibsp/SPConfig.h>
+#include <shibsp/ServiceProvider.h>
+#include <xmltooling/XMLToolingConfig.h>
 #include <xmltooling/util/NDC.h>
 #include <xmltooling/util/Threads.h>
-
-// SAML Runtime
-#include <saml/saml.h>
-#include <shib/shib.h>
-#include <shib-target/shib-target.h>
+#include <xmltooling/util/XMLConstants.h>
+#include <xmltooling/util/XMLHelper.h>
+#include <xercesc/util/XMLUniDefs.hpp>
 
 #include <fstream>
 #include <sstream>
@@ -60,7 +63,6 @@ extern "C"
 }
 
 using namespace shibsp;
-using namespace shibtarget;
 using namespace xmltooling;
 using namespace std;
 
@@ -69,22 +71,27 @@ using namespace std;
     if (IO_ERROR==net_write(sn->csd,str,strlen(str))) return REQ_EXIT
 
 namespace {
-    ShibTargetConfig* g_Config=NULL;
+    SPConfig* g_Config=NULL;
     string g_ServerName;
     string g_ServerScheme;
     string g_unsetHeaderValue;
+    bool g_checkSpoofing = true;
+    bool g_catchAll = false;
+
+    static const XMLCh path[] =     UNICODE_LITERAL_4(p,a,t,h);
+    static const XMLCh validate[] = UNICODE_LITERAL_8(v,a,l,i,d,a,t,e);
 }
 
-PluginManager<RequestMapper,const DOMElement*>::Factory SunRequestMapFactory;
+PluginManager<RequestMapper,string,const xercesc::DOMElement*>::Factory SunRequestMapFactory;
 
 extern "C" NSAPI_PUBLIC void nsapi_shib_exit(void*)
 {
     if (g_Config)
-        g_Config->shutdown();
+        g_Config->term();
     g_Config = NULL;
 }
 
-extern "C" NSAPI_PUBLIC int nsapi_shib_init(pblock* pb, Session* sn, Request* rq)
+extern "C" NSAPI_PUBLIC int nsapi_shib_init(pblock* pb, ::Session* sn, Request* rq)
 {
     // Save off a default hostname for this virtual server.
     char* name=pblock_findval("server-name",pb);
@@ -112,112 +119,104 @@ extern "C" NSAPI_PUBLIC int nsapi_shib_init(pblock* pb, Session* sn, Request* rq
 
     log_error(LOG_INFORM,"nsapi_shib_init",sn,rq,"nsapi_shib loaded for host (%s)",g_ServerName.c_str());
 
-#ifndef _DEBUG
-    try {
-#endif
-        const char* schemadir=pblock_findval("shib-schemas",pb);
-        if (!schemadir)
-            schemadir=getenv("SHIBSCHEMAS");
-        if (!schemadir)
-            schemadir=SHIB_SCHEMAS;
-        const char* config=pblock_findval("shib-config",pb);
-        if (!config)
-            config=getenv("SHIBCONFIG");
-        if (!config)
-            config=SHIB_CONFIG;
-        g_Config=&ShibTargetConfig::getConfig();
-        SPConfig::getConfig().setFeatures(
-            SPConfig::Listener |
-            SPConfig::Caching |
-            SPConfig::Metadata |
-            SPConfig::AAP |
-            SPConfig::RequestMapping |
-            SPConfig::InProcess |
-            SPConfig::Logging
-            );
-        if (!g_Config->init(schemadir)) {
-            g_Config=NULL;
-            pblock_nvinsert("error","unable to initialize Shibboleth libraries",pb);
-            return REQ_ABORTED;
-        }
-
-        SPConfig::getConfig().RequestMapperManager.registerFactory(XML_REQUEST_MAPPER,&SunRequestMapFactory);
+    const char* schemadir=pblock_findval("shib-schemas",pb);
+    const char* prefix=pblock_findval("shib-prefix",pb);
+
+    g_Config=&SPConfig::getConfig();
+    g_Config->setFeatures(
+        SPConfig::Listener |
+        SPConfig::Caching |
+        SPConfig::RequestMapping |
+        SPConfig::InProcess |
+        SPConfig::Logging |
+        SPConfig::Handlers
+        );
+    if (!g_Config->init(schemadir,prefix)) {
+        g_Config=NULL;
+        pblock_nvinsert("error","unable to initialize Shibboleth libraries",pb);
+        return REQ_ABORTED;
+    }
 
-        if (!g_Config->load(config)) {
-            g_Config=NULL;
-            pblock_nvinsert("error","unable to initialize load Shibboleth configuration",pb);
-            return REQ_ABORTED;
-        }
+    g_Config->RequestMapperManager.registerFactory(XML_REQUEST_MAPPER,&SunRequestMapFactory);
 
-        daemon_atrestart(nsapi_shib_exit,NULL);
+    const char* config=pblock_findval("shib-config",pb);
+    if (!config)
+        config=getenv("SHIBSP_CONFIG");
+    if (!config)
+        config=SHIBSP_CONFIG;
 
-        IConfig* conf=g_Config->getINI();
-        Locker locker(conf);
-        const PropertySet* props=conf->getPropertySet("Local");
-        if (props) {
-            pair<bool,const char*> unsetValue=props->getString("unsetHeaderValue");
-            if (unsetValue.first)
-                g_unsetHeaderValue = unsetValue.second;
-        }
-#ifndef _DEBUG
+    try {
+        xercesc::DOMDocument* dummydoc=XMLToolingConfig::getConfig().getParser().newDocument();
+        XercesJanitor<xercesc::DOMDocument> docjanitor(dummydoc);
+        xercesc::DOMElement* dummy = dummydoc->createElementNS(NULL,path);
+        auto_ptr_XMLCh src(config);
+        dummy->setAttributeNS(NULL,path,src.get());
+        dummy->setAttributeNS(NULL,validate,xmlconstants::XML_ONE);
+
+        g_Config->setServiceProvider(g_Config->ServiceProviderManager.newPlugin(XML_SERVICE_PROVIDER,dummy));
+        g_Config->getServiceProvider()->init();
     }
-    catch (...) {
+    catch (exception& ex) {
+        pblock_nvinsert("error",ex.what(),pb);
+        g_Config->term();
         g_Config=NULL;
-        pblock_nvinsert("error","caught exception, unable to initialize Shibboleth libraries",pb);
         return REQ_ABORTED;
     }
-#endif
+
+    daemon_atrestart(nsapi_shib_exit,NULL);
+
+    ServiceProvider* sp=g_Config->getServiceProvider();
+    Locker locker(sp);
+    const PropertySet* props=sp->getPropertySet("Local");
+    if (props) {
+        pair<bool,const char*> unsetValue=props->getString("unsetHeaderValue");
+        if (unsetValue.first)
+            g_unsetHeaderValue = unsetValue.second;
+        pair<bool,bool> flag=props->getBool("checkSpoofing");
+        g_checkSpoofing = !flag.first || flag.second;
+        flag=props->getBool("catchAll");
+        g_catchAll = flag.first && flag.second;
+    }
     return REQ_PROCEED;
 }
 
 /********************************************************************************/
 // NSAPI Shib Target Subclass
 
-class ShibTargetNSAPI : public ShibTarget
+class ShibTargetNSAPI : public AbstractSPRequest
 {
-  string m_uri;
   mutable string m_body;
-  mutable bool m_gotBody;
-  vector<XSECCryptoX509*> m_certs;
+  mutable bool m_gotBody,m_firsttime;
+  mutable vector<string> m_certs;
+  set<string> m_allhttp;
 
 public:
-  ShibTargetNSAPI(pblock* pb, Session* sn, Request* rq) : m_gotBody(false) {
-    m_pb = pb;
-    m_sn = sn;
-    m_rq = rq;
+  pblock* m_pb;
+  ::Session* m_sn;
+  Request* m_rq;
+
+  ShibTargetNSAPI(pblock* pb, ::Session* sn, Request* rq)
+      : AbstractSPRequest(SHIBSP_LOGCAT".NSAPI"), m_gotBody(false), m_firsttime(true), m_pb(pb), m_sn(sn), m_rq(rq) {
 
-    // Get everything but hostname...
     const char* uri=pblock_findval("uri", rq->reqpb);
     const char* qstr=pblock_findval("query", rq->reqpb);
 
-    string url;
-    if (uri) {
-        url = uri;
-        m_uri = uri;
+    if (qstr) {
+        string temp = string(uri) + '?' + qstr;
+        setRequestURI(temp.c_str());
+    }
+    else {
+        setRequestURI(uri);
     }
-    if (qstr)
-        url=url + '?' + qstr;
-    
-    const char* host=NULL;
-#ifdef vs_is_default_vs
-    // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
-    if (!vs_is_default_vs)
-        // The beauty here is, a non-default vhost can *only* be accessed if the client
-        // specified the exact name in the Host header. So we can trust the Host header.
-        host=pblock_findval("host", rq->headers);
-    else
-#endif
-    // In other cases, we're going to rely on the initialization process...
-    host=g_ServerName.c_str();
 
-    init(
-        security_active ? "https" : "http",
-        host,
-        server_portnum,
-        url.c_str()
-        );
+    // See if this is the first time we've run.
+    qstr = pblock_findval("auth-type", rq->vars);
+    if (qstr && !strcmp(qstr, "shibboleth"))
+        m_firsttime = false;
+    if (!m_firsttime || rq->orig_rq)
+        log(SPDebug, "nsapi_shib function running more than once");
   }
-  ~ShibTargetNSAPI() {}
+  ~ShibTargetNSAPI() { }
 
   const char* getScheme() const {
     return security_active ? "https" : "http";
@@ -225,7 +224,7 @@ public:
   const char* getHostname() const {
 #ifdef vs_is_default_vs
     // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
-    if (!vs_is_default_vs)
+    if (!vs_is_default_vs(request_get_vs(m_rq)))
         // The beauty here is, a non-default vhost can *only* be accessed if the client
         // specified the exact name in the Host header. So we can trust the Host header.
         return pblock_findval("host", m_rq->headers);
@@ -237,9 +236,6 @@ public:
   int getPort() const {
     return server_portnum;
   }
-  const char* getRequestURI() const {
-    return m_uri.c_str();
-  }
   const char* getMethod() const {
     return pblock_findval("method", m_rq->reqpb);
   }
@@ -258,7 +254,7 @@ public:
   string getRemoteAddr() const {
     return pblock_findval("ip", m_sn->client);
   }
-  void log(SPLogLevel level, const string& msg) {
+  void log(SPLogLevel level, const string& msg) const {
     AbstractSPRequest::log(level,msg);
     if (level>=SPError)
         log_error(LOG_FAILURE, "nsapi_shib", m_sn, m_rq, const_cast<char*>(msg.c_str()));
@@ -270,9 +266,8 @@ public:
     if (m_gotBody)
         return m_body.c_str();
     char* content_length=NULL;
-    if (request_header("content-length", &content_length, m_sn, m_rq)!=REQ_PROCEED ||
-         atoi(content_length) > 1024*1024) // 1MB?
-      throw opensaml::BindingException("Blocked POST request body exceeding size limit.");
+    if (request_header("content-length", &content_length, m_sn, m_rq)!=REQ_PROCEED || atoi(content_length) > 1024*1024) // 1MB?
+      throw opensaml::SecurityPolicyException("Blocked request body exceeding 1M size limit.");
     else {
       char ch=IO_EOF+1;
       int cl=atoi(content_length);
@@ -286,35 +281,63 @@ public:
         cl--;
       }
       if (cl)
-        throw opensaml::BindingException("Error reading POST request body from browser.");
+        throw IOException("Error reading request body from browser.");
       return m_body.c_str();
     }
   }
-  void clearHeader(const char* name) {
-    if (!strcmp(name,"REMOTE_USER")) {
-        param_free(pblock_remove("auth-user",m_rq->vars));
-        param_free(pblock_remove("remote-user",m_rq->headers));
-    }
-    else {
-        param_free(pblock_remove(name, m_rq->headers));
-        pblock_nvinsert(name, g_unsetHeaderValue.c_str() ,m_rq->headers);
+  void clearHeader(const char* rawname, const char* cginame) {
+    if (g_checkSpoofing && m_firsttime && !m_rq->orig_rq) {
+        if (m_allhttp.empty()) {
+            // Populate the set of client-supplied headers for spoof checking.
+            const pb_entry* entry;
+            for (int i=0; i<m_rq->headers->hsize; ++i) {
+                entry = m_rq->headers->ht[i];
+                while (entry) {
+                    string cgiversion("HTTP_");
+                    const char* pch = entry->param->name;
+                    while (*pch) {
+                        cgiversion += (isalnum(*pch) ? toupper(*pch) : '_');
+                        pch++;
+                    }
+                    m_allhttp.insert(cgiversion);
+                    entry = entry->next;
+                }
+            }
+        }
+        if (m_allhttp.count(cginame) > 0)
+            throw opensaml::SecurityPolicyException("Attempt to spoof header ($1) was detected.", params(1, rawname));
     }
+    param_free(pblock_remove(rawname, m_rq->headers));
+    pblock_nvinsert(rawname, g_unsetHeaderValue.c_str(), m_rq->headers);
   }
   void setHeader(const char* name, const char* value) {
+    param_free(pblock_remove(name, m_rq->headers));
     pblock_nvinsert(name, value, m_rq->headers);
   }
   string getHeader(const char* name) const {
+    // NSAPI headers tend to be lower case. We'll special case "cookie" since it's used a lot.
     char* hdr = NULL;
-    if (request_header(const_cast<char*>(name), &hdr, m_sn, m_rq) != REQ_PROCEED)
-      hdr = NULL;
+    int cookie = strcmp(name, "Cookie");
+    if (cookie == 0)
+        name = "cookie";
+    if (request_header(const_cast<char*>(name), &hdr, m_sn, m_rq) != REQ_PROCEED) {
+      // We didn't get a hit, so we'll try a lower-casing operation, unless we already did...
+      if (cookie == 0)
+          return "";
+      string n;
+      while (*name)
+          n += tolower(*(name++));
+      if (request_header(const_cast<char*>(n.c_str()), &hdr, m_sn, m_rq) != REQ_PROCEED)
+          return "";
+    }
     return string(hdr ? hdr : "");
   }
   void setRemoteUser(const char* user) {
-    pblock_nvinsert("remote-user", user, m_rq->headers);
     pblock_nvinsert("auth-user", user, m_rq->vars);
   }
   string getRemoteUser() const {
-    return getHeader("remote-user");
+    const char* ru = pblock_findval("auth-user", m_rq->vars);
+    return ru ? ru : "";
   }
   void setResponseHeader(const char* name, const char* value) {
     pblock_nvinsert(name, value, m_rq->srvhdrs);
@@ -347,18 +370,19 @@ public:
   }
   long returnDecline() { return REQ_NOACTION; }
   long returnOK() { return REQ_PROCEED; }
-  const vector<XSECCryptoX509*>& getClientCertificates() const {
+  const vector<string>& getClientCertificates() const {
+      if (m_certs.empty()) {
+          const char* cert = pblock_findval("auth-cert", m_rq->vars);
+          if (cert)
+              m_certs.push_back(cert);
+      }
       return m_certs;
   }
-
-  pblock* m_pb;
-  Session* m_sn;
-  Request* m_rq;
 };
 
 /********************************************************************************/
 
-int WriteClientError(Session* sn, Request* rq, char* func, char* msg)
+int WriteClientError(::Session* sn, Request* rq, char* func, char* msg)
 {
     log_error(LOG_FAILURE,func,sn,rq,msg);
     protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,msg);
@@ -367,7 +391,7 @@ int WriteClientError(Session* sn, Request* rq, char* func, char* msg)
 
 #undef FUNC
 #define FUNC "shibboleth"
-extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, Session* sn, Request* rq)
+extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, ::Session* sn, Request* rq)
 {
   ostringstream threadid;
   threadid << "[" << getpid() << "] nsapi_shib" << '\0';
@@ -377,7 +401,7 @@ extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, Session* sn, Request* rq)
     ShibTargetNSAPI stn(pb, sn, rq);
 
     // Check user authentication
-    pair<bool,long> res = stn.doCheckAuthN();
+    pair<bool,long> res = stn.getServiceProvider().doAuthentication(stn);
     if (res.first) return (int)res.second;
 
     // user authN was okay -- export the assertions now
@@ -385,11 +409,11 @@ extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, Session* sn, Request* rq)
     // This seems to be required in order to eventually set
     // the auth-user var.
     pblock_nvinsert("auth-type","shibboleth",rq->vars);
-    res = stn.doExportAssertions();
+    res = stn.getServiceProvider().doExport(stn);
     if (res.first) return (int)res.second;
 
     // Check the Authorization
-    res = stn.doCheckAuthZ();
+    res = stn.getServiceProvider().doAuthorization(stn);
     if (res.first) return (int)res.second;
 
     // this user is ok.
@@ -399,17 +423,18 @@ extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, Session* sn, Request* rq)
     log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
     return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an exception, see web server log for error.");
   }
-#ifndef _DEBUG
   catch (...) {
-    return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an uncaught exception.");
+    log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>("Shibboleth module threw an unknown exception."));
+    if (g_catchAll)
+        return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an unknown exception.");
+    throw;
   }
-#endif
 }
 
 
 #undef FUNC
 #define FUNC "shib_handler"
-extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, Session* sn, Request* rq)
+extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, ::Session* sn, Request* rq)
 {
   ostringstream threadid;
   threadid << "[" << getpid() << "] shib_handler" << '\0';
@@ -418,7 +443,7 @@ extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, Session* sn, Request* rq)
   try {
     ShibTargetNSAPI stn(pb, sn, rq);
 
-    pair<bool,long> res = stn.doHandler();
+    pair<bool,long> res = stn.getServiceProvider().doHandler(stn);
     if (res.first) return (int)res.second;
 
     return WriteClientError(sn, rq, FUNC, "Shibboleth handler did not do anything.");
@@ -427,30 +452,33 @@ extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, Session* sn, Request* rq)
     log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
     return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an exception, see web server log for error.");
   }
-#ifndef _DEBUG
   catch (...) {
-    return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an unknown exception.");
+    if (g_catchAll)
+        return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an unknown exception.");
+    throw;
   }
-#endif
 }
 
 
 class SunRequestMapper : public virtual RequestMapper, public virtual PropertySet
 {
 public:
-    SunRequestMapper(const DOMElement* e);
+    SunRequestMapper(const xercesc::DOMElement* e);
     ~SunRequestMapper() { delete m_mapper; delete m_stKey; delete m_propsKey; }
     Lockable* lock() { return m_mapper->lock(); }
     void unlock() { m_stKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
-    Settings getSettings(const SPRequest& request) const;
+    Settings getSettings(const HTTPRequest& request) const;
     
+    const PropertySet* getParent() const { return NULL; }
+    void setParent(const PropertySet*) {}
     pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
     pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
     pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
     pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
     pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
-    const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
-    const DOMElement* getElement() const;
+    void getAll(map<string,const char*>& properties) const;
+    const PropertySet* getPropertySet(const char* name, const char* ns=shibspconstants::ASCII_SHIB2SPCONFIG_NS) const;
+    const xercesc::DOMElement* getElement() const;
 
 private:
     RequestMapper* m_mapper;
@@ -458,19 +486,19 @@ private:
     ThreadKey* m_propsKey;
 };
 
-RequestMapper* SunRequestMapFactory(const DOMElement* const & e)
+RequestMapper* SunRequestMapFactory(const xercesc::DOMElement* const & e)
 {
     return new SunRequestMapper(e);
 }
 
-SunRequestMapper::SunRequestMapper(const DOMElement* e) : m_mapper(NULL), m_stKey(NULL), m_propsKey(NULL)
+SunRequestMapper::SunRequestMapper(const xercesc::DOMElement* e) : m_mapper(NULL), m_stKey(NULL), m_propsKey(NULL)
 {
     m_mapper = SPConfig::getConfig().RequestMapperManager.newPlugin(XML_REQUEST_MAPPER,e);
     m_stKey=ThreadKey::create(NULL);
     m_propsKey=ThreadKey::create(NULL);
 }
 
-RequestMapper::Settings SunRequestMapper::getSettings(const SPRequest& request) const
+RequestMapper::Settings SunRequestMapper::getSettings(const HTTPRequest& request) const
 {
     Settings s=m_mapper->getSettings(request);
     m_stKey->setData((void*)dynamic_cast<const ShibTargetNSAPI*>(&request));
@@ -540,13 +568,32 @@ pair<bool,int> SunRequestMapper::getInt(const char* name, const char* ns) const
     return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
 }
 
+void SunRequestMapper::getAll(map<string,const char*>& properties) const
+{
+    const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
+    const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
+    if (s)
+        s->getAll(properties);
+    if (!stn)
+        return;
+    properties["authType"] = "shibboleth";
+    const pb_entry* entry;
+    for (int i=0; i<stn->m_pb->hsize; ++i) {
+        entry = stn->m_pb->ht[i];
+        while (entry) {
+            properties[entry->param->name] = entry->param->value;
+            entry = entry->next;
+        }
+    }
+}
+
 const PropertySet* SunRequestMapper::getPropertySet(const char* name, const char* ns) const
 {
     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
     return s ? s->getPropertySet(name,ns) : NULL;
 }
 
-const DOMElement* SunRequestMapper::getElement() const
+const xercesc::DOMElement* SunRequestMapper::getElement() const
 {
     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
     return s ? s->getElement() : NULL;