Path resolution for error templates.
[shibboleth/sp.git] / apache / mod_apache.cpp
index c76bdcf..11a8106 100644 (file)
@@ -85,11 +85,13 @@ using xercesc::XMLException;
 extern "C" module MODULE_VAR_EXPORT mod_shib;
 
 namespace {
-    char* g_szSHIBConfig = SHIBSP_CONFIG;
-    char* g_szSchemaDir = SHIBSP_SCHEMAS;
+    char* g_szSHIBConfig = NULL;
+    char* g_szSchemaDir = NULL;
+    char* g_szPrefix = NULL;
     SPConfig* g_Config = NULL;
     string g_unsetHeaderValue;
     bool g_checkSpoofing = true;
+    bool g_catchAll = false;
     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);
@@ -141,9 +143,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
@@ -161,15 +166,17 @@ struct shib_dir_config
 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;
@@ -182,6 +189,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)
@@ -215,6 +233,7 @@ 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;
@@ -266,6 +285,14 @@ 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.
 
@@ -283,11 +310,13 @@ 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) : AbstractSPRequest(SHIBSP_LOGCAT".Apache"), 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);
     m_req = req;
+
+    setRequestURI(m_req->unparsed_uri);
   }
   virtual ~ShibTargetApache() {}
 
@@ -300,9 +329,6 @@ public:
   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;
   }
@@ -391,10 +417,6 @@ public:
     return m_body.c_str();
   }
   void clearHeader(const char* rawname, const char* cginame) {
-    if (m_dc->bUseEnvVars != 0) {
-       // ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_clear_header: env\n");
-       if (m_rc && m_rc->env) ap_table_unset(m_rc->env, rawname);
-    }
     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)) {
@@ -484,8 +506,11 @@ public:
         in.read(buf,1024);
         ap_rwrite(buf,in.gcount(),m_req);
     }
