Turn redirect expiration on by default.
[shibboleth/cpp-sp.git] / apache / mod_apache.cpp
index ef42915..8f04472 100644 (file)
@@ -1,23 +1,27 @@
-/*
- *  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
+/**
+ * Licensed to the University Corporation for Advanced Internet
+ * Development, Inc. (UCAID) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for
+ * additional information regarding copyright ownership.
+ *
+ * UCAID licenses this file to you 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
  *
- *     http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
+ * either express or implied. See the License for the specific
+ * language governing permissions and limitations under the License.
  */
 
 /**
  * mod_apache.cpp
- * 
- * Apache module implementation
+ *
+ * Apache module implementation.
  */
 
 #define SHIBSP_LITE
 # define _CRT_SECURE_NO_DEPRECATE 1
 #endif
 
+#include <shibsp/exceptions.h>
 #include <shibsp/AbstractSPRequest.h>
 #include <shibsp/AccessControl.h>
-#include <shibsp/exceptions.h>
+#include <shibsp/GSSRequest.h>
 #include <shibsp/RequestMapper.h>
 #include <shibsp/SPConfig.h>
 #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>
+#include <xmltooling/util/ParserPool.h>
 #include <xmltooling/util/Threads.h>
 #include <xmltooling/util/XMLConstants.h>
 #include <xmltooling/util/XMLHelper.h>
 #include <apr_pools.h>
 #endif
 
+#include <set>
+#include <memory>
 #include <fstream>
 #include <sstream>
+#include <stdexcept>
 
+#include <cstddef>
 #ifdef HAVE_UNISTD_H
 #include <unistd.h>            // for getpid()
 #endif
@@ -85,14 +96,17 @@ using xercesc::XMLException;
 extern "C" module MODULE_VAR_EXPORT mod_shib;
 
 namespace {
-    char* g_szSHIBConfig = SHIBSP_CONFIG;
-    char* g_szSchemaDir = SHIBSP_SCHEMAS;
-    SPConfig* g_Config = NULL;
-    string g_unsetHeaderValue;
+    char* g_szSHIBConfig = nullptr;
+    char* g_szSchemaDir = nullptr;
+    char* g_szPrefix = nullptr;
+    SPConfig* g_Config = nullptr;
+    string g_unsetHeaderValue,g_spoofKey;
     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);
+    bool g_catchAll = false;
+#ifndef SHIB_APACHE_13
+    char* g_szGSSContextKey = "mod_auth_gssapi:gss_ctx";
+#endif
+    static const char* g_UserDataKey = "urn:mace:shibboleth:Apache:shib_check_user";
 }
 
 /* Apache 2.2.x headers must be accumulated and set in the output filter.
@@ -117,7 +131,7 @@ struct shib_server_config
 extern "C" void* create_shib_server_config(SH_AP_POOL* p, server_rec* s)
 {
     shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
-    sc->szScheme = NULL;
+    sc->szScheme = nullptr;
     return sc;
 }
 
@@ -133,7 +147,7 @@ extern "C" void* merge_shib_server_config (SH_AP_POOL* p, void* base, void* sub)
     else if (parent->szScheme)
         sc->szScheme=ap_pstrdup(p,parent->szScheme);
     else
-        sc->szScheme=NULL;
+        sc->szScheme=nullptr;
 
     return sc;
 }
@@ -152,31 +166,35 @@ struct shib_dir_config
     char* szApplicationId;  // Shib applicationId value
     char* szRequireWith;    // require a session using a specific initiator?
     char* szRedirectToSSL;  // redirect non-SSL requests to SSL port
+       char* szAccessControl;  // path to "external" AccessControl plugin file
     int bOff;               // flat-out disable all Shib processing
     int bBasicHijack;       // activate for AuthType Basic?
     int bRequireSession;    // require a session?
     int bExportAssertion;   // export SAML assertion to the environment?
     int bUseEnvVars;        // use environment?
     int bUseHeaders;        // use headers?
+    int bExpireRedirects;   // expire redirects?
 };
 
 // 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->tSettings = nullptr;
+    dc->szAuthGrpFile = nullptr;
     dc->bRequireAll = -1;
     dc->bAuthoritative = -1;
-    dc->szApplicationId = NULL;
-    dc->szRequireWith = NULL;
-    dc->szRedirectToSSL = NULL;
+    dc->szApplicationId = nullptr;
+    dc->szRequireWith = nullptr;
+    dc->szRedirectToSSL = nullptr;
+       dc->szAccessControl = nullptr;
     dc->bOff = -1;
     dc->bBasicHijack = -1;
     dc->bRequireSession = -1;
     dc->bExportAssertion = -1;
     dc->bUseEnvVars = -1;
     dc->bUseHeaders = -1;
+    dc->bExpireRedirects = -1;
     return dc;
 }
 
@@ -188,7 +206,7 @@ extern "C" void* merge_shib_dir_config (SH_AP_POOL* p, void* base, void* sub)
     shib_dir_config* child=(shib_dir_config*)sub;
 
     // The child supersedes any matching table settings in the parent.
-    dc->tSettings = NULL;
+    dc->tSettings = nullptr;
     if (parent->tSettings)
         dc->tSettings = ap_copy_table(p, parent->tSettings);
     if (child->tSettings) {
@@ -203,28 +221,35 @@ extern "C" void* merge_shib_dir_config (SH_AP_POOL* p, void* base, void* sub)
     else if (parent->szAuthGrpFile)
         dc->szAuthGrpFile=ap_pstrdup(p,parent->szAuthGrpFile);
     else
-        dc->szAuthGrpFile=NULL;
+        dc->szAuthGrpFile=nullptr;
 
     if (child->szApplicationId)
         dc->szApplicationId=ap_pstrdup(p,child->szApplicationId);
     else if (parent->szApplicationId)
         dc->szApplicationId=ap_pstrdup(p,parent->szApplicationId);
     else
-        dc->szApplicationId=NULL;
+        dc->szApplicationId=nullptr;
 
     if (child->szRequireWith)
         dc->szRequireWith=ap_pstrdup(p,child->szRequireWith);
     else if (parent->szRequireWith)
         dc->szRequireWith=ap_pstrdup(p,parent->szRequireWith);
     else
-        dc->szRequireWith=NULL;
+        dc->szRequireWith=nullptr;
 
     if (child->szRedirectToSSL)
         dc->szRedirectToSSL=ap_pstrdup(p,child->szRedirectToSSL);
     else if (parent->szRedirectToSSL)
         dc->szRedirectToSSL=ap_pstrdup(p,parent->szRedirectToSSL);
     else
-        dc->szRedirectToSSL=NULL;
+        dc->szRedirectToSSL=nullptr;
+
+       if (child->szAccessControl)
+        dc->szAccessControl=ap_pstrdup(p,child->szAccessControl);
+    else if (parent->szAccessControl)
+        dc->szAccessControl=ap_pstrdup(p,parent->szAccessControl);
+    else
+        dc->szAccessControl=nullptr;
 
     dc->bOff=((child->bOff==-1) ? parent->bOff : child->bOff);
     dc->bBasicHijack=((child->bBasicHijack==-1) ? parent->bBasicHijack : child->bBasicHijack);
@@ -234,6 +259,7 @@ extern "C" void* merge_shib_dir_config (SH_AP_POOL* p, void* base, void* sub)
     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);
+    dc->bExpireRedirects=((child->bExpireRedirects==-1) ? parent->bExpireRedirects : child->bExpireRedirects);
     return dc;
 }
 
@@ -260,7 +286,7 @@ static shib_request_config *init_request_config(request_rec *r)
 extern "C" const char* ap_set_global_string_slot(cmd_parms* parms, void*, const char* arg)
 {
     *((char**)(parms->info))=ap_pstrdup(parms->pool,arg);
-    return NULL;
+    return nullptr;
 }
 
 extern "C" const char* shib_set_server_string_slot(cmd_parms* parms, void*, const char* arg)
@@ -268,7 +294,7 @@ extern "C" const char* shib_set_server_string_slot(cmd_parms* parms, void*, cons
     char* base=(char*)ap_get_module_config(parms->server->module_config,&mod_shib);
     size_t offset=(size_t)parms->info;
     *((char**)(base + offset))=ap_pstrdup(parms->pool,arg);
-    return NULL;
+    return nullptr;
 }
 
 extern "C" const char* shib_ap_set_file_slot(cmd_parms* parms,
@@ -288,17 +314,18 @@ extern "C" const char* shib_table_set(cmd_parms* parms, shib_dir_config* dc, con
     if (!dc->tSettings)
         dc->tSettings = ap_make_table(parms->pool, 4);
     ap_table_set(dc->tSettings, arg1, arg2);
-    return NULL;
+    return nullptr;
 }
 
-/********************************************************************************/
-// Apache ShibTarget subclass(es) here.
 
 class ShibTargetApache : public AbstractSPRequest
