https://issues.shibboleth.net/jira/browse/SSPCPP-175
[shibboleth/cpp-sp.git] / nsapi_shib / nsapi_shib.cpp
index f20ed7d..1523c78 100644 (file)
@@ -1,6 +1,6 @@
 /*
  *  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.
  * You may obtain a copy of the License at
@@ -16,7 +16,7 @@
 
 /**
  * nsapi_shib.cpp
- * 
+ *
  * Shibboleth NSAPI filter
  */
 
 #include <xmltooling/util/XMLHelper.h>
 #include <xercesc/util/XMLUniDefs.hpp>
 
+#include <memory>
 #include <fstream>
 #include <sstream>
+#include <stdexcept>
 
 #ifdef WIN32
 # include <process.h>
@@ -75,6 +77,7 @@ namespace {
     string g_ServerName;
     string g_ServerScheme;
     string g_unsetHeaderValue;
+    string g_spoofKey;
     bool g_checkSpoofing = true;
     bool g_catchAll = false;
 
@@ -120,15 +123,8 @@ extern "C" NSAPI_PUBLIC int nsapi_shib_init(pblock* pb, ::Session* sn, Request*
     log_error(LOG_INFORM,"nsapi_shib_init",sn,rq,"nsapi_shib loaded for host (%s)",g_ServerName.c_str());
 
     const char* schemadir=pblock_findval("shib-schemas",pb);
-    if (!schemadir)
-        schemadir=getenv("SHIBSP_SCHEMAS");
-    if (!schemadir)
-        schemadir=SHIBSP_SCHEMAS;
-    const char* config=pblock_findval("shib-config",pb);
-    if (!config)
-        config=getenv("SHIBSP_CONFIG");
-    if (!config)
-        config=SHIBSP_CONFIG;
+    const char* prefix=pblock_findval("shib-prefix",pb);
+
     g_Config=&SPConfig::getConfig();
     g_Config->setFeatures(
         SPConfig::Listener |
@@ -138,24 +134,17 @@ extern "C" NSAPI_PUBLIC int nsapi_shib_init(pblock* pb, ::Session* sn, Request*
         SPConfig::Logging |
         SPConfig::Handlers
         );
-    if (!g_Config->init(schemadir)) {
+    if (!g_Config->init(schemadir,prefix)) {
         g_Config=NULL;
         pblock_nvinsert("error","unable to initialize Shibboleth libraries",pb);
         return REQ_ABORTED;
     }
 
-    g_Config->RequestMapperManager.registerFactory(XML_REQUEST_MAPPER,&SunRequestMapFactory);
+    g_Config->RequestMapperManager.registerFactory(NATIVE_REQUEST_MAPPER,&SunRequestMapFactory);
 
     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();
+        if (!g_Config->instantiate(pblock_findval("shib-config",pb), true))
+            throw runtime_error("unknown error");
     }
     catch (exception& ex) {
         pblock_nvinsert("error",ex.what(),pb);
@@ -168,13 +157,18 @@ extern "C" NSAPI_PUBLIC int nsapi_shib_init(pblock* pb, ::Session* sn, Request*
 
     ServiceProvider* sp=g_Config->getServiceProvider();
     Locker locker(sp);
-    const PropertySet* props=sp->getPropertySet("Local");
+    const PropertySet* props=sp->getPropertySet("InProcess");
     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;
+        if (g_checkSpoofing) {
+            unsetValue=props->getString("spoofKey");
+            if (unsetValue.first)
+                g_spoofKey = unsetValue.second;
+        }
         flag=props->getBool("catchAll");
         g_catchAll = flag.first && flag.second;
     }
@@ -186,28 +180,40 @@ extern "C" NSAPI_PUBLIC int nsapi_shib_init(pblock* pb, ::Session* sn, Request*
 
 class ShibTargetNSAPI : public AbstractSPRequest
 {
-  string m_uri;
   mutable string m_body;
-  mutable bool m_gotBody;
+  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) {
 
     const char* uri=pblock_findval("uri", rq->reqpb);
     const char* qstr=pblock_findval("query", rq->reqpb);
 
-    if (uri)
-        m_uri = uri;
-    if (qstr)
-        m_uri = m_uri + '?' + qstr;
-  }
-  ~ShibTargetNSAPI() {
+    if (qstr) {
+        string temp = string(uri) + '?' + qstr;
+        setRequestURI(temp.c_str());
+    }
+    else {
+        setRequestURI(uri);
+    }
+
+    // See if this is the first time we've run.
+    if (!g_spoofKey.empty()) {
+        qstr = pblock_findval("Shib-Spoof-Check", rq->headers);
+        if (qstr && g_spoofKey == qstr)
+            m_firsttime = false;
+    }
+    if (!m_firsttime || rq->orig_rq)
+        log(SPDebug, "nsapi_shib function running more than once");
   }
+  ~ShibTargetNSAPI() { }
 
   const char* getScheme() const {
     return security_active ? "https" : "http";
@@ -227,40 +233,44 @@ 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);
   }
   string getContentType() const {
-    char* content_type = "";
-    request_header("content-type", &content_type, m_sn, m_rq);
-    return content_type;
+    char* content_type = NULL;
+    if (request_header("content-type", &content_type, m_sn, m_rq) != REQ_PROCEED)
+        return "";
+    return content_type ? content_type : "";
   }
   long getContentLength() const {
     if (m_gotBody)
         return m_body.length();
-    char* content_length="";
-    request_header("content-length", &content_length, m_sn, m_rq);
-    return atoi(content_length);
+    char* content_length=NULL;
+    if (request_header("content-length", &content_length, m_sn, m_rq) != REQ_PROCEED)
+        return 0;
+    return content_length ? atoi(content_length) : 0;
   }
   string getRemoteAddr() const {
-    return pblock_findval("ip", m_sn->client);
+    string ret = AbstractSPRequest::getRemoteAddr();
+    return ret.empty() ? pblock_findval("ip", m_sn->client) : ret;
   }
   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()));
   }
-  const char* getQueryString() const { 
+  const char* getQueryString() const {
     return pblock_findval("query", m_rq->reqpb);
   }
   const char* getRequestBody() const {
     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?
+    if (request_header("content-length", &content_length, m_sn, m_rq) != REQ_PROCEED || !content_length) {
+        m_gotBody = true;
+        return NULL;
+    }
+    else if (atoi(content_length) > 1024*1024) // 1MB?
       throw opensaml::SecurityPolicyException("Blocked request body exceeding 1M size limit.");
     else {
       char ch=IO_EOF+1;
@@ -280,7 +290,7 @@ public:
     }
   }
   void clearHeader(const char* rawname, const char* cginame) {
-    if (g_checkSpoofing) {
+    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;
@@ -301,8 +311,14 @@ public:
         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);
+    if (strcmp(rawname, "REMOTE_USER") == 0) {
+        param_free(pblock_remove("remote-user", m_rq->headers));
+        pblock_nvinsert("remote-user", g_unsetHeaderValue.c_str(), m_rq->headers);
+    }
+    else {
+        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));
@@ -328,11 +344,18 @@ public:
   }
   void setRemoteUser(const char* user) {
     pblock_nvinsert("auth-user", user, m_rq->vars);
+    param_free(pblock_remove("remote-user", m_rq->headers));
+    pblock_nvinsert("remote-user", user, m_rq->headers);
   }
   string getRemoteUser() const {
     const char* ru = pblock_findval("auth-user", m_rq->vars);
     return ru ? ru : "";
   }
+  void setContentType(const char* type) {
+      // iPlanet seems to have a case folding problem.
+      param_free(pblock_remove("content-type", m_rq->srvhdrs));
+      setResponseHeader("Content-Type", type);
+  }
   void setResponseHeader(const char* name, const char* value) {
     pblock_nvinsert(name, value, m_rq->srvhdrs);
   }
@@ -372,10 +395,6 @@ public:
       }
       return m_certs;
   }