-    if (status!=XMLTOOLING_HTTP_STATUS_OK)
+    if (status != XMLTOOLING_HTTP_STATUS_OK) {
         m_req->status = status;
+        if (status != XMLTOOLING_HTTP_STATUS_ERROR)
+            return status;
+    }
     return DONE;
   }
   long sendRedirect(const char* url) {
@@ -544,12 +569,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)
@@ -589,12 +614,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
 }
 
 /*
@@ -619,19 +644,20 @@ extern "C" int shib_auth_checker(request_rec* r)
     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());
     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
@@ -642,7 +668,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;
 };
@@ -659,7 +685,7 @@ public:
     ~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;
+    Settings getSettings(const HTTPRequest& request) const;
     
     const PropertySet* getParent() const { return NULL; }
     void setParent(const PropertySet*) {}
@@ -668,6 +694,7 @@ public:
     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;
+    void getAll(map<string,const char*>& properties) const;
     const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:2.0:native:sp:config") const;
     const xercesc::DOMElement* getElement() const;
 
@@ -691,7 +718,7 @@ ApacheRequestMapper::ApacheRequestMapper(const xercesc::DOMElement* e) : m_mappe
     m_propsKey=ThreadKey::create(NULL);
 }
 
-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));
@@ -705,10 +732,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);
 }
@@ -734,6 +766,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);
 }
@@ -751,7 +788,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 pair<bool,unsigned int>(true, atoi(prop));
+        }
     }
     return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
 }
@@ -764,10 +806,45 @@ 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);
 }
 
+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";
+}
+
 const PropertySet* ApacheRequestMapper::getPropertySet(const char* name, const char* ns) const
 {
     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
@@ -834,30 +911,26 @@ 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"
-                    );
+                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;
 }
 
-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);
@@ -872,27 +945,21 @@ 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;
-    
-    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);
-
-    vector<bool> auth_OK(reqs_arr->nelts,false);
-
-#define SHIB_AP_CHECK_IS_OK {           \
-     if (sta->m_dc->bRequireAll < 1)    \
-         return true;                   \
-     auth_OK[x] = true;                 \
-     continue;                          \
-}
 
     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;
@@ -901,83 +968,135 @@ bool htAccessControl::authorized(const SPRequest& request, const Session* sessio
         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;
+            status = true;  // treat it as an "accepted" rule
         }
-        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");
+        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,negate=false;
             while (*t) {
                 w=ap_getword_conf(sta->m_req->pool,&t);
                 if (*w=='~') {
                     regexp=true;
                     continue;
                 }
-                
+                else if (*w=='!') {
+                    negate=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_ptr<XMLCh> trans(fromUTF8(w));
+                        auto_arrayptr<XMLCh> trans(fromUTF8(w));
                         RegularExpression re(trans.get());
-                        auto_ptr<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;
-                        }
+                        auto_arrayptr<XMLCh> trans2(fromUTF8(remote_user.c_str()));
+                        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;
+                    match = true;
+                }
+
+                if (match) {
+                    // If we matched, then we're done with this rule either way and status is set to reflect the outcome.
+                    status = !negate;
+                    if (request.isPriorityEnabled(SPRequest::SPDebug))
+                        request.log(SPRequest::SPDebug,
+                            string("htaccess: require user ") + (negate ? "rejecting (" : "accepting (") + remote_user + ")");
+                    break;
                 }
             }
         }
-        else if (!strcmp(w,"group")) {
+        else if (!strcmp(w,"group")  && !remote_user.empty()) {
             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);
+            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;
     
+            bool negate=false;
             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;
+                if (*w=='!') {
+                    negate=true;
+                    continue;
+                }
+
+                if (grpstatus && ap_table_get(grpstatus,w)) {
+                    // If we matched, then we're done with this rule either way and status is set to reflect the outcome.
+                    status = !negate;
+                    request.log(SPRequest::SPDebug, string("htaccess: require group ") + (negate ? "rejecting (" : "accepting (") + w + ")");
+                    break;
                 }
             }
         }
-        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;
+        else if (!strcmp(w,"authnContextClassRef") || !strcmp(w,"authnContextDeclRef")) {
+            const char* ref = !strcmp(w,"authnContextClassRef") ? session->getAuthnContextClassRef() : session->getAuthnContextDeclRef();
+            bool regexp=false,negate=false;
+            while (ref && *t) {
+                w=ap_getword_conf(sta->m_req->pool,&t);
+                if (*w=='~') {
+                    regexp=true;
+                    continue;
+                }
+                else if (*w=='!') {
+                    negate=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 status is set to reflect the outcome.
+                    status = !negate;
+                    if (request.isPriorityEnabled(SPRequest::SPDebug))
+                        request.log(SPRequest::SPDebug,
+                            string("htaccess: require authnContext ") + (negate ? "rejecting (" : "accepting (") + ref + ")");
+                    break;
+                }
             }
-            
+        }
+        else if (!session) {
+            request.log(SPRequest::SPError, string("htaccess: require ") + w + " not given a valid session, are you using lazy sessions?");
+        }
+        else {
             // 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;
@@ -988,36 +1107,67 @@ 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;
                     }
                     
-                    for (; !auth_OK[x] && attrs.first!=attrs.second; ++attrs.first) {
+                    for (; !status && attrs.first!=attrs.second; ++attrs.first) {
                         if (checkAttribute(request, attrs.first->second, w, regexp ? re.get() : NULL)) {
-                            SHIB_AP_CHECK_IS_OK;
+                            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.
     }
 
-    // check if all require directives are true
-    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;
+    }
+    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;
     }
-    if (auth_all_OK || !method_restricted)
-        return true;
 
-    return false;
+    request.log(SPRequest::SPDebug, "htaccess: no rules were successful but not authoritative, leaving it up to Apache");
+    return shib_acl_indeterminate;
 }
 
 
@@ -1110,14 +1260,20 @@ 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)) {
+    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);
+
+    if (!g_szSHIBConfig)
+        g_szSHIBConfig=getenv("SHIBSP_CONFIG");
+    if (!g_szSHIBConfig)
+        g_szSHIBConfig=SHIBSP_CONFIG;
     
     try {
         xercesc::DOMDocument* dummydoc=XMLToolingConfig::getConfig().getParser().newDocument();
@@ -1143,9 +1299,10 @@ 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;
+        pair<bool,bool> flag=props->getBool("checkSpoofing");
+        g_checkSpoofing = !flag.first || flag.second;
+        flag=props->getBool("catchAll");
+        g_catchAll = flag.first && flag.second;
     }
 
     // Set the cleanup handler
@@ -1218,6 +1375,8 @@ 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"},
   {"ShibCatalogs", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
@@ -1229,6 +1388,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"},
@@ -1256,6 +1418,9 @@ 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 attributes using environment variables (default)"},
@@ -1316,56 +1481,60 @@ 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("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"),
+    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,
+    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_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 attributes using environment variables (default)"),
-  AP_INIT_FLAG("ShibUseHeaders", (config_fn_t)ap_set_flag_slot,
+    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 = {