+#if defined(SHIBSP_HAVE_GSSAPI) && !defined(SHIB_APACHE_13)
+    , public GSSRequest
+#endif
 {
   bool m_handler;
   mutable string m_body;
-  mutable bool m_gotBody;
+  mutable bool m_gotBody,m_firsttime;
   mutable vector<string> m_certs;
   set<string> m_allhttp;
 
@@ -308,26 +335,44 @@ public:
   shib_server_config* m_sc;
   shib_request_config* m_rc;
 
-  ShibTargetApache(request_rec* req, bool handler) : m_handler(handler), m_gotBody(false) {
+  ShibTargetApache(request_rec* req, bool handler, bool shib_check_user)
+      : AbstractSPRequest(SHIBSP_LOGCAT".Apache"), m_handler(handler), m_gotBody(false),m_firsttime(true) {
     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);
     m_req = req;
+
+    setRequestURI(m_req->unparsed_uri);
+
+    if (shib_check_user && m_dc->bUseHeaders == 1) {
+        // Try and see if this request was already processed, to skip spoof checking.
+        if (!ap_is_initial_req(m_req)) {
+            m_firsttime = false;
+        }
+        else if (!g_spoofKey.empty()) {
+            const char* hdr = ap_table_get(m_req->headers_in, "Shib-Spoof-Check");
+            if (hdr && g_spoofKey == hdr)
+                m_firsttime=false;
+        }
+
+        if (!m_firsttime)
+            log(SPDebug, "shib_check_user running more than once");
+    }
   }
   virtual ~ShibTargetApache() {}
 
   const char* getScheme() const {
     return m_sc->szScheme ? m_sc->szScheme : ap_http_method(m_req);
   }
+  bool isSecure() const {
+      return HTTPRequest::isSecure();
+  }
   const char* getHostname() const {
     return ap_get_server_name(m_req);
   }
   int getPort() const {
     return ap_get_server_port(m_req);
   }
-  const char* getRequestURI() const {
-    return m_req->unparsed_uri;
-  }
   const char* getMethod() const {
     return m_req->method;
   }
@@ -339,7 +384,8 @@ public:
       return m_gotBody ? m_body.length() : m_req->remaining;
   }
   string getRemoteAddr() const {
-    return m_req->connection->remote_ip;
+    string ret = AbstractSPRequest::getRemoteAddr();
+    return ret.empty() ? m_req->connection->remote_ip : ret;
   }
   void log(SPLogLevel level, const string& msg) const {
     AbstractSPRequest::log(level,msg);
@@ -350,6 +396,7 @@ public:
         (level == SPWarn ? APLOG_WARNING :
         (level == SPError ? APLOG_ERR : APLOG_CRIT))))|APLOG_NOERRNO,
         SH_AP_R(m_req),
+        "%s",
         msg.c_str()
         );
   }
@@ -415,10 +462,16 @@ public:
 #endif
     return m_body.c_str();
   }
+  const char* getParameter(const char* name) const {
+      return AbstractSPRequest::getParameter(name);
+  }
+  vector<const char*>::size_type getParameters(const char* name, vector<const char*>& values) const {
+      return AbstractSPRequest::getParameters(name, values);
+  }
   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");
