Add Handler feature for config.
[shibboleth/sp.git] / apache / mod_apache.cpp
index aac8ac4..b7a00d0 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
+
 #ifdef SOLARIS2
 #undef _XOPEN_SOURCE    // causes gethostname conflict in unistd.h
 #endif
@@ -39,7 +39,7 @@
 #include <shibsp/ServiceProvider.h>
 #include <shibsp/SessionCache.h>
 #include <shibsp/attribute/Attribute.h>
-
+#include <xercesc/util/XMLUniDefs.hpp>
 #include <xercesc/util/regx/RegularExpression.hpp>
 #include <xmltooling/XMLToolingConfig.h>
 #include <xmltooling/util/NDC.h>
 #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>
 #endif
@@ -88,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);
@@ -139,9 +141,12 @@ extern "C" void* merge_shib_server_config (SH_AP_POOL* p, void* base, void* sub)
 // per-dir module configuration structure
 struct shib_dir_config
 {
+    SH_AP_TABLE* tSettings; // generic table of extensible settings
+
     // RM Configuration
     char* szAuthGrpFile;    // Auth GroupFile name
-    int bRequireAll;        // all require directives must match, otherwise OR logic
+    int bRequireAll;        // all "known" require directives must match, otherwise OR logic
+    int bAuthoritative;     // allow htaccess plugin to DECLINE when authz fails
 
     // Content Configuration
     char* szApplicationId;  // Shib applicationId value
@@ -151,23 +156,27 @@ struct shib_dir_config
     int bBasicHijack;       // activate for AuthType Basic?
     int bRequireSession;    // require a session?
     int bExportAssertion;   // export SAML assertion to the environment?
-    int bUseEnvVars;        // use environment instead of headers?
+    int bUseEnvVars;        // use environment?
+    int bUseHeaders;        // use headers?
 };
 
 // creates per-directory config structure
 extern "C" void* create_shib_dir_config (SH_AP_POOL* p, char* d)
 {
     shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
+    dc->tSettings = NULL;
+    dc->szAuthGrpFile = NULL;
+    dc->bRequireAll = -1;
+    dc->bAuthoritative = -1;
+    dc->szApplicationId = NULL;
+    dc->szRequireWith = NULL;
+    dc->szRedirectToSSL = NULL;
     dc->bOff = -1;
     dc->bBasicHijack = -1;
     dc->bRequireSession = -1;
     dc->bExportAssertion = -1;
-    dc->bRequireAll = -1;
-    dc->szRedirectToSSL = NULL;
-    dc->szAuthGrpFile = NULL;
-    dc->szApplicationId = NULL;
-    dc->szRequireWith = NULL;
     dc->bUseEnvVars = -1;
+    dc->bUseHeaders = -1;
     return dc;
 }
 
@@ -178,6 +187,17 @@ extern "C" void* merge_shib_dir_config (SH_AP_POOL* p, void* base, void* sub)
     shib_dir_config* parent=(shib_dir_config*)base;
     shib_dir_config* child=(shib_dir_config*)sub;
 
+    // The child supersedes any matching table settings in the parent.
+    dc->tSettings = NULL;
+    if (parent->tSettings)
+        dc->tSettings = ap_copy_table(p, parent->tSettings);
+    if (child->tSettings) {
+        if (dc->tSettings)
+            ap_overlap_tables(dc->tSettings, child->tSettings, AP_OVERLAP_TABLES_SET);
+        else
+            dc->tSettings = ap_copy_table(p, child->tSettings);
+    }
+
     if (child->szAuthGrpFile)
         dc->szAuthGrpFile=ap_pstrdup(p,child->szAuthGrpFile);
     else if (parent->szAuthGrpFile)
@@ -211,7 +231,9 @@ extern "C" void* merge_shib_dir_config (SH_AP_POOL* p, void* base, void* sub)
     dc->bRequireSession=((child->bRequireSession==-1) ? parent->bRequireSession : child->bRequireSession);
     dc->bExportAssertion=((child->bExportAssertion==-1) ? parent->bExportAssertion : child->bExportAssertion);
     dc->bRequireAll=((child->bRequireAll==-1) ? parent->bRequireAll : child->bRequireAll);
