Convert logging to log4shib via compile time switch.
[shibboleth/sp.git] / apache / mod_apache.cpp
index 2d77272..b7be829 100644 (file)
  * limitations under the License.
  */
 
-/*
- * mod_apache.cpp -- the core Apache Module code
- *
- * Created by: Derek Atkins <derek@ihtfp.com>
- *
- * $Id$
+/**
+ * mod_apache.cpp
+ * 
+ * Apache module implementation
  */
 
 #define SHIBSP_LITE
@@ -63,9 +61,9 @@
 #define CORE_PRIVATE
 #include <http_core.h>
 #include <http_log.h>
+#include <http_request.h>
 
 #ifndef SHIB_APACHE_13
-#include <http_request.h>
 #include <apr_buckets.h>
 #include <apr_strings.h>
 #include <apr_pools.h>
@@ -91,6 +89,7 @@ namespace {
     char* g_szSchemaDir = SHIBSP_SCHEMAS;
     SPConfig* g_Config = NULL;
     string g_unsetHeaderValue;
+    bool g_checkSpoofing = true;
     static const char* g_UserDataKey = "_shib_check_user_";
     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);
@@ -224,7 +223,6 @@ struct shib_request_config
     SH_AP_TABLE *env;        // environment vars
 #ifdef SHIB_DEFERRED_HEADERS
     SH_AP_TABLE *hdr_out;    // headers to browser
-    SH_AP_TABLE *hdr_err;    // err headers to browser
 #endif
 };
 