-        if (g_checkSpoofing && ap_is_initial_req(m_req)) {
+        if (g_checkSpoofing && m_firsttime) {
             if (m_allhttp.empty()) {
                 // First time, so populate set with "CGI" versions of client-supplied headers.
 #ifdef SHIB_APACHE_13
@@ -473,44 +526,74 @@ public:
        if (m_rc && m_rc->env)
            hdr = ap_table_get(m_rc->env, name);
        else
-           hdr = NULL;
+           hdr = nullptr;
        return string(hdr ? hdr : "");
     }
     return getHeader(name);
   }
   void setRemoteUser(const char* user) {
-      SH_AP_USER(m_req) = user ? ap_pstrdup(m_req->pool, user) : NULL;
+      SH_AP_USER(m_req) = user ? ap_pstrdup(m_req->pool, user) : nullptr;
+      if (m_dc->bUseHeaders == 1) {
+          if (user) {
+              ap_table_set(m_req->headers_in, "REMOTE_USER", user);
+          }
+          else {
+              ap_table_unset(m_req->headers_in, "REMOTE_USER");
+              ap_table_set(m_req->headers_in, "REMOTE_USER", g_unsetHeaderValue.c_str());
+          }
+      }
   }
   string getRemoteUser() const {
     return string(SH_AP_USER(m_req) ? SH_AP_USER(m_req) : "");
   }
+  void setAuthType(const char* authtype) {
+      if (authtype && m_dc->bBasicHijack == 1)
+          authtype = "Basic";
+      SH_AP_AUTH_TYPE(m_req) = authtype ? ap_pstrdup(m_req->pool, authtype) : nullptr;
+  }
+  string getAuthType() const {
+    return string(SH_AP_AUTH_TYPE(m_req) ? SH_AP_AUTH_TYPE(m_req) : "");
+  }
   void setContentType(const char* type) {
-      m_req->content_type = ap_psprintf(m_req->pool, type);
+      m_req->content_type = ap_psprintf(m_req->pool, "%s", type);
   }
   void setResponseHeader(const char* name, const char* value) {
+   HTTPResponse::setResponseHeader(name, value);
 #ifdef SHIB_DEFERRED_HEADERS
    if (!m_rc)
       // this happens on subrequests
       m_rc = init_request_config(m_req);
-    if (m_handler)
+    if (m_handler) {
+        if (!m_rc->hdr_out)
+            m_rc->hdr_out = ap_make_table(m_req->pool, 5);
         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) {
+    if (status != XMLTOOLING_HTTP_STATUS_OK)
+        m_req->status = status;
     ap_send_http_header(m_req);
     char buf[1024];
     while (in) {
         in.read(buf,1024);
         ap_rwrite(buf,in.gcount(),m_req);
     }
-    if (status!=XMLTOOLING_HTTP_STATUS_OK)
-        m_req->status = status;
+#if (defined(SHIB_APACHE_20) || defined(SHIB_APACHE_22))
+    if (status != XMLTOOLING_HTTP_STATUS_OK && status != XMLTOOLING_HTTP_STATUS_ERROR)
+        return status;
+#endif
     return DONE;
   }
   long sendRedirect(const char* url) {
+    HTTPResponse::sendRedirect(url);
     ap_table_set(m_req->headers_out, "Location", url);
+    if (m_dc->bExpireRedirects != 0) {
+        ap_table_set(m_req->err_headers_out, "Expires", "Wed, 01 Jan 1997 12:00:00 GMT");
+        ap_table_set(m_req->err_headers_out, "Cache-Control", "private,no-store,no-cache,max-age=0");
+    }
     return REDIRECT;
   }
   const vector<string>& getClientCertificates() const {
@@ -529,6 +612,13 @@ public:
   }
   long returnDecline(void) { return DECLINED; }
   long returnOK(void) { return OK; }
+#if defined(SHIBSP_HAVE_GSSAPI) && !defined(SHIB_APACHE_13)
+  gss_ctx_id_t getGSSContext() const {
+    gss_ctx_id_t ctx = GSS_C_NO_CONTEXT;
+    apr_pool_userdata_get((void**)&ctx, g_szGSSContextKey, m_req->pool);
+    return ctx;
+  }
+#endif
 };
 
 /********************************************************************************/
@@ -539,7 +629,7 @@ extern "C" int shib_check_user(request_rec* r)
   // Short-circuit entirely?
   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", (int)getpid());
 
   ostringstream threadid;
@@ -547,11 +637,14 @@ extern "C" int shib_check_user(request_rec* r)
   xmltooling::NDC ndc(threadid.str().c_str());
 
   try {
-    ShibTargetApache sta(r,false);
+    ShibTargetApache sta(r,false,true);
 
     // Check user authentication and export information, then set the handler bypass
     pair<bool,long> res = sta.getServiceProvider().doAuthentication(sta,true);
-    apr_pool_userdata_setn((const void*)42,g_UserDataKey,NULL,r->pool);
+    apr_pool_userdata_setn((const void*)42,g_UserDataKey,nullptr,r->pool);
+    // If directed, install a spoof key to recognize when we've already cleared headers.
+    if (!g_spoofKey.empty() && (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bUseHeaders==1))
+        ap_table_set(r->headers_in, "Shib-Spoof-Check", g_spoofKey.c_str());
     if (res.first) return res.second;
 
     // user auth was okay -- export the assertions now
@@ -565,12 +658,12 @@ extern "C" int shib_check_user(request_rec* r)
     ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user threw an exception: %s", e.what());
     return SERVER_ERROR;
   }
-#ifndef _DEBUG
   catch (...) {
-    ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user threw an uncaught exception!");
-    return SERVER_ERROR;
+    ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user threw an unknown exception!");
+    if (g_catchAll)
+      return SERVER_ERROR;
+    throw;
   }
-#endif
 }
 
 extern "C" int shib_handler(request_rec* r)
@@ -598,7 +691,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,true);
+    ShibTargetApache sta(r,true,false);
 
     pair<bool,long> res = sta.getServiceProvider().doHandler(sta);
     if (res.first) return res.second;
@@ -610,12 +703,12 @@ extern "C" int shib_handler(request_rec* r)
     ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler threw an exception: %s", e.what());
     return SERVER_ERROR;
   }
-#ifndef _DEBUG
   catch (...) {
-    ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler threw an uncaught exception!");
-    return SERVER_ERROR;
+    ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler threw an unknown exception!");
+    if (g_catchAll)
+      return SERVER_ERROR;
+    throw;
   }