+    dc->bAuthoritative=((child->bAuthoritative==-1) ? parent->bAuthoritative : child->bAuthoritative);
     dc->bUseEnvVars=((child->bUseEnvVars==-1) ? parent->bUseEnvVars : child->bUseEnvVars);
+    dc->bUseHeaders=((child->bUseHeaders==-1) ? parent->bUseHeaders : child->bUseHeaders);
     return dc;
 }
 
@@ -221,7 +243,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
 };
 
@@ -262,14 +283,24 @@ extern "C" const char* shib_ap_set_file_slot(cmd_parms* parms,
   return DECLINE_CMD;
 }
 
+extern "C" const char* shib_table_set(cmd_parms* parms, shib_dir_config* dc, const char* arg1, const char* arg2)
+{
+    if (!dc->tSettings)
+        dc->tSettings = ap_make_table(parms->pool, 4);
+    ap_table_set(dc->tSettings, arg1, arg2);
+    return NULL;
+}
+
 /********************************************************************************/
 // Apache ShibTarget subclass(es) here.
 
 class ShibTargetApache : public AbstractSPRequest
 {
+  bool m_handler;
   mutable string m_body;
   mutable bool m_gotBody;
-  vector<string> m_certs;
+  mutable vector<string> m_certs;
+  set<string> m_allhttp;
 
 public:
   request_rec* m_req;
@@ -277,7 +308,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);
@@ -326,6 +357,7 @@ public:
   const char* getRequestBody() const {
     if (m_gotBody || m_req->method_number==M_GET)
         return m_body.c_str();
+#ifdef SHIB_APACHE_13
     // Read the posted data
     if (ap_setup_client_block(m_req, REQUEST_CHUNKED_DECHUNK) != OK) {
         m_gotBody=true;
@@ -340,48 +372,103 @@ public:
     if (m_req->remaining > 1024*1024)
         throw opensaml::SecurityPolicyException("Blocked request body larger than 1M size limit.");
     m_gotBody=true;
+    int len;
     char buff[HUGE_STRING_LEN];
     ap_hard_timeout("[mod_shib] getRequestBody", m_req);
-    memset(buff, 0, sizeof(buff));
-    while (ap_get_client_block(m_req, buff, sizeof(buff)-1) > 0) {
+    while ((len=ap_get_client_block(m_req, buff, sizeof(buff))) > 0) {
       ap_reset_timeout(m_req);
-      m_body += buff;
-      memset(buff, 0, sizeof(buff));
+      m_body.append(buff, len);
     }
     ap_kill_timeout(m_req);
+#else
+    const char *data;
+    apr_size_t len;
+    int seen_eos = 0;
+    apr_bucket_brigade* bb = apr_brigade_create(m_req->pool, m_req->connection->bucket_alloc);
+    do {
+        apr_bucket *bucket;
+        apr_status_t rv = ap_get_brigade(m_req->input_filters, bb, AP_MODE_READBYTES, APR_BLOCK_READ, HUGE_STRING_LEN);
+        if (rv != APR_SUCCESS) {
+            log(SPError, "Apache function (ap_get_brigade) failed while reading request body.");
+            break;
+        }
+
+        for (bucket = APR_BRIGADE_FIRST(bb); bucket != APR_BRIGADE_SENTINEL(bb); bucket = APR_BUCKET_NEXT(bucket)) {
+            if (APR_BUCKET_IS_EOS(bucket)) {
+                seen_eos = 1;
+                break;
+            }
+
+            /* We can't do much with this. */
+            if (APR_BUCKET_IS_FLUSH(bucket))
+                continue;
+
+            /* read */
+            apr_bucket_read(bucket, &data, &len, APR_BLOCK_READ);
+            if (len > 0)
+                m_body.append(data, len);
+        }
+        apr_brigade_cleanup(bb);
+    } while (!seen_eos);
+    apr_brigade_destroy(bb);
+    m_gotBody=true;
+#endif
     return m_body.c_str();
   }
-  void clearHeader(const char* name) {
-    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);
-    } else {
+  void clearHeader(const char* rawname, const char* cginame) {
+    if (m_dc->bUseHeaders == 1) {
        // 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) {
-    if (m_dc->bUseEnvVars!=0) {
+    if (m_dc->bUseEnvVars != 0) {
        if (!m_rc) {
           // this happens on subrequests
           // ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_setheader: no_m_rc\n");
           m_rc = init_request_config(m_req);
        }
-       if (!m_rc->env) m_rc->env = ap_make_table(m_req->pool, 10);
+       if (!m_rc->env)
+           m_rc->env = ap_make_table(m_req->pool, 10);
        // ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_set_env: %s=%s\n", name, value?value:"Null");
-       ap_table_set(m_rc->env, name, value?value:"");
+       ap_table_set(m_rc->env, name, value ? value : "");
     }
-    else {
+    if (m_dc->bUseHeaders == 1)
        ap_table_set(m_req->headers_in, name, value);
-    }
   }
   string getHeader(const char* name) const {
     const char* hdr = ap_table_get(m_req->headers_in, name);
     return string(hdr ? hdr : "");
   }
   string getSecureHeader(const char* name) const {
-    if (m_dc->bUseEnvVars!=0) {
+    if (m_dc->bUseEnvVars != 0) {
        const char *hdr;
        if (m_rc && m_rc->env)
            hdr = ap_table_get(m_rc->env, name);
@@ -405,11 +492,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);
@@ -418,13 +505,26 @@ public:
         in.read(buf,1024);
         ap_rwrite(buf,in.gcount(),m_req);
     }
-    return ((status==XMLTOOLING_HTTP_STATUS_OK) ? DONE : status);
+    if (status!=XMLTOOLING_HTTP_STATUS_OK)
+        m_req->status = status;
+    return DONE;
   }
   long sendRedirect(const char* url) {
     ap_table_set(m_req->headers_out, "Location", url);
     return REDIRECT;
   }
   const vector<string>& getClientCertificates() const {
+      if (m_certs.empty()) {
+          const char* cert = ap_table_get(m_req->subprocess_env, "SSL_CLIENT_CERT");
+          if (cert)
+              m_certs.push_back(cert);
+          int i = 0;
+          do {
+              cert = ap_table_get(m_req->subprocess_env, ap_psprintf(m_req->pool, "SSL_CLIENT_CERT_CHAIN_%d", i++));
+              if (cert)
+                  m_certs.push_back(cert);
+          } while (cert);
+      }
       return m_certs;
   }
   long returnDecline(void) { return DECLINED; }
@@ -440,14 +540,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);
@@ -498,7 +598,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;
@@ -535,13 +635,14 @@ 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;
 
-    // We're all okay.
-    return OK;
+    // The SP method should always return true, so if we get this far, something unusual happened.
+    // Just let Apache (or some other module) decide what to do.
+    return DECLINED;
   }
   catch (exception& e) {
     ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an exception: %s", e.what());
@@ -563,7 +664,7 @@ public:
     ~htAccessControl() {}
     Lockable* lock() {return this;}
     void unlock() {}
-    bool authorized(const SPRequest& request, const Session* session) const;
+    aclresult_t authorized(const SPRequest& request, const Session* session) const;
 private:
     bool checkAttribute(const SPRequest& request, const Attribute* attr, const char* toMatch, RegularExpression* re) const;
 };
@@ -582,6 +683,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;
@@ -625,10 +727,15 @@ pair<bool,bool> ApacheRequestMapper::getBool(const char* name, const char* ns) c
     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
     if (sta && !ns) {
         // Override Apache-settable boolean properties.
-        if (name && !strcmp(name,"requireSession") && sta->m_dc->bRequireSession==1)
-            return make_pair(true,true);
-        else if (name && !strcmp(name,"exportAssertion") && sta->m_dc->bExportAssertion==1)
-            return make_pair(true,true);
+        if (name && !strcmp(name,"requireSession") && sta->m_dc->bRequireSession != -1)
+            return make_pair(true, sta->m_dc->bRequireSession==1);
+        else if (name && !strcmp(name,"exportAssertion") && sta->m_dc->bExportAssertion != -1)
+            return make_pair(true, sta->m_dc->bExportAssertion==1);
+        else if (sta->m_dc->tSettings) {
+            const char* prop = ap_table_get(sta->m_dc->tSettings, name);
+            if (prop)
+                return make_pair(true, !strcmp(prop, "true") || !strcmp(prop, "1") || !strcmp(prop, "On"));
+        }
     }
     return s ? s->getBool(name,ns) : make_pair(false,false);
 }
@@ -654,6 +761,11 @@ pair<bool,const char*> ApacheRequestMapper::getString(const char* name, const ch
             return pair<bool,const char*>(true,sta->m_dc->szRequireWith);
         else if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
             return pair<bool,const char*>(true,sta->m_dc->szRedirectToSSL);
+        else if (sta->m_dc->tSettings) {
+            const char* prop = ap_table_get(sta->m_dc->tSettings, name);
+            if (prop)
+                return make_pair(true, prop);
+        }
     }
     return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
 }