@@ -270,9 +268,11 @@ extern "C" const char* shib_ap_set_file_slot(cmd_parms* parms,
 
 class ShibTargetApache : public AbstractSPRequest
 {
+  bool m_handler;
   mutable string m_body;
   mutable bool m_gotBody;
   mutable vector<string> m_certs;
+  set<string> m_allhttp;
 
 public:
   request_rec* m_req;
@@ -280,7 +280,7 @@ public:
   shib_server_config* m_sc;
   shib_request_config* m_rc;
 
-  ShibTargetApache(request_rec* req) : m_gotBody(false) {
+  ShibTargetApache(request_rec* req, bool handler) : m_handler(handler), m_gotBody(false) {
     m_sc = (shib_server_config*)ap_get_module_config(req->server->module_config, &mod_shib);
     m_dc = (shib_dir_config*)ap_get_module_config(req->per_dir_config, &mod_shib);
     m_rc = (shib_request_config*)ap_get_module_config(req->request_config, &mod_shib);
@@ -387,14 +387,40 @@ public:
 #endif
     return m_body.c_str();
   }
-  void clearHeader(const char* name) {
+  void clearHeader(const char* rawname, const char* cginame) {
     if (m_dc->bUseEnvVars!=0) {
        // ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_clear_header: env\n");
-       if (m_rc && m_rc->env) ap_table_unset(m_rc->env, name);
+       if (m_rc && m_rc->env) ap_table_unset(m_rc->env, rawname);
     } else {
        // ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_clear_header: hdr\n");
-       ap_table_unset(m_req->headers_in, name);
-       ap_table_set(m_req->headers_in, name, g_unsetHeaderValue.c_str());
+        if (g_checkSpoofing && ap_is_initial_req(m_req)) {
+            if (m_allhttp.empty()) {
+                // First time, so populate set with "CGI" versions of client-supplied headers.
+#ifdef SHIB_APACHE_13
+                array_header *hdrs_arr = ap_table_elts(m_req->headers_in);
+                table_entry *hdrs = (table_entry *) hdrs_arr->elts;
+#else
+                const apr_array_header_t *hdrs_arr = apr_table_elts(m_req->headers_in);
+                const apr_table_entry_t *hdrs = (const apr_table_entry_t *) hdrs_arr->elts;
+#endif
+                for (int i = 0; i < hdrs_arr->nelts; ++i) {
+                    if (!hdrs[i].key)
+                        continue;
+                    string cgiversion("HTTP_");
+                    const char* pch = hdrs[i].key;
+                    while (*pch) {
+                        cgiversion += (isalnum(*pch) ? toupper(*pch) : '_');
+                        pch++;
+                    }
+                    m_allhttp.insert(cgiversion);
+                }
+            }
+
+            if (m_allhttp.count(cginame) > 0)
+                throw opensaml::SecurityPolicyException("Attempt to spoof header ($1) was detected.", params(1, rawname));
+        }
+        ap_table_unset(m_req->headers_in, rawname);
+        ap_table_set(m_req->headers_in, rawname, g_unsetHeaderValue.c_str());
     }
   }
   void setHeader(const char* name, const char* value) {
@@ -441,11 +467,11 @@ public:
    if (!m_rc)
       // this happens on subrequests
       m_rc = init_request_config(m_req);
-    ap_table_add(m_rc->hdr_err, name, value);
-    ap_table_add(m_rc->hdr_out, name, value);
-#else
-    ap_table_add(m_req->err_headers_out, name, value);
+    if (m_handler)
+        ap_table_add(m_rc->hdr_out, name, value);
+    else
 #endif
+    ap_table_add(m_req->err_headers_out, name, value);
   }
   long sendResponse(istream& in, long status) {
     ap_send_http_header(m_req);
@@ -489,14 +515,14 @@ extern "C" int shib_check_user(request_rec* r)
   if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
     return DECLINED;
     
-  ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_check_user(%d): ENTER\n", (int)getpid());
+  ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_check_user(%d): ENTER", (int)getpid());
 
   ostringstream threadid;
   threadid << "[" << getpid() << "] shib_check_user" << '\0';
   xmltooling::NDC ndc(threadid.str().c_str());
 
   try {
-    ShibTargetApache sta(r);
+    ShibTargetApache sta(r,false);
 
     // Check user authentication and export information, then set the handler bypass
     pair<bool,long> res = sta.getServiceProvider().doAuthentication(sta,true);
@@ -547,7 +573,7 @@ extern "C" int shib_handler(request_rec* r)
   ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler(%d): ENTER: %s", (int)getpid(), r->handler);
 
   try {
-    ShibTargetApache sta(r);
+    ShibTargetApache sta(r,true);
 
     pair<bool,long> res = sta.getServiceProvider().doHandler(sta);
     if (res.first) return res.second;
@@ -584,7 +610,7 @@ extern "C" int shib_auth_checker(request_rec* r)
   xmltooling::NDC ndc(threadid.str().c_str());
 
   try {
-    ShibTargetApache sta(r);
+    ShibTargetApache sta(r,false);
 
     pair<bool,long> res = sta.getServiceProvider().doAuthorization(sta);
     if (res.first) return res.second;
@@ -631,6 +657,7 @@ public:
     void unlock() { m_staKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
     Settings getSettings(const SPRequest& 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;
@@ -989,22 +1016,6 @@ bool htAccessControl::authorized(const SPRequest& request, const Session* sessio
     return false;
 }
 
-#ifndef SHIB_APACHE_13
-/*
- * shib_exit()
- *  Empty cleanup hook, Apache 2.x doesn't check NULL very well...
- */
-extern "C" apr_status_t shib_exit(void* data)
-{
-    if (g_Config) {
-        g_Config->term();
-        g_Config = NULL;
-    }
-    ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,0,NULL,"shib_exit() done");
-    return OK;
-}
-#endif
-
 
 // Initial look at a request - create the per-request structure
 static int shib_post_read(request_rec *r)
@@ -1015,7 +1026,6 @@ static int shib_post_read(request_rec *r)
 
 #ifdef SHIB_DEFERRED_HEADERS
     rc->hdr_out = ap_make_table(r->pool, 5);
-    rc->hdr_err = ap_make_table(r->pool, 5);
 #endif
     return DECLINED;
 }
@@ -1040,28 +1050,35 @@ extern "C" int shib_fixups(request_rec* r)
   return OK;
 }
 
+#ifdef SHIB_APACHE_13
 /*
  * shib_child_exit()
  *  Cleanup the (per-process) pool info.
  */
-#ifdef SHIB_APACHE_13
 extern "C" void shib_child_exit(server_rec* s, SH_AP_POOL* p)
 {
+    if (g_Config) {
+        ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit(%d) dealing with g_Config..", (int)getpid());
+        g_Config->term();
+        g_Config = NULL;
+        ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit() done");
+    }
+}
 #else
-extern "C" apr_status_t shib_child_exit(void* data)
+/*
+ * shib_exit()
+ *  Apache 2.x doesn't allow for per-child cleanup, causes CGI forks to hang.
+ */
+extern "C" apr_status_t shib_exit(void* data)
 {
-  server_rec* s = NULL;
-#endif
-
-    ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit(%d) dealing with g_Config..", (int)getpid());
-    g_Config->term();
-    g_Config = NULL;
-    ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit() done");
-
-#ifndef SHIB_APACHE_13
+    if (g_Config) {
+        g_Config->term();
+        g_Config = NULL;
+    }
+    ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,0,NULL,"shib_exit() done");
     return OK;
-#endif
 }
+#endif
 
 /* 
  * shire_child_init()
@@ -1122,10 +1139,13 @@ extern "C" void shib_child_init(apr_pool_t* p, server_rec* s)
         pair<bool,const char*> unsetValue=props->getString("unsetHeaderValue");
         if (unsetValue.first)
             g_unsetHeaderValue = unsetValue.second;
+        pair<bool,bool> checkSpoofing=props->getBool("checkSpoofing");
+        if (checkSpoofing.first && !checkSpoofing.second)
+            g_checkSpoofing = false;
     }
 
     // Set the cleanup handler
-    apr_pool_cleanup_register(p, NULL, &shib_exit, &shib_child_exit);
+    apr_pool_cleanup_register(p, NULL, &shib_exit, apr_pool_cleanup_null);
 
     ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() done");
 }
@@ -1173,10 +1193,10 @@ static apr_status_t do_error_filter(ap_filter_t *f, apr_bucket_brigade *in)
     shib_request_config *rc = (shib_request_config*) ap_get_module_config(r->request_config, &mod_shib);
 
     if (rc) {
-        ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_err_filter: merging %d headers", apr_table_elts(rc->hdr_err)->nelts);
-        apr_table_do(_table_add,r->err_headers_out, rc->hdr_err,NULL);
+        ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_err_filter: merging %d headers", apr_table_elts(rc->hdr_out)->nelts);
+        apr_table_do(_table_add,r->err_headers_out, rc->hdr_out,NULL);
         // can't use overlap call because it will collapse Set-Cookie headers
-        //apr_table_overlap(r->err_headers_out, rc->hdr_err, APR_OVERLAP_TABLES_MERGE);
+        //apr_table_overlap(r->err_headers_out, rc->hdr_out, APR_OVERLAP_TABLES_MERGE);
     }
 
     /* remove ourselves from the filter chain */
@@ -1326,8 +1346,8 @@ static command_rec shib_cmds[] = {
         (void *) offsetof (shib_dir_config, szRedirectToSSL),
         OR_AUTHCFG, "Redirect non-SSL requests to designated port"),
   AP_INIT_TAKE1("AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
-               (void *) offsetof (shib_dir_config, szAuthGrpFile),
-               OR_AUTHCFG, "Text file containing group names and member user IDs"),
+        (void *) offsetof (shib_dir_config, szAuthGrpFile),
+        OR_AUTHCFG, "Text file containing group names and member user IDs"),
   AP_INIT_FLAG("ShibRequireAll", (config_fn_t)ap_set_flag_slot,
         (void *) offsetof (shib_dir_config, bRequireAll),
         OR_AUTHCFG, "All require directives must match"),
@@ -1349,7 +1369,7 @@ module AP_MODULE_DECLARE_DATA mod_shib = {
 };
 
 #else
-#error "undefined APACHE version"
+#error "unsupported Apache version"
 #endif
 
 }