-#endif
 }
 
 /*
@@ -635,7 +728,7 @@ extern "C" int shib_auth_checker(request_rec* r)
   xmltooling::NDC ndc(threadid.str().c_str());
 
   try {
-    ShibTargetApache sta(r,false);
+    ShibTargetApache sta(r,false,false);
 
     pair<bool,long> res = sta.getServiceProvider().doAuthorization(sta);
     if (res.first) return res.second;
@@ -648,12 +741,12 @@ extern "C" int shib_auth_checker(request_rec* r)
     ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an exception: %s", e.what());
     return SERVER_ERROR;
   }
-#ifndef _DEBUG
   catch (...) {
-    ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an uncaught exception!");
-    return SERVER_ERROR;
+    ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an unknown exception!");
+    if (g_catchAll)
+      return SERVER_ERROR;
+    throw;
   }
-#endif
 }
 
 // Access control plugin that enforces htaccess rules
@@ -680,17 +773,18 @@ public:
     ApacheRequestMapper(const xercesc::DOMElement* e);
     ~ApacheRequestMapper() { delete m_mapper; delete m_htaccess; delete m_staKey; delete m_propsKey; }
     Lockable* lock() { return m_mapper->lock(); }
-    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 unlock() { m_staKey->setData(nullptr); m_propsKey->setData(nullptr); m_mapper->unlock(); }
+    Settings getSettings(const HTTPRequest& request) const;
+
+    const PropertySet* getParent() const { return nullptr; }
     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:2.0:native:sp:config") const;
+    pair<bool,bool> getBool(const char* name, const char* ns=nullptr) const;
+    pair<bool,const char*> getString(const char* name, const char* ns=nullptr) const;
+    pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=nullptr) const;
+    pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=nullptr) const;
+    pair<bool,int> getInt(const char* name, const char* ns=nullptr) 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:
@@ -705,15 +799,15 @@ RequestMapper* ApacheRequestMapFactory(const xercesc::DOMElement* const & e)
     return new ApacheRequestMapper(e);
 }
 
-ApacheRequestMapper::ApacheRequestMapper(const xercesc::DOMElement* e) : m_mapper(NULL), m_staKey(NULL), m_propsKey(NULL), m_htaccess(NULL)
+ApacheRequestMapper::ApacheRequestMapper(const xercesc::DOMElement* e) : m_mapper(nullptr), m_staKey(nullptr), m_propsKey(nullptr), m_htaccess(nullptr)
 {
     m_mapper=SPConfig::getConfig().RequestMapperManager.newPlugin(XML_REQUEST_MAPPER,e);
     m_htaccess=new htAccessControl();
-    m_staKey=ThreadKey::create(NULL);
-    m_propsKey=ThreadKey::create(NULL);
+    m_staKey=ThreadKey::create(nullptr);
+    m_propsKey=ThreadKey::create(nullptr);
 }
 
-RequestMapper::Settings ApacheRequestMapper::getSettings(const SPRequest& request) const
+RequestMapper::Settings ApacheRequestMapper::getSettings(const HTTPRequest& request) const
 {
     Settings s=m_mapper->getSettings(request);
     m_staKey->setData((void*)dynamic_cast<const ShibTargetApache*>(&request));
@@ -767,13 +861,13 @@ pair<bool,const char*> ApacheRequestMapper::getString(const char* name, const ch
                 return make_pair(true, prop);
         }
     }
-    return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
+    return s ? s->getString(name,ns) : pair<bool,const char*>(false,nullptr);
 }
 
 pair<bool,const XMLCh*> ApacheRequestMapper::getXMLString(const char* name, const char* ns) const
 {
     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
-    return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
+    return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,nullptr);
 }
 
 pair<bool,unsigned int> ApacheRequestMapper::getUnsignedInt(const char* name, const char* ns) const
@@ -783,11 +877,11 @@ 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, nullptr, 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 pair<bool,unsigned int>(true, atoi(prop));
         }
     }
     return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
@@ -810,16 +904,55 @@ pair<bool,int> ApacheRequestMapper::getInt(const char* name, const char* ns) con
     return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
 }
 
+static int _rm_get_all_table_walk(void *v, const char *key, const char *value)
+{
+    reinterpret_cast<map<string,const char*>*>(v)->insert(pair<string,const char*>(key, value));
+    return 1;
+}
+
+void ApacheRequestMapper::getAll(map<string,const char*>& properties) const
+{
+    const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
+    const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
+
+    if (s)
+        s->getAll(properties);
+    if (!sta)
+        return;
+
+    const char* auth_type=ap_auth_type(sta->m_req);
+    if (auth_type) {
+        // Check for Basic Hijack
+        if (!strcasecmp(auth_type, "basic") && sta->m_dc->bBasicHijack == 1)
+            auth_type = "shibboleth";
+        properties["authType"] = auth_type;
+    }
+
+    if (sta->m_dc->szApplicationId)
+        properties["applicationId"] = sta->m_dc->szApplicationId;
+    if (sta->m_dc->szRequireWith)
+        properties["requireSessionWith"] = sta->m_dc->szRequireWith;
+    if (sta->m_dc->szRedirectToSSL)
+        properties["redirectToSSL"] = sta->m_dc->szRedirectToSSL;
+    if (sta->m_dc->bRequireSession != 0)
+        properties["requireSession"] = (sta->m_dc->bRequireSession==1) ? "true" : "false";
+    if (sta->m_dc->bExportAssertion != 0)
+        properties["exportAssertion"] = (sta->m_dc->bExportAssertion==1) ? "true" : "false";
+
+    if (sta->m_dc->tSettings)
+        ap_table_do(_rm_get_all_table_walk, &properties, sta->m_dc->tSettings, NULL);
+}
+
 const PropertySet* ApacheRequestMapper::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;
+    return s ? s->getPropertySet(name,ns) : nullptr;
 }
 
 const xercesc::DOMElement* ApacheRequestMapper::getElement() const
 {
     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
-    return s ? s->getElement() : NULL;
+    return s ? s->getElement() : nullptr;
 }
 
 static SH_AP_TABLE* groups_for_user(request_rec* r, const char* user, char* grpfile)
@@ -835,7 +968,7 @@ static SH_AP_TABLE* groups_for_user(request_rec* r, const char* user, char* grpf
     if (ap_pcfg_openfile(&f,r->pool,grpfile) != APR_SUCCESS) {
 #endif
         ap_log_rerror(APLOG_MARK,APLOG_DEBUG,SH_AP_R(r),"groups_for_user() could not open group file: %s\n",grpfile);
-        return NULL;
+        return nullptr;
     }
 
     SH_AP_POOL* sp;
@@ -845,7 +978,7 @@ static SH_AP_TABLE* groups_for_user(request_rec* r, const char* user, char* grpf
     if (apr_pool_create(&sp,r->pool) != APR_SUCCESS) {
         ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,
             "groups_for_user() could not create a subpool");
-        return NULL;
+        return nullptr;
     }
 #endif
 
@@ -878,22 +1011,18 @@ bool htAccessControl::checkAttribute(const SPRequest& request, const Attribute*
         if (re) {
             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"
-                    );
+                if (request.isPriorityEnabled(SPRequest::SPDebug))
+                    request.log(SPRequest::SPDebug, string("htaccess: expecting regexp ") + toMatch + ", got " + *v + ": acccepted");
                 return true;
             }
         }
         else if ((caseSensitive && *v == toMatch) || (!caseSensitive && !strcasecmp(v->c_str(), toMatch))) {
-            request.log(SPRequest::SPDebug,
-                string("htAccessControl plugin expecting ") + toMatch + ", got " + *v + ": authorization granted."
-                );
+            if (request.isPriorityEnabled(SPRequest::SPDebug))
+                request.log(SPRequest::SPDebug, string("htaccess: expecting ") + toMatch + ", got " + *v + ": accepted");
             return true;
         }
-        else {
-            request.log(SPRequest::SPDebug,
-                string("htAccessControl plugin expecting ") + toMatch + ", got " + *v + ": authorization not granted."
-                );
+        else if (request.isPriorityEnabled(SPRequest::SPDebug)) {
+            request.log(SPRequest::SPDebug, string("htaccess: expecting ") + toMatch + ", got " + *v + ": rejected");
         }
     }
     return false;
@@ -906,35 +1035,65 @@ AccessControl::aclresult_t htAccessControl::authorized(const SPRequest& request,
     if (!sta)
         throw ConfigurationException("Request wrapper object was not of correct type.");
 
-    // mod_auth clone
-
     int m=sta->m_req->method_number;
     bool method_restricted=false;
     const char *t, *w;
-    
+
     const array_header* reqs_arr=ap_requires(sta->m_req);
     if (!reqs_arr)
         return shib_acl_indeterminate;  // should never happen
 
-    require_line* reqs=(require_line*)reqs_arr->elts;
-    
-    ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(sta->m_req),"REQUIRE nelts: %d", reqs_arr->nelts);
-    ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(sta->m_req),"REQUIRE all: %d", sta->m_dc->bRequireAll);
+       // Check for an "embedded" AccessControl plugin.
+       if (sta->m_dc->szAccessControl) {
+               aclresult_t result = shib_acl_false;
+               try {
+            ifstream aclfile(sta->m_dc->szAccessControl);
+            xercesc::DOMDocument* acldoc = XMLToolingConfig::getConfig().getParser().parse(aclfile);
+                   XercesJanitor<xercesc::DOMDocument> docjanitor(acldoc);
+                   static XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
+            string t(XMLHelper::getAttrString(acldoc ? acldoc->getDocumentElement() : nullptr, nullptr, _type));
+            if (t.empty())
+                throw ConfigurationException("Missing type attribute in AccessControl plugin configuration.");
+            auto_ptr<AccessControl> aclplugin(SPConfig::getConfig().AccessControlManager.newPlugin(t.c_str(), acldoc->getDocumentElement()));
+                       Locker acllock(aclplugin.get());
+                       result = aclplugin->authorized(request, session);
+               }
+               catch (exception& ex) {
+                       request.log(SPRequest::SPError, ex.what());
+               }
+
+        if (result == shib_acl_true && sta->m_dc->bRequireAll != 1) {
+            // If we're not insisting that all rules be met, then we're done.
+            request.log(SPRequest::SPDebug, "htaccess: embedded AccessControl plugin was successful, granting access");
+            return shib_acl_true;
+        }
+        else if (result != shib_acl_true && sta->m_dc->bRequireAll == 1) {
+            // If we're insisting that all rules be met, which is not something Apache really handles well,
+            // then we either return false or indeterminate based on the authoritative option, which defaults on.
+            if (sta->m_dc->bAuthoritative != 0) {
+                request.log(SPRequest::SPDebug, "htaccess: embedded AccessControl plugin was unsuccessful, denying access");
+                return shib_acl_false;
+            }
 
-    vector<bool> auth_OK(reqs_arr->nelts,false);
+            request.log(SPRequest::SPDebug, "htaccess: embedded AccessControl plugin was unsuccessful but not authoritative, leaving it up to Apache");
+            return shib_acl_indeterminate;
+        }
+    }
 
-#define SHIB_AP_CHECK_IS_OK {           \
-     if (sta->m_dc->bRequireAll < 1)    \
-         return shib_acl_true;          \
-     auth_OK[x] = true;                 \
-     continue;                          \
-}
+
+    require_line* reqs=(require_line*)reqs_arr->elts;
 
     for (int x=0; x<reqs_arr->nelts; x++) {
-        auth_OK[x] = false;
+        // This rule should be completely ignored, the method doesn't fit.
+        // The rule just doesn't exist for our purposes.
         if (!(reqs[x].method_mask & (1 << m)))
             continue;
-        method_restricted=true;
+
+        method_restricted=true; // this lets us know at the end that at least one rule was potentially enforcable.
+
+        // Tracks status of this rule's evaluation.
+        bool status = false;
+
         string remote_user = request.getRemoteUser();
 
         t = reqs[x].requirement;
@@ -943,104 +1102,151 @@ AccessControl::aclresult_t htAccessControl::authorized(const SPRequest& request,
         if (!strcasecmp(w,"shibboleth")) {
             // This is a dummy rule needed because Apache conflates authn and authz.
             // Without some require rule, AuthType is ignored and no check_user hooks run.
-            SHIB_AP_CHECK_IS_OK;
-        }
-        else if (!strcmp(w,"valid-user")) {
-            if (session) {
-                request.log(SPRequest::SPDebug,"htAccessControl plugin accepting valid-user based on active session");
-                SHIB_AP_CHECK_IS_OK;
-            }
-            else {
-                request.log(SPRequest::SPError,"htAccessControl plugin rejecting access for valid-user rule, no session is active");
+
+            // We evaluate to false if ShibAccessControl is used and ShibRequireAll is off.
+            // This allows actual rules to dictate the result, since ShibAccessControl returned
+            // non-true, and if nothing else is used, access will be denied.
+            if (!sta->m_dc->szAccessControl || sta->m_dc->bRequireAll == 1) {
+                // We evaluate to true, because ShibRequireAll is enabled (so a true is just a no-op)
+                // or because there was no other AccessControl rule in place, so this may be the only
+                // rule in effect.
+                status = true;
             }
         }
+        else if (!strcmp(w,"valid-user") && session) {
+            request.log(SPRequest::SPDebug, "htaccess: accepting valid-user based on active session");
+            status = true;
+        }
         else if (!strcmp(w,"user") && !remote_user.empty()) {
-            bool regexp=false;
+            bool regexp = false;
             while (*t) {
-                w=ap_getword_conf(sta->m_req->pool,&t);
-                if (*w=='~') {
-                    regexp=true;
+                w = ap_getword_conf(sta->m_req->pool,&t);
+                if (*w == '~') {
+                    regexp = true;
+                    continue;
+                }
+                else if (*w == '!') {
+                    // A negated rule presumes success unless a match is found.
+                    status = true;
+                    if (*(w+1) == '~')
+                        regexp = true;
                     continue;
                 }
-                
+
+                // Figure out if there's a match.
+                bool match = false;
                 if (regexp) {
                     try {
                         // To do regex matching, we have to convert from UTF-8.
                         auto_arrayptr<XMLCh> trans(fromUTF8(w));
                         RegularExpression re(trans.get());
                         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;
-                        }
+                        match = re.matches(trans2.get());
                     }
                     catch (XMLException& ex) {
                         auto_ptr_char tmp(ex.getMessage());
                         request.log(SPRequest::SPError,
-                            string("htAccessControl plugin caught exception while parsing regular expression (") + w + "): " + tmp.get());
+                            string("htaccess plugin caught exception while parsing regular expression (") + w + "): " + tmp.get());
                     }
                 }
-                else if (remote_user==w) {
-                    request.log(SPRequest::SPDebug, string("htAccessControl plugin accepting user (") + w + ")");
-                    SHIB_AP_CHECK_IS_OK;
+                else if (remote_user == w) {
+                    match = true;
+                }
+
+                if (match) {
+                    // If we matched, then we're done with this rule either way and we flip status to reflect the outcome.
+                    status = !status;
+                    if (request.isPriorityEnabled(SPRequest::SPDebug))
+                        request.log(SPRequest::SPDebug,
+                            string("htaccess: require user ") + (!status ? "rejecting (" : "accepting (") + remote_user + ")");
+                    break;
                 }
             }
         }
-        else if (!strcmp(w,"group")) {
-            SH_AP_TABLE* grpstatus=NULL;
-            if (sta->m_dc->szAuthGrpFile && !remote_user.empty()) {
-                request.log(SPRequest::SPDebug,string("htAccessControl plugin using groups file: ") + sta->m_dc->szAuthGrpFile);
-                grpstatus=groups_for_user(sta->m_req,remote_user.c_str(),sta->m_dc->szAuthGrpFile);
+        else if (!strcmp(w,"group")  && !remote_user.empty()) {
+            SH_AP_TABLE* grpstatus = nullptr;
+            if (sta->m_dc->szAuthGrpFile) {
+                if (request.isPriorityEnabled(SPRequest::SPDebug))
+                    request.log(SPRequest::SPDebug,string("htaccess plugin using groups file: ") + sta->m_dc->szAuthGrpFile);
+                grpstatus = groups_for_user(sta->m_req,remote_user.c_str(),sta->m_dc->szAuthGrpFile);
             }
-            if (!grpstatus)
-                continue;
-    
+
             while (*t) {
-                w=ap_getword_conf(sta->m_req->pool,&t);
-                if (ap_table_get(grpstatus,w)) {
-                    request.log(SPRequest::SPDebug, string("htAccessControl plugin accepting group (") + w + ")");
-                    SHIB_AP_CHECK_IS_OK;
+                w = ap_getword_conf(sta->m_req->pool,&t);
+                if (*w == '!') {
+                    // A negated rule presumes success unless a match is found.
+                    status = true;
+                    continue;
                 }
-            }
-        }
-        else if (!strcmp(w,"authnContextClassRef")) {
-            const char* ref = session->getAuthnContextClassRef();
-            while (ref && *t) {
-                w=ap_getword_conf(sta->m_req->pool,&t);
-                if (!strcmp(w, ref)) {
-                    request.log(SPRequest::SPDebug, string("htAccessControl plugin accepting authnContextClassRef (") + w + ")");
-                    SHIB_AP_CHECK_IS_OK;
+
+                if (grpstatus && ap_table_get(grpstatus,w)) {
+                    // If we matched, then we're done with this rule either way and we flip status to reflect the outcome.
+                    status = !status;
+                    request.log(SPRequest::SPDebug, string("htaccess: require group ") + (!status ? "rejecting (" : "accepting (") + w + ")");
+                    break;
                 }
             }
         }
-        else if (!strcmp(w,"authnContextDeclRef")) {
-            const char* ref = session->getAuthnContextDeclRef();
-            while (ref && *t) {
-                w=ap_getword_conf(sta->m_req->pool,&t);
-                if (!strcmp(w, ref)) {
-                    request.log(SPRequest::SPDebug, string("htAccessControl plugin accepting authnContextDeclRef (") + w + ")");
-                    SHIB_AP_CHECK_IS_OK;
+        else if (!strcmp(w,"authnContextClassRef") || !strcmp(w,"authnContextDeclRef")) {
+            const char* ref = !strcmp(w,"authnContextClassRef") ? session->getAuthnContextClassRef() : session->getAuthnContextDeclRef();
+            if (ref && *ref) {
+                bool regexp = false;
+                while (ref && *t) {
+                    w = ap_getword_conf(sta->m_req->pool,&t);
+                    if (*w == '~') {
+                        regexp=true;
+                        continue;
+                    }
+                    else if (*w == '!') {
+                        // A negated rule presumes success unless a match is found.
+                        status = true;
+                        if (*(w+1)=='~')
+                            regexp = true;
+                        continue;
+                    }
+
+                    // Figure out if there's a match.
+                    bool match = false;
+                    if (regexp) {
+                        try {
+                            // To do regex matching, we have to convert from UTF-8.
+                            RegularExpression re(w);
+                            match = re.matches(ref);
+                        }
+                        catch (XMLException& ex) {
+                            auto_ptr_char tmp(ex.getMessage());
+                            request.log(SPRequest::SPError,
+                                string("htaccess plugin caught exception while parsing regular expression (") + w + "): " + tmp.get());
+                        }
+                    }
+                    else if (!strcmp(w,ref)) {
+                        match = true;
+                    }
+
+                    if (match) {
+                        // If we matched, then we're done with this rule either way and we flip status to reflect the outcome.
+                        status = !status;
+                        if (request.isPriorityEnabled(SPRequest::SPDebug))
+                            request.log(SPRequest::SPDebug,
+                                string("htaccess: require authnContext ") + (!status ? "rejecting (" : "accepting (") + ref + ")");
+                        break;
+                    }
                 }
             }
+            else if (request.isPriorityEnabled(SPRequest::SPDebug)) {
+                request.log(SPRequest::SPDebug, "htaccess: require authnContext rejecting session with no context associated");
+            }
+        }
+        else if (!session) {
+            request.log(SPRequest::SPError, string("htaccess: require ") + w + " not given a valid session, are you using lazy sessions?");
         }
         else {
-            // Map alias in rule to the attribute.
-            if (!session) {
-                request.log(SPRequest::SPError, "htAccessControl plugin not given a valid session to evaluate, are you using lazy sessions?");
-                continue;
-            }
-            
             // Find the attribute(s) matching the require rule.
             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;
-            }
 
             bool regexp=false;
-
-            while (!auth_OK[x] && *t) {
+            while (!status && attrs.first!=attrs.second && *t) {
                 w=ap_getword_conf(sta->m_req->pool,&t);
                 if (*w=='~') {
                     regexp=true;
@@ -1056,44 +1262,71 @@ AccessControl::aclresult_t htAccessControl::authorized(const SPRequest& request,
                         re=temp;
                     }
                     
-                    for (; !auth_OK[x] && attrs.first!=attrs.second; ++attrs.first) {
-                        if (checkAttribute(request, attrs.first->second, w, regexp ? re.get() : NULL)) {
-                            SHIB_AP_CHECK_IS_OK;
+                    pair<multimap<string,const Attribute*>::const_iterator,multimap<string,const Attribute*>::const_iterator> attrs2(attrs);
+                    for (; !status && attrs2.first!=attrs2.second; ++attrs2.first) {
+                        if (checkAttribute(request, attrs2.first->second, w, regexp ? re.get() : nullptr)) {
+                            status = true;
                         }
                     }
                 }
                 catch (XMLException& ex) {
                     auto_ptr_char tmp(ex.getMessage());
                     request.log(SPRequest::SPError,
-                        string("htAccessControl plugin caught exception while parsing regular expression (") + w + "): " + tmp.get()
+                        string("htaccess plugin caught exception while parsing regular expression (") + w + "): " + tmp.get()
                         );
                 }
             }
         }
+
+        // If status is false, we found a rule we couldn't satisfy.
+        // Could be an unknown rule to us, or it just didn't match.
+
+        if (status && sta->m_dc->bRequireAll != 1) {
+            // If we're not insisting that all rules be met, then we're done.
+            request.log(SPRequest::SPDebug, "htaccess: a rule was successful, granting access");
+            return shib_acl_true;
+        }
+        else if (!status && sta->m_dc->bRequireAll == 1) {
+            // If we're insisting that all rules be met, which is not something Apache really handles well,
+            // then we either return false or indeterminate based on the authoritative option, which defaults on.
+            if (sta->m_dc->bAuthoritative != 0) {
+                request.log(SPRequest::SPDebug, "htaccess: a rule was unsuccessful, denying access");
+                return shib_acl_false;
+            }
+
+            request.log(SPRequest::SPDebug, "htaccess: a rule was unsuccessful but not authoritative, leaving it up to Apache");
+            return shib_acl_indeterminate;
+        }
+
+        // Otherwise, we keep going. If we're requring all, then we have to check every rule.
+        // If not we just didn't find a successful rule yet, so we keep going anyway.
     }
 
-    // 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 we get here, we either "failed" or we're in require all mode (but not both).
+    // If no rules possibly apply or we insisted that all rules check out, then we're good.
+    if (!method_restricted) {
+        request.log(SPRequest::SPDebug, "htaccess: no rules applied to this request method, granting access");
+        return shib_acl_true;
     }
-    if (auth_all_OK || !method_restricted)
+    else if (sta->m_dc->bRequireAll == 1) {
+        request.log(SPRequest::SPDebug, "htaccess: all rules successful, granting access");
         return shib_acl_true;
+    }
+    else if (sta->m_dc->bAuthoritative != 0) {
+        request.log(SPRequest::SPDebug, "htaccess: no rules were successful, denying access");
+        return shib_acl_false;
+    }
 
-    return (sta->m_dc->bAuthoritative != 0) ? shib_acl_false : shib_acl_indeterminate;
+    request.log(SPRequest::SPDebug, "htaccess: no rules were successful but not authoritative, leaving it up to Apache");
+    return shib_acl_indeterminate;
 }
 
 
 // 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");
-
-#ifdef SHIB_DEFERRED_HEADERS
-    rc->hdr_out = ap_make_table(r->pool, 5);
-#endif
+    init_request_config(r);
+    //ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_post_read");
     return DECLINED;
 }
 
@@ -1108,7 +1341,7 @@ extern "C" int shib_fixups(request_rec* r)
 
   ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_fixup(%d): ENTER", (int)getpid());
 
-  if (rc==NULL || rc->env==NULL || ap_is_empty_table(rc->env))
+  if (rc==nullptr || rc->env==nullptr || ap_is_empty_table(rc->env))
         return DECLINED;
 
   ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_fixup adding %d vars", ap_table_elts(rc->env)->nelts);
@@ -1127,7 +1360,7 @@ 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;
+        g_Config = nullptr;
         ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit() done");
     }
 }
@@ -1140,14 +1373,14 @@ extern "C" apr_status_t shib_exit(void* data)
 {
     if (g_Config) {
         g_Config->term();
-        g_Config = NULL;
+        g_Config = nullptr;
     }
-    ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,0,NULL,"shib_exit() done");
+    ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,0,nullptr,"shib_exit() done");
     return OK;
 }
 #endif
 
-/* 
+/*
  * shire_child_init()
  *  Things to do when the child process is initialized.
  *  (or after the configs are read in apache-2)
@@ -1176,44 +1409,43 @@ extern "C" void shib_child_init(apr_pool_t* p, server_rec* s)
         SPConfig::Logging |
         SPConfig::Handlers
         );
-    if (!g_Config->init(g_szSchemaDir)) {
+    if (!g_Config->init(g_szSchemaDir, g_szPrefix)) {
         ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize libraries");
         exit(1);
     }
     g_Config->AccessControlManager.registerFactory(HT_ACCESS_CONTROL,&htAccessFactory);
     g_Config->RequestMapperManager.registerFactory(NATIVE_REQUEST_MAPPER,&ApacheRequestMapFactory);
-    
+
     try {
-        xercesc::DOMDocument* dummydoc=XMLToolingConfig::getConfig().getParser().newDocument();
-        XercesJanitor<xercesc::DOMDocument> docjanitor(dummydoc);
-        xercesc::DOMElement* dummy = dummydoc->createElementNS(NULL,path);
-        auto_ptr_XMLCh src(g_szSHIBConfig);
-        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(g_szSHIBConfig, true))
+            throw runtime_error("unknown error");
     }
     catch (exception& ex) {
-        ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),ex.what());
+        ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"%s",ex.what());
         ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to load configuration");
         exit(1);
     }
 
     ServiceProvider* sp=g_Config->getServiceProvider();
     xmltooling::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> checkSpoofing=props->getBool("checkSpoofing");
-        if (checkSpoofing.first && !checkSpoofing.second)
-            g_checkSpoofing = false;
+        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;
     }
 
     // Set the cleanup handler
-    apr_pool_cleanup_register(p, NULL, &shib_exit, apr_pool_cleanup_null);
+    apr_pool_cleanup_register(p, nullptr, &shib_exit, apr_pool_cleanup_null);
 
     ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() done");
 }
@@ -1222,12 +1454,12 @@ extern "C" void shib_child_init(apr_pool_t* p, server_rec* s)
 #ifdef SHIB_DEFERRED_HEADERS
 static void set_output_filter(request_rec *r)
 {
-   ap_add_output_filter("SHIB_HEADERS_OUT", NULL, r, r->connection);
+   ap_add_output_filter("SHIB_HEADERS_OUT", nullptr, r, r->connection);
 }
 
 static void set_error_filter(request_rec *r)
 {
-   ap_add_output_filter("SHIB_HEADERS_ERR", NULL, r, r->connection);
+   ap_add_output_filter("SHIB_HEADERS_ERR", nullptr, r, r->connection);
 }
 
 static int _table_add(void *v, const char *key, const char *value)
@@ -1241,11 +1473,11 @@ static apr_status_t do_output_filter(ap_filter_t *f, apr_bucket_brigade *in)
     request_rec *r = f->r;
     shib_request_config *rc = (shib_request_config*) ap_get_module_config(r->request_config, &mod_shib);
 
-    if (rc) {
+    if (rc && rc->hdr_out) {
         ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_out_filter: merging %d headers", apr_table_elts(rc->hdr_out)->nelts);
-        apr_table_do(_table_add,r->headers_out, rc->hdr_out,NULL);
         // can't use overlap call because it will collapse Set-Cookie headers
         //apr_table_overlap(r->headers_out, rc->hdr_out, APR_OVERLAP_TABLES_MERGE);
+        apr_table_do(_table_add,r->headers_out, rc->hdr_out,NULL);
     }
 
     /* remove ourselves from the filter chain */
@@ -1260,11 +1492,11 @@ static apr_status_t do_error_filter(ap_filter_t *f, apr_bucket_brigade *in)
     request_rec *r = f->r;
     shib_request_config *rc = (shib_request_config*) ap_get_module_config(r->request_config, &mod_shib);
 
-    if (rc) {
+    if (rc && rc->hdr_out) {
         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_out, APR_OVERLAP_TABLES_MERGE);
+        apr_table_do(_table_add,r->err_headers_out, rc->hdr_out,NULL);
     }
 
     /* remove ourselves from the filter chain */
@@ -1282,20 +1514,24 @@ typedef const char* (*config_fn_t)(void);
 // SHIB Module commands
 
 static command_rec shire_cmds[] = {
+  {"ShibPrefix", (config_fn_t)ap_set_global_string_slot, &g_szPrefix,
+   RSRC_CONF, TAKE1, "Shibboleth installation directory"},
   {"ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
-   RSRC_CONF, TAKE1, "Path to shibboleth.xml config file"},
+   RSRC_CONF, TAKE1, "Path to shibboleth2.xml config file"},
   {"ShibCatalogs", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
    RSRC_CONF, TAKE1, "Paths of XML schema catalogs"},
-  {"ShibSchemaDir", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
-   RSRC_CONF, TAKE1, "Paths of XML schema catalogs (deprecated in favor of ShibCatalogs)"},
 
   {"ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
    (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,
+
+  {"ShibRequestSetting", (config_fn_t)shib_table_set, nullptr,
    OR_AUTHCFG, TAKE2, "Set arbitrary Shibboleth request property for content"},
 
+  {"ShibAccessControl", (config_fn_t)ap_set_string_slot,
+   (void *) XtOffsetOf (shib_dir_config, szAccessControl),
+   OR_AUTHCFG, TAKE1, "Set arbitrary Shibboleth access control plugin 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"},
@@ -1304,7 +1540,7 @@ static command_rec shire_cmds[] = {
    OR_AUTHCFG, TAKE1, "Set Shibboleth applicationId property for content"},
   {"ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
    (void *) XtOffsetOf (shib_dir_config, bBasicHijack),
-   OR_AUTHCFG, FLAG, "Respond to AuthType Basic and convert to shibboleth"},
+   OR_AUTHCFG, FLAG, "(DEPRECATED) Respond to AuthType Basic and convert to shibboleth"},
   {"ShibRequireSession", (config_fn_t)ap_set_flag_slot,
    (void *) XtOffsetOf (shib_dir_config, bRequireSession),
    OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist"},
@@ -1332,33 +1568,36 @@ static command_rec shire_cmds[] = {
   {"ShibUseHeaders", (config_fn_t)ap_set_flag_slot,
    (void *) XtOffsetOf (shib_dir_config, bUseHeaders),
    OR_AUTHCFG, FLAG, "Export attributes using custom HTTP headers"},
+  {"ShibExpireRedirects", (config_fn_t)ap_set_flag_slot,
+   (void *) XtOffsetOf (shib_dir_config, bExpireRedirects),
+   OR_AUTHCFG, FLAG, "Expire SP-generated redirects"},
 
-  {NULL}
+  {nullptr}
 };
 
 extern "C"{
 handler_rec shib_handlers[] = {
   { "shib-handler", shib_handler },
-  { NULL }
+  { nullptr }
 };
 
 module MODULE_VAR_EXPORT mod_shib = {
     STANDARD_MODULE_STUFF,
-    NULL,                        /* initializer */
+    nullptr,                        /* initializer */
     create_shib_dir_config,    /* dir config creater */
     merge_shib_dir_config,     /* dir merger --- default is to override */
     create_shib_server_config, /* server config */
     merge_shib_server_config,   /* merge server config */
     shire_cmds,                        /* command table */
     shib_handlers,             /* handlers */
-    NULL,                      /* filename translation */
+    nullptr,                   /* filename translation */
     shib_check_user,           /* check_user_id */
     shib_auth_checker,         /* check auth */
-    NULL,                      /* check access */
-    NULL,                      /* type_checker */
+    nullptr,                   /* check access */
+    nullptr,                   /* type_checker */
     shib_fixups,               /* fixups */
-    NULL,                      /* logger */
-    NULL,                      /* header parser */
+    nullptr,                   /* logger */
+    nullptr,                   /* header parser */
     shib_child_init,           /* child_init */
     shib_child_exit,           /* child_exit */
     shib_post_read             /* post read-request */
@@ -1366,40 +1605,55 @@ module MODULE_VAR_EXPORT mod_shib = {
 
 #elif defined(SHIB_APACHE_20) || defined(SHIB_APACHE_22)
 
+//static const char * const authnPre[] = { "mod_gss.c", nullptr };
+
 extern "C" void shib_register_hooks (apr_pool_t *p)
 {
 #ifdef SHIB_DEFERRED_HEADERS
-  ap_register_output_filter("SHIB_HEADERS_OUT", do_output_filter, NULL, AP_FTYPE_CONTENT_SET);
-  ap_hook_insert_filter(set_output_filter, NULL, NULL, APR_HOOK_LAST);
-  ap_register_output_filter("SHIB_HEADERS_ERR", do_error_filter, NULL, AP_FTYPE_CONTENT_SET);
-  ap_hook_insert_error_filter(set_error_filter, NULL, NULL, APR_HOOK_LAST);
-  ap_hook_post_read_request(shib_post_read, NULL, NULL, APR_HOOK_MIDDLE);
+  ap_register_output_filter("SHIB_HEADERS_OUT", do_output_filter, nullptr, AP_FTYPE_CONTENT_SET);
+  ap_hook_insert_filter(set_output_filter, nullptr, nullptr, APR_HOOK_LAST);
+  ap_register_output_filter("SHIB_HEADERS_ERR", do_error_filter, nullptr, AP_FTYPE_CONTENT_SET);
+  ap_hook_insert_error_filter(set_error_filter, nullptr, nullptr, APR_HOOK_LAST);
+  ap_hook_post_read_request(shib_post_read, nullptr, nullptr, APR_HOOK_MIDDLE);
 #endif
-  ap_hook_child_init(shib_child_init, NULL, NULL, APR_HOOK_MIDDLE);
-  ap_hook_check_user_id(shib_check_user, NULL, NULL, APR_HOOK_MIDDLE);
-  ap_hook_auth_checker(shib_auth_checker, NULL, NULL, APR_HOOK_FIRST);
-  ap_hook_handler(shib_handler, NULL, NULL, APR_HOOK_LAST);
-  ap_hook_fixups(shib_fixups, NULL, NULL, APR_HOOK_MIDDLE);
+  ap_hook_child_init(shib_child_init, nullptr, nullptr, APR_HOOK_MIDDLE);
+  const char* prereq = getenv("SHIBSP_APACHE_PREREQ");
+  if (prereq && *prereq) {
+    const char* const authnPre[] = { prereq, nullptr };
+    ap_hook_check_user_id(shib_check_user, authnPre, nullptr, APR_HOOK_MIDDLE);
+  }
+  else {
+    ap_hook_check_user_id(shib_check_user, nullptr, nullptr, APR_HOOK_MIDDLE);
+  }
+  ap_hook_auth_checker(shib_auth_checker, nullptr, nullptr, APR_HOOK_FIRST);
+  ap_hook_handler(shib_handler, nullptr, nullptr, APR_HOOK_LAST);
+  ap_hook_fixups(shib_fixups, nullptr, nullptr, APR_HOOK_MIDDLE);
 }
 
 // SHIB Module commands
 
 extern "C" {
 static command_rec shib_cmds[] = {
+    AP_INIT_TAKE1("ShibPrefix", (config_fn_t)ap_set_global_string_slot, &g_szPrefix,
+        RSRC_CONF, "Shibboleth installation directory"),
     AP_INIT_TAKE1("ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
-        RSRC_CONF, "Path to shibboleth.xml config file"),
+        RSRC_CONF, "Path to shibboleth2.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("ShibGSSKey", (config_fn_t)ap_set_global_string_slot, &g_szGSSContextKey,
+        RSRC_CONF, "Name of user data key containing GSS context established by GSS module"),
 
     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,
+    AP_INIT_TAKE2("ShibRequestSetting", (config_fn_t)shib_table_set, nullptr,
         OR_AUTHCFG, "Set arbitrary Shibboleth request property for content"),
 
+    AP_INIT_TAKE1("ShibAccessControl", (config_fn_t)ap_set_string_slot,
+        (void *) offsetof (shib_dir_config, szAccessControl),
+        OR_AUTHCFG, "Set arbitrary Shibboleth access control plugin 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"),
@@ -1408,7 +1662,7 @@ static command_rec shib_cmds[] = {
         OR_AUTHCFG, "Set Shibboleth applicationId property for content"),
     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"),
+        OR_AUTHCFG, "(DEPRECATED) Respond to AuthType Basic and convert to shibboleth"),
     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"),
@@ -1436,8 +1690,11 @@ static command_rec shib_cmds[] = {
     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"),
+    AP_INIT_FLAG("ShibExpireRedirects", (config_fn_t)ap_set_flag_slot,
+        (void *) offsetof (shib_dir_config, bExpireRedirects),
+        OR_AUTHCFG, "Expire SP-generated redirects"),
 
-    {NULL}
+    {nullptr}
 };
 
 module AP_MODULE_DECLARE_DATA mod_shib = {