-
-  pblock* m_pb;
-  ::Session* m_sn;
-  Request* m_rq;
 };
 
 /********************************************************************************/
@@ -400,13 +419,20 @@ extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, ::Session* sn, Request* rq)
 
     // Check user authentication
     pair<bool,long> res = stn.getServiceProvider().doAuthentication(stn);
+    // If directed, install a spoof key to recognize when we've already cleared headers.
+    if (!g_spoofKey.empty()) {
+      param_free(pblock_remove("Shib-Spoof-Check", rq->headers));
+      pblock_nvinsert("Shib-Spoof-Check", g_spoofKey.c_str(), rq->headers);
+    }
     if (res.first) return (int)res.second;
 
     // user authN was okay -- export the assertions now
     param_free(pblock_remove("auth-user",rq->vars));
+
     // This seems to be required in order to eventually set
     // the auth-user var.
     pblock_nvinsert("auth-type","shibboleth",rq->vars);
+
     res = stn.getServiceProvider().doExport(stn);
     if (res.first) return (int)res.second;
 
@@ -422,8 +448,9 @@ extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, ::Session* sn, Request* rq)
     return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an exception, see web server log for error.");
   }
   catch (...) {
+    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 uncaught exception.");
+        return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an unknown exception.");
     throw;
   }
 }
@@ -450,6 +477,7 @@ extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, ::Session* sn, Request* rq)
     return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an exception, see web server log for error.");
   }
   catch (...) {
+    log_error(LOG_FAILURE,FUNC,sn,rq,"unknown exception caught in Shibboleth handler");
     if (g_catchAll)
         return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an unknown exception.");
     throw;
@@ -465,7 +493,7 @@ public:
     Lockable* lock() { return m_mapper->lock(); }
     void unlock() { m_stKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
     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;
@@ -474,7 +502,7 @@ public:
     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;
     void getAll(map<string,const char*>& properties) const;
-    const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:2.0:native:sp:config") const;
+    const PropertySet* getPropertySet(const char* name, const char* ns=shibspconstants::ASCII_SHIB2SPCONFIG_NS) const;
     const xercesc::DOMElement* getElement() const;
 
 private: