Imported Upstream version 2.2.1+dfsg
[shibboleth/sp.git] / nsapi_shib / nsapi_shib.cpp
index ea38feb..960409d 100644 (file)
@@ -1,5 +1,5 @@
 /*
- *  Copyright 2001-2007 Internet2
+ *  Copyright 2001-2009 Internet2
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -31,6 +31,7 @@
 #ifdef WIN32
 # define _CRT_NONSTDC_NO_DEPRECATE 1
 # define _CRT_SECURE_NO_DEPRECATE 1
+# define _CRT_RAND_S
 #endif
 
 #include <shibsp/AbstractSPRequest.h>
@@ -75,13 +76,23 @@ using namespace std;
 namespace {
     SPConfig* g_Config=NULL;
     string g_ServerName;
-    string g_ServerScheme;
     string g_unsetHeaderValue;
+    string g_spoofKey;
     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);
+
+    void _my_invalid_parameter_handler(
+       const wchar_t * expression,
+       const wchar_t * function,
+       const wchar_t * file,
+       unsigned int line,
+       uintptr_t pReserved
+       ) {
+        return;
+    }
 }
 
 PluginManager<RequestMapper,string,const xercesc::DOMElement*>::Factory SunRequestMapFactory;
@@ -115,9 +126,6 @@ extern "C" NSAPI_PUBLIC int nsapi_shib_init(pblock* pb, ::Session* sn, Request*
             }
         }
     }
-    name=pblock_findval("server-scheme",pb);
-    if (name)
-        g_ServerScheme=name;
 
     log_error(LOG_INFORM,"nsapi_shib_init",sn,rq,"nsapi_shib loaded for host (%s)",g_ServerName.c_str());
 
@@ -139,7 +147,7 @@ extern "C" NSAPI_PUBLIC int nsapi_shib_init(pblock* pb, ::Session* sn, Request*
         return REQ_ABORTED;
     }
 
-    g_Config->RequestMapperManager.registerFactory(XML_REQUEST_MAPPER,&SunRequestMapFactory);
+    g_Config->RequestMapperManager.registerFactory(NATIVE_REQUEST_MAPPER,&SunRequestMapFactory);
 
     try {
         if (!g_Config->instantiate(pblock_findval("shib-config",pb), true))
@@ -156,15 +164,41 @@ 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;
         flag=props->getBool("catchAll");
         g_catchAll = flag.first && flag.second;
+
+        pair<bool,const char*> unsetValue=props->getString("unsetHeaderValue");
+        if (unsetValue.first)
+            g_unsetHeaderValue = unsetValue.second;
+        if (g_checkSpoofing) {
+            unsetValue=props->getString("spoofKey");
+            if (unsetValue.first)
+                g_spoofKey = unsetValue.second;
+#ifdef WIN32
+            else {
+                _invalid_parameter_handler old = _set_invalid_parameter_handler(_my_invalid_parameter_handler);
+                unsigned int randkey=0,randkey2=0,randkey3=0,randkey4=0;
+                if (rand_s(&randkey) == 0 && rand_s(&randkey2) == 0 && rand_s(&randkey3) == 0 && rand_s(&randkey4) == 0) {
+                    _set_invalid_parameter_handler(old);
+                    ostringstream keystr;
+                    keystr << randkey << randkey2 << randkey3 << randkey4;
+                    g_spoofKey = keystr.str();
+                }
+                else {
+                    _set_invalid_parameter_handler(old);
+                    pblock_nvinsert("error", "module failed to generate a random anti-spoofing key (if this is Windows 2000 set one manually)", pb);
+                    locker.assign(); // pops lock on SP config
+                    g_Config->term();
+                    g_Config=NULL;
+                    return REQ_ABORTED;
+                }
+            }
+#endif
+        }
     }
     return REQ_PROCEED;
 }
@@ -176,6 +210,8 @@ class ShibTargetNSAPI : public AbstractSPRequest
 {
   mutable string m_body;
   mutable bool m_gotBody,m_firsttime;
+  bool m_security_active;
+  int m_server_portnum;
   mutable vector<string> m_certs;
   set<string> m_allhttp;
 
@@ -185,10 +221,34 @@ public:
   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) {
+      : AbstractSPRequest(SHIBSP_LOGCAT".NSAPI"),
+        m_gotBody(false), m_firsttime(true), m_security_active(false), m_server_portnum(0), m_pb(pb), m_sn(sn), m_rq(rq) {
+
+    // To determine whether SSL is active or not, we're supposed to rely
+    // on the security_active macro. For iPlanet 4.x, this works.
+    // For Sun 7.x, it's useless and appears to be on or off based
+    // on whether ANY SSL support is enabled for a vhost. Sun 6.x is unknown.
+    // As a fix, there's a conf variable called $security that can be mapped
+    // into a function parameter: security_active="$security"
+    // We check for this parameter, and rely on the macro if it isn't set.
+    // This doubles as a scheme virtualizer for load balanced scenarios
+    // since you can set the parameter to 1 or 0 as needed.
+    const char* sa = pblock_findval("security_active", m_pb);
+    if (sa)
+        m_security_active = (*sa == '1');
+    else if (security_active)
+        m_security_active = true;
+    else
+        m_security_active = false;
+
+    // A similar issue exists for the port. server_portnum is no longer
+    // working on at least Sun 7.x, and returns the first listener's port
+    // rather than whatever port is actually used for the request. Nice job, Sun.
+    sa = pblock_findval("server_portnum", m_pb);
+    m_server_portnum = (sa && *sa) ? atoi(sa) : server_portnum;
 
-    const char* uri=pblock_findval("uri", rq->reqpb);
-    const char* qstr=pblock_findval("query", rq->reqpb);
+    const char* uri = pblock_findval("uri", rq->reqpb);
+    const char* qstr = pblock_findval("query", rq->reqpb);
 
     if (qstr) {
         string temp = string(uri) + '?' + qstr;
@@ -199,16 +259,18 @@ public:
     }
 
     // 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 (!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";
+    return m_security_active ? "https" : "http";
   }
   const char* getHostname() const {
 #ifdef vs_is_default_vs
@@ -223,25 +285,28 @@ public:
     return g_ServerName.c_str();
   }
   int getPort() const {
-    return server_portnum;
+    return m_server_portnum;
   }
   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);
@@ -255,7 +320,11 @@ 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?
+    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;
@@ -296,8 +365,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));
@@ -323,11 +398,27 @@ 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 setAuthType(const char* authtype) {
+    param_free(pblock_remove("auth-type", m_rq->vars));
+    if (authtype)
+        pblock_nvinsert("auth-type", authtype, m_rq->vars);
+  }
+  string getAuthType() const {
+    const char* at = pblock_findval("auth-type", m_rq->vars);
+    return at ? at : "";
+  }
+  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);
   }
@@ -391,13 +482,16 @@ 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;
 
@@ -442,6 +536,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;