@@ -671,7 +783,12 @@ pair<bool,unsigned int> ApacheRequestMapper::getUnsignedInt(const char* name, co
     if (sta && !ns) {
         // Override Apache-settable int properties.
         if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
-            return pair<bool,unsigned int>(true,strtol(sta->m_dc->szRedirectToSSL,NULL,10));
+            return pair<bool,unsigned int>(true, strtol(sta->m_dc->szRedirectToSSL, NULL, 10));
+        else if (sta->m_dc->tSettings) {
+            const char* prop = ap_table_get(sta->m_dc->tSettings, name);
+            if (prop)
+                return make_pair(true, strtol(prop, NULL, 10));
+        }
     }
     return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
 }
@@ -684,6 +801,11 @@ pair<bool,int> ApacheRequestMapper::getInt(const char* name, const char* ns) con
         // Override Apache-settable int properties.
         if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
             return pair<bool,int>(true,atoi(sta->m_dc->szRedirectToSSL));
+        else if (sta->m_dc->tSettings) {
+            const char* prop = ap_table_get(sta->m_dc->tSettings, name);
+            if (prop)
+                return make_pair(true, atoi(prop));
+        }
     }
     return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
 }
@@ -754,7 +876,7 @@ bool htAccessControl::checkAttribute(const SPRequest& request, const Attribute*
     const vector<string>& vals = attr->getSerializedValues();
     for (vector<string>::const_iterator v=vals.begin(); v!=vals.end(); ++v) {
         if (re) {
-            auto_ptr<XMLCh> trans(fromUTF8(v->c_str()));
+            auto_arrayptr<XMLCh> trans(fromUTF8(v->c_str()));
             if (re->matches(trans.get())) {
                 request.log(SPRequest::SPDebug,
                     string("htAccessControl plugin expecting regexp ") + toMatch + ", got " + *v + ": authorization granted"
@@ -777,7 +899,7 @@ bool htAccessControl::checkAttribute(const SPRequest& request, const Attribute*
     return false;
 }
 
-bool htAccessControl::authorized(const SPRequest& request, const Session* session) const
+AccessControl::aclresult_t htAccessControl::authorized(const SPRequest& request, const Session* session) const
 {
     // Make sure the object is our type.
     const ShibTargetApache* sta=dynamic_cast<const ShibTargetApache*>(&request);
@@ -792,7 +914,7 @@ bool htAccessControl::authorized(const SPRequest& request, const Session* sessio
     
     const array_header* reqs_arr=ap_requires(sta->m_req);
     if (!reqs_arr)
-        return true;
+        return shib_acl_indeterminate;  // should never happen
 
     require_line* reqs=(require_line*)reqs_arr->elts;
     
@@ -803,7 +925,7 @@ bool htAccessControl::authorized(const SPRequest& request, const Session* sessio
 
 #define SHIB_AP_CHECK_IS_OK {           \
      if (sta->m_dc->bRequireAll < 1)    \
-         return true;                   \
+         return shib_acl_true;          \
      auth_OK[x] = true;                 \
      continue;                          \
 }
@@ -828,8 +950,9 @@ bool htAccessControl::authorized(const SPRequest& request, const Session* sessio
                 request.log(SPRequest::SPDebug,"htAccessControl plugin accepting valid-user based on active session");
                 SHIB_AP_CHECK_IS_OK;
             }
-            else
+            else {
                 request.log(SPRequest::SPError,"htAccessControl plugin rejecting access for valid-user rule, no session is active");
+            }
         }
         else if (!strcmp(w,"user") && !remote_user.empty()) {
             bool regexp=false;
@@ -843,9 +966,9 @@ bool htAccessControl::authorized(const SPRequest& request, const Session* sessio
                 if (regexp) {
                     try {
                         // To do regex matching, we have to convert from UTF-8.
-                        auto_ptr<XMLCh> trans(fromUTF8(w));
+                        auto_arrayptr<XMLCh> trans(fromUTF8(w));
                         RegularExpression re(trans.get());
-                        auto_ptr<XMLCh> trans2(fromUTF8(remote_user.c_str()));
+                        auto_arrayptr<XMLCh> trans2(fromUTF8(remote_user.c_str()));
                         if (re.matches(trans2.get())) {
                             request.log(SPRequest::SPDebug, string("htAccessControl plugin accepting user (") + w + ")");
                             SHIB_AP_CHECK_IS_OK;
@@ -888,8 +1011,8 @@ bool htAccessControl::authorized(const SPRequest& request, const Session* sessio
             }
             
             // Find the attribute(s) matching the require rule.
-            pair<multimap<string,Attribute*>::const_iterator,multimap<string,Attribute*>::const_iterator> attrs =
-                session->getAttributes().equal_range(w);
+            pair<multimap<string,const Attribute*>::const_iterator,multimap<string,const Attribute*>::const_iterator> attrs =
+                session->getIndexedAttributes().equal_range(w);
             if (attrs.first == attrs.second) {
                 request.log(SPRequest::SPWarn, string("htAccessControl rule requires attribute (") + w + "), not found in session");
                 continue;
@@ -908,7 +1031,7 @@ bool htAccessControl::authorized(const SPRequest& request, const Session* sessio
                     auto_ptr<RegularExpression> re;
                     if (regexp) {
                         delete re.release();
-                        auto_ptr<XMLCh> trans(fromUTF8(w));
+                        auto_arrayptr<XMLCh> trans(fromUTF8(w));
                         auto_ptr<xercesc::RegularExpression> temp(new xercesc::RegularExpression(trans.get()));
                         re=temp;
                     }
@@ -929,44 +1052,27 @@ bool htAccessControl::authorized(const SPRequest& request, const Session* sessio
         }
     }
 
-    // check if all require directives are true
+    // If we get here, we either "failed" or we're in require all mode.
     bool auth_all_OK = true;
     for (int i= 0; i<reqs_arr->nelts; i++) {
         auth_all_OK &= auth_OK[i];
     }
     if (auth_all_OK || !method_restricted)
-        return true;
+        return shib_acl_true;
 
-    return false;
+    return (sta->m_dc->bAuthoritative != 0) ? shib_acl_false : shib_acl_indeterminate;
 }
 
-#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)
 {
     shib_request_config* rc = init_request_config(r);
 
-    ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_post_read: E=%s", rc->env?"env":"hdr");
+    ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_post_read");
 
 #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;
 }
@@ -991,28 +1097,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()
@@ -1040,7 +1153,8 @@ extern "C" void shib_child_init(apr_pool_t* p, server_rec* s)
         SPConfig::Caching |
         SPConfig::RequestMapping |
         SPConfig::InProcess |
-        SPConfig::Logging
+        SPConfig::Logging |
+        SPConfig::Handlers
         );
     if (!g_Config->init(g_szSchemaDir)) {
         ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize libraries");
@@ -1073,10 +1187,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");
 }
@@ -1124,10 +1241,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 */
@@ -1156,6 +1273,9 @@ static command_rec shire_cmds[] = {
    (void *) XtOffsetOf (shib_server_config, szScheme),
    RSRC_CONF, TAKE1, "URL scheme to force into generated URLs for a vhost"},
    
+  {"ShibRequestSetting", (config_fn_t)shib_table_set, NULL,
+   OR_AUTHCFG, TAKE2, "Set arbitrary Shibboleth request property for content"},
+
   {"ShibDisable", (config_fn_t)ap_set_flag_slot,
    (void *) XtOffsetOf (shib_dir_config, bOff),
    OR_AUTHCFG, FLAG, "Disable all Shib module activity here to save processing effort"},
@@ -1183,9 +1303,15 @@ static command_rec shire_cmds[] = {
   {"ShibRequireAll", (config_fn_t)ap_set_flag_slot,
    (void *) XtOffsetOf (shib_dir_config, bRequireAll),
    OR_AUTHCFG, FLAG, "All require directives must match"},
+  {"AuthzShibAuthoritative", (config_fn_t)ap_set_flag_slot,
+   (void *) XtOffsetOf (shib_dir_config, bAuthoritative),
+   OR_AUTHCFG, FLAG, "Allow failed mod_shib htaccess authorization to fall through to other modules"},
   {"ShibUseEnvironment", (config_fn_t)ap_set_flag_slot,
    (void *) XtOffsetOf (shib_dir_config, bUseEnvVars),
-   OR_AUTHCFG, FLAG, "Export data in environment instead of headers (default)"},
+   OR_AUTHCFG, FLAG, "Export attributes using environment variables (default)"},
+  {"ShibUseHeaders", (config_fn_t)ap_set_flag_slot,
+   (void *) XtOffsetOf (shib_dir_config, bUseHeaders),
+   OR_AUTHCFG, FLAG, "Export attributes using custom HTTP headers"},
 
   {NULL}
 };
@@ -1210,12 +1336,12 @@ module MODULE_VAR_EXPORT mod_shib = {
     shib_auth_checker,         /* check auth */
     NULL,                      /* check access */
     NULL,                      /* type_checker */
-    shib_fixups,               /* fixups */
+    NULL,//shib_fixups,                /* fixups */
     NULL,                      /* logger */
     NULL,                      /* header parser */
     shib_child_init,           /* child_init */
     shib_child_exit,           /* child_exit */
-    shib_post_read             /* post read-request */
+    NULL//shib_post_read               /* post read-request */
 };
 
 #elif defined(SHIB_APACHE_20) || defined(SHIB_APACHE_22)
@@ -1240,53 +1366,58 @@ extern "C" void shib_register_hooks (apr_pool_t *p)
 
 extern "C" {
 static command_rec shib_cmds[] = {
-  AP_INIT_TAKE1("ShibConfig",
-               (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
-               RSRC_CONF, "Path to shibboleth.xml config file"),
-  AP_INIT_TAKE1("ShibCatalogs",
-     (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
-      RSRC_CONF, "Paths of XML schema catalogs"),
-  AP_INIT_TAKE1("ShibSchemaDir",
-     (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
-      RSRC_CONF, "Paths of XML schema catalogs (deprecated in favor of ShibCatalogs)"),
-
-  AP_INIT_TAKE1("ShibURLScheme",
-     (config_fn_t)shib_set_server_string_slot,
-     (void *) offsetof (shib_server_config, szScheme),
-      RSRC_CONF, "URL scheme to force into generated URLs for a vhost"),
-
-  AP_INIT_FLAG("ShibDisable", (config_fn_t)ap_set_flag_slot,
+    AP_INIT_TAKE1("ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
+        RSRC_CONF, "Path to shibboleth.xml config file"),
+    AP_INIT_TAKE1("ShibCatalogs", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
+        RSRC_CONF, "Paths of XML schema catalogs"),
+    AP_INIT_TAKE1("ShibSchemaDir", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
+        RSRC_CONF, "Paths of XML schema catalogs (deprecated in favor of ShibCatalogs)"),
+
+    AP_INIT_TAKE1("ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
+        (void *) offsetof (shib_server_config, szScheme),
+        RSRC_CONF, "URL scheme to force into generated URLs for a vhost"),
+
+    AP_INIT_TAKE2("ShibRequestSetting", (config_fn_t)shib_table_set, NULL,
+        OR_AUTHCFG, "Set arbitrary Shibboleth request property for content"),
+
+    AP_INIT_FLAG("ShibDisable", (config_fn_t)ap_set_flag_slot,
         (void *) offsetof (shib_dir_config, bOff),
         OR_AUTHCFG, "Disable all Shib module activity here to save processing effort"),
-  AP_INIT_TAKE1("ShibApplicationId", (config_fn_t)ap_set_string_slot,
+    AP_INIT_TAKE1("ShibApplicationId", (config_fn_t)ap_set_string_slot,
         (void *) offsetof (shib_dir_config, szApplicationId),
         OR_AUTHCFG, "Set Shibboleth applicationId property for content"),
-  AP_INIT_FLAG("ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
+    AP_INIT_FLAG("ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
         (void *) offsetof (shib_dir_config, bBasicHijack),
         OR_AUTHCFG, "Respond to AuthType Basic and convert to shibboleth"),
-  AP_INIT_FLAG("ShibRequireSession", (config_fn_t)ap_set_flag_slot,
+    AP_INIT_FLAG("ShibRequireSession", (config_fn_t)ap_set_flag_slot,
         (void *) offsetof (shib_dir_config, bRequireSession),
         OR_AUTHCFG, "Initiates a new session if one does not exist"),
-  AP_INIT_TAKE1("ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
+    AP_INIT_TAKE1("ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
         (void *) offsetof (shib_dir_config, szRequireWith),
         OR_AUTHCFG, "Initiates a new session if one does not exist using a specific SessionInitiator"),
-  AP_INIT_FLAG("ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
+    AP_INIT_FLAG("ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
         (void *) offsetof (shib_dir_config, bExportAssertion),
         OR_AUTHCFG, "Export SAML attribute assertion(s) to Shib-Attributes header"),
-  AP_INIT_TAKE1("ShibRedirectToSSL", (config_fn_t)ap_set_string_slot,
+    AP_INIT_TAKE1("ShibRedirectToSSL", (config_fn_t)ap_set_string_slot,
         (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"),
-  AP_INIT_FLAG("ShibRequireAll", (config_fn_t)ap_set_flag_slot,
+    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"),
+    AP_INIT_FLAG("ShibRequireAll", (config_fn_t)ap_set_flag_slot,
         (void *) offsetof (shib_dir_config, bRequireAll),
         OR_AUTHCFG, "All require directives must match"),
-  AP_INIT_FLAG("ShibUseEnvironment", (config_fn_t)ap_set_flag_slot,
+    AP_INIT_FLAG("AuthzShibAuthoritative", (config_fn_t)ap_set_flag_slot,
+        (void *) offsetof (shib_dir_config, bAuthoritative),
+        OR_AUTHCFG, "Allow failed mod_shib htaccess authorization to fall through to other modules"),
+    AP_INIT_FLAG("ShibUseEnvironment", (config_fn_t)ap_set_flag_slot,
         (void *) offsetof (shib_dir_config, bUseEnvVars),
-        OR_AUTHCFG, "Export data in environment instead of headers (default)"),
+        OR_AUTHCFG, "Export attributes using environment variables (default)"),
+    AP_INIT_FLAG("ShibUseHeaders", (config_fn_t)ap_set_flag_slot,
+        (void *) offsetof (shib_dir_config, bUseHeaders),
+        OR_AUTHCFG, "Export attributes using custom HTTP headers"),
 
-  {NULL}
+    {NULL}
 };
 
 module AP_MODULE_DECLARE_DATA mod_shib = {
@@ -1300,7 +1431,7 @@ module AP_MODULE_DECLARE_DATA mod_shib = {
 };
 
 #else
-#error "undefined APACHE version"
+#error "unsupported Apache version"
 #endif
 
 }