SSPCPP-506 - use lit to put the common objects into a library
[shibboleth/cpp-sp.git] / apache / mod_shib.cpp
1 /**
2  * Licensed to the University Corporation for Advanced Internet
3  * Development, Inc. (UCAID) under one or more contributor license
4  * agreements. See the NOTICE file distributed with this work for
5  * additional information regarding copyright ownership.
6  *
7  * UCAID licenses this file to you under the Apache License,
8  * Version 2.0 (the "License"); you may not use this file except
9  * in compliance with the License. You may obtain a copy of the
10  * License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing,
15  * software distributed under the License is distributed on an
16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17  * either express or implied. See the License for the specific
18  * language governing permissions and limitations under the License.
19  */
20
21 /**
22  * mod_shib.cpp
23  *
24  * Apache module implementation.
25  */
26
27 #define SHIBSP_LITE
28
29 #ifdef SOLARIS2
30 #undef _XOPEN_SOURCE    // causes gethostname conflict in unistd.h
31 #endif
32
33 #ifdef WIN32
34 # define _CRT_NONSTDC_NO_DEPRECATE 1
35 # define _CRT_SECURE_NO_DEPRECATE 1
36 #endif
37
38 #include <shibsp/exceptions.h>
39 #include <shibsp/AbstractSPRequest.h>
40 #include <shibsp/AccessControl.h>
41 #include <shibsp/GSSRequest.h>
42 #include <shibsp/RequestMapper.h>
43 #include <shibsp/SPConfig.h>
44 #include <shibsp/ServiceProvider.h>
45 #include <shibsp/SessionCache.h>
46 #include <shibsp/attribute/Attribute.h>
47
48 #include <xercesc/util/XMLUniDefs.hpp>
49 #include <xercesc/util/regx/RegularExpression.hpp>
50 #include <xmltooling/XMLToolingConfig.h>
51 #include <xmltooling/util/NDC.h>
52 #include <xmltooling/util/ParserPool.h>
53 #include <xmltooling/util/Threads.h>
54 #include <xmltooling/util/XMLConstants.h>
55 #include <xmltooling/util/XMLHelper.h>
56
57 #ifdef WIN32
58 # include <winsock2.h>
59 # include <ws2tcpip.h>
60 #endif
61
62 #undef _XPG4_2
63
64 #include <set>
65 #include <memory>
66 #include <fstream>
67 #include <stdexcept>
68 #include <boost/lexical_cast.hpp>
69
70 // Apache specific header files
71 #include <httpd.h>
72 #include <http_config.h>
73 #include <http_protocol.h>
74 #include <http_main.h>
75 #define CORE_PRIVATE
76 #include <http_core.h>
77 #include <http_log.h>
78 #include <http_request.h>
79
80 #ifndef SHIB_APACHE_13
81 #include <apr_buckets.h>
82 #include <apr_strings.h>
83 #include <apr_pools.h>
84 #endif
85
86 #ifdef SHIB_APACHE_24
87 #include <mod_auth.h>
88 #endif
89
90 #include <cstddef>
91 #ifdef HAVE_UNISTD_H
92 #include <unistd.h>             // for getpid()
93 #endif
94
95 using namespace shibsp;
96 using namespace xmltooling;
97 using namespace boost;
98 using namespace std;
99 using xercesc::RegularExpression;
100 using xercesc::XMLException;
101
102 #ifdef APLOG_USE_MODULE
103     extern "C" module AP_MODULE_DECLARE_DATA mod_shib;
104     static int* const aplog_module_index = &(mod_shib.module_index);
105 #else
106     extern "C" module MODULE_VAR_EXPORT mod_shib;
107 #endif
108
109 namespace {
110     char* g_szSHIBConfig = nullptr;
111     char* g_szSchemaDir = nullptr;
112     char* g_szPrefix = nullptr;
113     SPConfig* g_Config = nullptr;
114     string g_unsetHeaderValue,g_spoofKey;
115     bool g_checkSpoofing = true;
116     bool g_catchAll = false;
117 #ifndef SHIB_APACHE_13
118     char* g_szGSSContextKey = "mod_auth_gssapi:gss_ctx";
119 #endif
120     static const char* g_UserDataKey = "urn:mace:shibboleth:Apache:shib_check_user";
121 }
122
123 /* Apache 2.2.x headers must be accumulated and set in the output filter.
124    Apache 2.0.49+ supports the filter method.
125    Apache 1.3.x and lesser 2.0.x must write the headers directly. */
126
127 #if (defined(SHIB_APACHE_20) || defined(SHIB_APACHE_22) || defined(SHIB_APACHE_24)) && AP_MODULE_MAGIC_AT_LEAST(20020903,6)
128 #define SHIB_DEFERRED_HEADERS
129 #endif
130
131 /********************************************************************************/
132 // Basic Apache Configuration code.
133 //
134
135 // per-server module configuration structure
136 struct shib_server_config
137 {
138     char* szScheme;
139 };
140
141 // creates the per-server configuration
142 extern "C" void* create_shib_server_config(SH_AP_POOL* p, server_rec* s)
143 {
144     shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
145     sc->szScheme = nullptr;
146     return sc;
147 }
148
149 // overrides server configuration in virtual servers
150 extern "C" void* merge_shib_server_config (SH_AP_POOL* p, void* base, void* sub)
151 {
152     shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
153     shib_server_config* parent=(shib_server_config*)base;
154     shib_server_config* child=(shib_server_config*)sub;
155
156     if (child->szScheme)
157         sc->szScheme=ap_pstrdup(p,child->szScheme);
158     else if (parent->szScheme)
159         sc->szScheme=ap_pstrdup(p,parent->szScheme);
160     else
161         sc->szScheme=nullptr;
162
163     return sc;
164 }
165
166 // per-dir module configuration structure
167 struct shib_dir_config
168 {
169     SH_AP_TABLE* tSettings; // generic table of extensible settings
170
171     // RM Configuration
172 #ifdef SHIB_APACHE_24
173     int bRequestMapperAuthz;// support RequestMapper AccessControl plugins
174 #else
175     char* szAuthGrpFile;    // Auth GroupFile name
176         char* szAccessControl;  // path to "external" AccessControl plugin file
177     int bRequireAll;        // all "known" require directives must match, otherwise OR logic
178     int bAuthoritative;     // allow htaccess plugin to DECLINE when authz fails
179     int bCompatWith24;      // support 2.4-reserved require logic for compatibility
180 #endif
181
182     // Content Configuration
183     char* szApplicationId;  // Shib applicationId value
184     char* szRequireWith;    // require a session using a specific initiator?
185     char* szRedirectToSSL;  // redirect non-SSL requests to SSL port
186     int bOff;               // flat-out disable all Shib processing
187     int bBasicHijack;       // activate for AuthType Basic?
188     int bRequireSession;    // require a session?
189     int bExportAssertion;   // export SAML assertion to the environment?
190     int bUseEnvVars;        // use environment?
191     int bUseHeaders;        // use headers?
192     int bExpireRedirects;   // expire redirects?
193 };
194
195 // creates per-directory config structure
196 extern "C" void* create_shib_dir_config (SH_AP_POOL* p, char* d)
197 {
198     shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
199     dc->tSettings = nullptr;
200 #ifdef SHIB_APACHE_24
201     dc->bRequestMapperAuthz = -1;
202 #else
203     dc->szAuthGrpFile = nullptr;
204         dc->szAccessControl = nullptr;
205     dc->bRequireAll = -1;
206     dc->bAuthoritative = -1;
207     dc->bCompatWith24 = -1;
208 #endif
209     dc->szApplicationId = nullptr;
210     dc->szRequireWith = nullptr;
211     dc->szRedirectToSSL = nullptr;
212     dc->bOff = -1;
213     dc->bBasicHijack = -1;
214     dc->bRequireSession = -1;
215     dc->bExportAssertion = -1;
216     dc->bUseEnvVars = -1;
217     dc->bUseHeaders = -1;
218     dc->bExpireRedirects = -1;
219     return dc;
220 }
221
222 // overrides server configuration in directories
223 extern "C" void* merge_shib_dir_config (SH_AP_POOL* p, void* base, void* sub)
224 {
225     shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
226     shib_dir_config* parent=(shib_dir_config*)base;
227     shib_dir_config* child=(shib_dir_config*)sub;
228
229     // The child supersedes any matching table settings in the parent.
230     dc->tSettings = nullptr;
231     if (parent->tSettings)
232         dc->tSettings = ap_copy_table(p, parent->tSettings);
233     if (child->tSettings) {
234         if (dc->tSettings)
235             ap_overlap_tables(dc->tSettings, child->tSettings, AP_OVERLAP_TABLES_SET);
236         else
237             dc->tSettings = ap_copy_table(p, child->tSettings);
238     }
239
240 #ifdef SHIB_APACHE_24
241     dc->bRequestMapperAuthz = ((child->bRequestMapperAuthz==-1) ? parent->bRequestMapperAuthz : child->bRequestMapperAuthz);
242 #else
243     if (child->szAuthGrpFile)
244         dc->szAuthGrpFile=ap_pstrdup(p,child->szAuthGrpFile);
245     else if (parent->szAuthGrpFile)
246         dc->szAuthGrpFile=ap_pstrdup(p,parent->szAuthGrpFile);
247     else
248         dc->szAuthGrpFile=nullptr;
249
250         if (child->szAccessControl)
251         dc->szAccessControl=ap_pstrdup(p,child->szAccessControl);
252     else if (parent->szAccessControl)
253         dc->szAccessControl=ap_pstrdup(p,parent->szAccessControl);
254     else
255         dc->szAccessControl=nullptr;
256 #endif
257
258     if (child->szApplicationId)
259         dc->szApplicationId=ap_pstrdup(p,child->szApplicationId);
260     else if (parent->szApplicationId)
261         dc->szApplicationId=ap_pstrdup(p,parent->szApplicationId);
262     else
263         dc->szApplicationId=nullptr;
264
265     if (child->szRequireWith)
266         dc->szRequireWith=ap_pstrdup(p,child->szRequireWith);
267     else if (parent->szRequireWith)
268         dc->szRequireWith=ap_pstrdup(p,parent->szRequireWith);
269     else
270         dc->szRequireWith=nullptr;
271
272     if (child->szRedirectToSSL)
273         dc->szRedirectToSSL=ap_pstrdup(p,child->szRedirectToSSL);
274     else if (parent->szRedirectToSSL)
275         dc->szRedirectToSSL=ap_pstrdup(p,parent->szRedirectToSSL);
276     else
277         dc->szRedirectToSSL=nullptr;
278
279     dc->bOff = ((child->bOff==-1) ? parent->bOff : child->bOff);
280     dc->bBasicHijack = ((child->bBasicHijack==-1) ? parent->bBasicHijack : child->bBasicHijack);
281     dc->bRequireSession = ((child->bRequireSession==-1) ? parent->bRequireSession : child->bRequireSession);
282     dc->bExportAssertion = ((child->bExportAssertion==-1) ? parent->bExportAssertion : child->bExportAssertion);
283 #ifndef SHIB_APACHE_24
284     dc->bRequireAll = ((child->bRequireAll==-1) ? parent->bRequireAll : child->bRequireAll);
285     dc->bAuthoritative = ((child->bAuthoritative==-1) ? parent->bAuthoritative : child->bAuthoritative);
286     dc->bCompatWith24 = ((child->bCompatWith24==-1) ? parent->bCompatWith24 : child->bCompatWith24);
287 #endif
288     dc->bUseEnvVars = ((child->bUseEnvVars==-1) ? parent->bUseEnvVars : child->bUseEnvVars);
289     dc->bUseHeaders = ((child->bUseHeaders==-1) ? parent->bUseHeaders : child->bUseHeaders);
290     dc->bExpireRedirects = ((child->bExpireRedirects==-1) ? parent->bExpireRedirects : child->bExpireRedirects);
291     return dc;
292 }
293
294 class ShibTargetApache; // forward decl
295
296 // per-request module structure
297 struct shib_request_config
298 {
299     SH_AP_TABLE* env;        // environment vars
300 #ifdef SHIB_DEFERRED_HEADERS
301     SH_AP_TABLE* hdr_out;    // headers to browser
302 #endif
303 #ifndef SHIB_APACHE_13
304     ShibTargetApache* sta;  // SP per-request structure wrapped around Apache's request
305 #endif
306 };
307
308 // create a request record
309 static shib_request_config* init_request_config(request_rec *r)
310 {
311     ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "init_request_config");
312     shib_request_config* rc = (shib_request_config*)ap_pcalloc(r->pool,sizeof(shib_request_config));
313     memset(rc, 0, sizeof(shib_request_config));
314     ap_set_module_config(r->request_config, &mod_shib, rc);
315     return rc;
316 }
317
318 class ShibTargetApache : public AbstractSPRequest
319 #if defined(SHIBSP_HAVE_GSSAPI) && !defined(SHIB_APACHE_13)
320     , public GSSRequest
321 #endif
322 {
323   mutable string m_body;
324   mutable bool m_gotBody,m_firsttime;
325   mutable vector<string> m_certs;
326   set<string> m_allhttp;
327 #if defined(SHIBSP_HAVE_GSSAPI) && !defined(SHIB_APACHE_13)
328   mutable gss_name_t m_gssname;
329 #endif
330
331 public:
332   bool m_handler;
333   request_rec* m_req;
334   shib_dir_config* m_dc;
335   shib_server_config* m_sc;
336   shib_request_config* m_rc;
337
338   ShibTargetApache(request_rec* req) : AbstractSPRequest(SHIBSP_LOGCAT".Apache"),
339         m_gotBody(false),m_firsttime(true),
340 #if defined(SHIBSP_HAVE_GSSAPI) && !defined(SHIB_APACHE_13)
341         m_gssname(GSS_C_NO_NAME),
342 #endif
343         m_handler(false), m_req(req), m_dc(nullptr), m_sc(nullptr), m_rc(nullptr) {
344   }
345   virtual ~ShibTargetApache() {
346 #if defined(SHIBSP_HAVE_GSSAPI) && !defined(SHIB_APACHE_13)
347     if (m_gssname != GSS_C_NO_NAME) {
348         OM_uint32 minor;
349         gss_release_name(&minor, &m_gssname);
350     }
351 #endif
352   }
353
354   bool isInitialized() const {
355       return (m_sc != nullptr);
356   }
357
358   bool init(bool handler, bool check_user) {
359     m_handler = handler;
360     if (m_sc)
361         return !check_user; // only initialize once
362     m_sc = (shib_server_config*)ap_get_module_config(m_req->server->module_config, &mod_shib);
363     m_dc = (shib_dir_config*)ap_get_module_config(m_req->per_dir_config, &mod_shib);
364     m_rc = (shib_request_config*)ap_get_module_config(m_req->request_config, &mod_shib);
365
366     setRequestURI(m_req->unparsed_uri);
367
368     if (check_user && m_dc->bUseHeaders == 1) {
369         // Try and see if this request was already processed, to skip spoof checking.
370         if (!ap_is_initial_req(m_req)) {
371             m_firsttime = false;
372         }
373         else if (!g_spoofKey.empty()) {
374             const char* hdr = ap_table_get(m_req->headers_in, "Shib-Spoof-Check");
375             if (hdr && g_spoofKey == hdr)
376                 m_firsttime = false;
377         }
378         if (!m_firsttime)
379             log(SPDebug, "shib_check_user running more than once");
380     }
381     return true;
382   }
383
384   const char* getScheme() const {
385     return m_sc->szScheme ? m_sc->szScheme : ap_http_method(m_req);
386   }
387   bool isSecure() const {
388       return HTTPRequest::isSecure();
389   }
390   const char* getHostname() const {
391 #ifdef SHIB_APACHE_24
392       return ap_get_server_name_for_url(m_req);
393 #else
394       return ap_get_server_name(m_req);
395 #endif
396   }
397   int getPort() const {
398     return ap_get_server_port(m_req);
399   }
400   const char* getMethod() const {
401     return m_req->method;
402   }
403   string getContentType() const {
404     const char* type = ap_table_get(m_req->headers_in, "Content-Type");
405     return type ? type : "";
406   }
407   long getContentLength() const {
408       return m_gotBody ? m_body.length() : m_req->remaining;
409   }
410   string getRemoteAddr() const {
411     string ret = AbstractSPRequest::getRemoteAddr();
412     if (!ret.empty())
413         return ret;
414 #ifdef SHIB_APACHE_24
415     return m_req->useragent_ip;
416 #else
417     return m_req->connection->remote_ip;
418 #endif
419   }
420   void log(SPLogLevel level, const string& msg) const {
421     AbstractSPRequest::log(level,msg);
422     ap_log_rerror(
423         APLOG_MARK,
424         (level == SPDebug ? APLOG_DEBUG :
425         (level == SPInfo ? APLOG_INFO :
426         (level == SPWarn ? APLOG_WARNING :
427         (level == SPError ? APLOG_ERR : APLOG_CRIT))))|APLOG_NOERRNO,
428         SH_AP_R(m_req),
429         "%s",
430         msg.c_str()
431         );
432   }
433   const char* getQueryString() const { return m_req->args; }
434   const char* getRequestBody() const {
435     if (m_gotBody || m_req->method_number==M_GET)
436         return m_body.c_str();
437 #ifdef SHIB_APACHE_13
438     // Read the posted data
439     if (ap_setup_client_block(m_req, REQUEST_CHUNKED_DECHUNK) != OK) {
440         m_gotBody=true;
441         log(SPError, "Apache function (setup_client_block) failed while reading request body.");
442         return m_body.c_str();
443     }
444     if (!ap_should_client_block(m_req)) {
445         m_gotBody=true;
446         log(SPError, "Apache function (should_client_block) failed while reading request body.");
447         return m_body.c_str();
448     }
449     if (m_req->remaining > 1024*1024)
450         throw opensaml::SecurityPolicyException("Blocked request body larger than 1M size limit.");
451     m_gotBody=true;
452     int len;
453     char buff[HUGE_STRING_LEN];
454     ap_hard_timeout("[mod_shib] getRequestBody", m_req);
455     while ((len=ap_get_client_block(m_req, buff, sizeof(buff))) > 0) {
456       ap_reset_timeout(m_req);
457       m_body.append(buff, len);
458     }
459     ap_kill_timeout(m_req);
460 #else
461     const char *data;
462     apr_size_t len;
463     int seen_eos = 0;
464     apr_bucket_brigade* bb = apr_brigade_create(m_req->pool, m_req->connection->bucket_alloc);
465     do {
466         apr_bucket *bucket;
467         apr_status_t rv = ap_get_brigade(m_req->input_filters, bb, AP_MODE_READBYTES, APR_BLOCK_READ, HUGE_STRING_LEN);
468         if (rv != APR_SUCCESS) {
469             log(SPError, "Apache function (ap_get_brigade) failed while reading request body.");
470             break;
471         }
472
473         for (bucket = APR_BRIGADE_FIRST(bb); bucket != APR_BRIGADE_SENTINEL(bb); bucket = APR_BUCKET_NEXT(bucket)) {
474             if (APR_BUCKET_IS_EOS(bucket)) {
475                 seen_eos = 1;
476                 break;
477             }
478
479             /* We can't do much with this. */
480             if (APR_BUCKET_IS_FLUSH(bucket))
481                 continue;
482
483             /* read */
484             apr_bucket_read(bucket, &data, &len, APR_BLOCK_READ);
485             if (len > 0)
486                 m_body.append(data, len);
487         }
488         apr_brigade_cleanup(bb);
489     } while (!seen_eos);
490     apr_brigade_destroy(bb);
491     m_gotBody=true;
492 #endif
493     return m_body.c_str();
494   }
495   const char* getParameter(const char* name) const {
496       return AbstractSPRequest::getParameter(name);
497   }
498   vector<const char*>::size_type getParameters(const char* name, vector<const char*>& values) const {
499       return AbstractSPRequest::getParameters(name, values);
500   }
501   void clearHeader(const char* rawname, const char* cginame) {
502     if (m_dc->bUseHeaders == 1) {
503        // ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_clear_header: hdr\n");
504         if (g_checkSpoofing && m_firsttime) {
505             if (m_allhttp.empty()) {
506                 // First time, so populate set with "CGI" versions of client-supplied headers.
507 #ifdef SHIB_APACHE_13
508                 array_header *hdrs_arr = ap_table_elts(m_req->headers_in);
509                 table_entry *hdrs = (table_entry *) hdrs_arr->elts;
510 #else
511                 const apr_array_header_t *hdrs_arr = apr_table_elts(m_req->headers_in);
512                 const apr_table_entry_t *hdrs = (const apr_table_entry_t *) hdrs_arr->elts;
513 #endif
514                 for (int i = 0; i < hdrs_arr->nelts; ++i) {
515                     if (!hdrs[i].key)
516                         continue;
517                     string cgiversion("HTTP_");
518                     const char* pch = hdrs[i].key;
519                     while (*pch) {
520                         cgiversion += (isalnum(*pch) ? toupper(*pch) : '_');
521                         pch++;
522                     }
523                     m_allhttp.insert(cgiversion);
524                 }
525             }
526
527             if (m_allhttp.count(cginame) > 0)
528                 throw opensaml::SecurityPolicyException("Attempt to spoof header ($1) was detected.", params(1, rawname));
529         }
530         ap_table_unset(m_req->headers_in, rawname);
531         ap_table_set(m_req->headers_in, rawname, g_unsetHeaderValue.c_str());
532     }
533   }
534   void setHeader(const char* name, const char* value) {
535     if (m_dc->bUseEnvVars != 0) {
536        if (!m_rc) {
537           // this happens on subrequests
538           // ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_setheader: no_m_rc\n");
539           m_rc = init_request_config(m_req);
540        }
541        if (!m_rc->env)
542            m_rc->env = ap_make_table(m_req->pool, 10);
543        // ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_set_env: %s=%s\n", name, value?value:"Null");
544        ap_table_set(m_rc->env, name, value ? value : "");
545     }
546     if (m_dc->bUseHeaders == 1)
547        ap_table_set(m_req->headers_in, name, value);
548   }
549   string getHeader(const char* name) const {
550     const char* hdr = ap_table_get(m_req->headers_in, name);
551     return string(hdr ? hdr : "");
552   }
553   string getSecureHeader(const char* name) const {
554     if (m_dc->bUseEnvVars != 0) {
555        const char *hdr;
556        if (m_rc && m_rc->env)
557            hdr = ap_table_get(m_rc->env, name);
558        else
559            hdr = nullptr;
560        return string(hdr ? hdr : "");
561     }
562     return getHeader(name);
563   }
564   void setRemoteUser(const char* user) {
565       SH_AP_USER(m_req) = user ? ap_pstrdup(m_req->pool, user) : nullptr;
566       if (m_dc->bUseHeaders == 1) {
567           if (user) {
568               ap_table_set(m_req->headers_in, "REMOTE_USER", user);
569           }
570           else {
571               ap_table_unset(m_req->headers_in, "REMOTE_USER");
572               ap_table_set(m_req->headers_in, "REMOTE_USER", g_unsetHeaderValue.c_str());
573           }
574       }
575   }
576   string getRemoteUser() const {
577     return string(SH_AP_USER(m_req) ? SH_AP_USER(m_req) : "");
578   }
579   void setAuthType(const char* authtype) {
580       if (authtype && m_dc->bBasicHijack == 1)
581           authtype = "Basic";
582       SH_AP_AUTH_TYPE(m_req) = authtype ? ap_pstrdup(m_req->pool, authtype) : nullptr;
583   }
584   string getAuthType() const {
585     return string(SH_AP_AUTH_TYPE(m_req) ? SH_AP_AUTH_TYPE(m_req) : "");
586   }
587   void setContentType(const char* type) {
588       m_req->content_type = ap_psprintf(m_req->pool, "%s", type);
589   }
590   void setResponseHeader(const char* name, const char* value) {
591    HTTPResponse::setResponseHeader(name, value);
592 #ifdef SHIB_DEFERRED_HEADERS
593    if (!m_rc)
594       // this happens on subrequests
595       m_rc = init_request_config(m_req);
596     if (m_handler) {
597         if (!m_rc->hdr_out)
598             m_rc->hdr_out = ap_make_table(m_req->pool, 5);
599         ap_table_add(m_rc->hdr_out, name, value);
600     }
601     else
602 #endif
603     ap_table_add(m_req->err_headers_out, name, value);
604   }
605   long sendResponse(istream& in, long status) {
606     if (status != XMLTOOLING_HTTP_STATUS_OK)
607         m_req->status = status;
608     ap_send_http_header(m_req);
609     char buf[1024];
610     while (in) {
611         in.read(buf,1024);
612         ap_rwrite(buf,in.gcount(),m_req);
613     }
614 #if (defined(SHIB_APACHE_20) || defined(SHIB_APACHE_22) || defined(SHIB_APACHE_24))
615     if (status != XMLTOOLING_HTTP_STATUS_OK && status != XMLTOOLING_HTTP_STATUS_ERROR)
616         return status;
617 #endif
618     return DONE;
619   }
620   long sendRedirect(const char* url) {
621     HTTPResponse::sendRedirect(url);
622     ap_table_set(m_req->headers_out, "Location", url);
623     if (m_dc->bExpireRedirects != 0) {
624         ap_table_set(m_req->err_headers_out, "Expires", "Wed, 01 Jan 1997 12:00:00 GMT");
625         ap_table_set(m_req->err_headers_out, "Cache-Control", "private,no-store,no-cache,max-age=0");
626     }
627     return REDIRECT;
628   }
629   const vector<string>& getClientCertificates() const {
630       if (m_certs.empty()) {
631           const char* cert = ap_table_get(m_req->subprocess_env, "SSL_CLIENT_CERT");
632           if (cert)
633               m_certs.push_back(cert);
634           int i = 0;
635           do {
636               cert = ap_table_get(m_req->subprocess_env, ap_psprintf(m_req->pool, "SSL_CLIENT_CERT_CHAIN_%d", i++));
637               if (cert)
638                   m_certs.push_back(cert);
639           } while (cert);
640       }
641       return m_certs;
642   }
643   long returnDecline(void) { return DECLINED; }
644   long returnOK(void) { return OK; }
645 #if defined(SHIBSP_HAVE_GSSAPI) && !defined(SHIB_APACHE_13)
646   gss_ctx_id_t getGSSContext() const {
647     gss_ctx_id_t ctx = GSS_C_NO_CONTEXT;
648     apr_pool_userdata_get((void**)&ctx, g_szGSSContextKey, m_req->pool);
649     return ctx;
650   }
651   gss_name_t getGSSName() const {
652       if (m_gssname == GSS_C_NO_NAME) {
653           gss_ctx_id_t ctx = getGSSContext();
654           if (ctx != GSS_C_NO_CONTEXT) {
655               OM_uint32 minor;
656               OM_uint32 major = gss_inquire_context(&minor, ctx, &m_gssname, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr);
657               if (major != GSS_S_COMPLETE)
658                   m_gssname = GSS_C_NO_NAME;
659           }
660       }
661       return m_gssname;
662   }
663   #endif
664 };
665
666 /********************************************************************************/
667 // Apache hooks
668
669 #ifndef SHIB_APACHE_13
670 extern "C" apr_status_t shib_request_cleanup(void* r)
671 {
672     if (r)
673         delete reinterpret_cast<ShibTargetApache*>(r);
674     return APR_SUCCESS;
675 }
676 #endif
677
678 // Initial look at a request - create the per-request structure
679 static int shib_post_read(request_rec *r)
680 {
681     shib_request_config* rc = init_request_config(r);
682 #ifdef SHIB_APACHE_24
683     rc->sta = new ShibTargetApache(r);
684     apr_pool_cleanup_register(r->pool, rc->sta, shib_request_cleanup, apr_pool_cleanup_null);
685 #endif
686     return DECLINED;
687 }
688
689 // Performs authentication and enforce session requirements.
690 // Also does header/env export from session, and will dispatch
691 // SP handler requests if it detects a handler URL.
692 extern "C" int shib_check_user(request_rec* r)
693 {
694     // Short-circuit entirely?
695     if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff == 1)
696         return DECLINED;
697
698     ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user entered in pid (%d)", (int)getpid());
699
700     string threadid("[");
701     threadid += lexical_cast<string>(getpid()) + "] shib_check_user";
702     xmltooling::NDC ndc(threadid.c_str());
703
704     try {
705 #ifndef SHIB_APACHE_24
706         ShibTargetApache sta(r);
707         ShibTargetApache* psta = &sta;
708 #else
709         shib_request_config* rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
710         if (!rc || !rc->sta) {
711             ap_log_rerror(APLOG_MARK, APLOG_INFO|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user found no per-request structure");
712             shib_post_read(r);  // ensures objects are created if post_read hook didn't run
713             rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
714         }
715         ShibTargetApache* psta = rc->sta;
716 #endif
717         if (!psta->init(false, true)) {
718             ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user unable to initialize SP request object");
719             return SERVER_ERROR;
720         }
721
722         // Check user authentication and export information, then set the handler bypass
723         pair<bool,long> res = psta->getServiceProvider().doAuthentication(*psta, true);
724         apr_pool_userdata_setn((const void*)42,g_UserDataKey,nullptr,r->pool);
725         // If directed, install a spoof key to recognize when we've already cleared headers.
726         if (!g_spoofKey.empty() && (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bUseHeaders == 1))
727             ap_table_set(r->headers_in, "Shib-Spoof-Check", g_spoofKey.c_str());
728         if (res.first) {
729 #ifdef SHIB_APACHE_24
730             // This is insane, but Apache's internal request.c logic insists that an auth module
731             // returning OK MUST set r->user to avoid a failure. But they check for NULL and not
732             // for an empty string. If this turns out to cause trouble, there's no solution except
733             // to set a dummy ID any time it's not set.
734             if (res.second == OK && !r->user)
735                 r->user = "";
736 #endif
737             return res.second;
738         }
739
740         // user auth was okay -- export the session data now
741         res = psta->getServiceProvider().doExport(*psta);
742         if (res.first) {
743 #ifdef SHIB_APACHE_24
744             // See above for explanation of this hack.
745             if (res.second == OK && !r->user)
746                 r->user = "";
747 #endif
748             return res.second;
749         }
750
751 #ifdef SHIB_APACHE_24
752         // See above for explanation of this hack.
753         if (!r->user)
754             r->user = "";
755 #endif
756         return OK;
757     }
758     catch (std::exception& e) {
759         ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user threw an exception: %s", e.what());
760         return SERVER_ERROR;
761     }
762     catch (...) {
763         ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user threw an unknown exception!");
764         if (g_catchAll)
765             return SERVER_ERROR;
766         throw;
767     }
768 }
769
770 // Runs SP handler requests when invoked directly.
771 extern "C" int shib_handler(request_rec* r)
772 {
773     // Short-circuit entirely?
774     if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff == 1)
775         return DECLINED;
776
777     string threadid("[");
778     threadid += lexical_cast<string>(getpid()) + "] shib_handler";
779     xmltooling::NDC ndc(threadid.c_str());
780
781 #ifndef SHIB_APACHE_13
782     // With 2.x, this handler always runs, though last.
783     // We check if shib_check_user ran, because it will detect a handler request
784     // and dispatch it directly.
785     void* data;
786     apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
787     if (data==(const void*)42) {
788         ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "shib_handler skipped since check_user ran");
789         return DECLINED;
790     }
791 #endif
792
793     ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "shib_handler entered in pid (%d): %s", (int)getpid(), r->handler);
794
795     try {
796 #ifndef SHIB_APACHE_24
797         ShibTargetApache sta(r);
798         ShibTargetApache* psta = &sta;
799 #else
800         shib_request_config* rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
801         if (!rc || !rc->sta) {
802             ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler found no per-request structure");
803             return SERVER_ERROR;
804         }
805         ShibTargetApache* psta = rc->sta;
806 #endif
807         if (!psta->init(true, false)) {
808             ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler unable to initialize SP request object");
809             return SERVER_ERROR;
810         }
811
812         pair<bool,long> res = psta->getServiceProvider().doHandler(*psta);
813         if (res.first) return res.second;
814
815         ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "doHandler() did not handle the request");
816         return SERVER_ERROR;
817     }
818     catch (std::exception& e) {
819         ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler threw an exception: %s", e.what());
820         return SERVER_ERROR;
821     }
822     catch (...) {
823         ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler threw an unknown exception!");
824         if (g_catchAll)
825           return SERVER_ERROR;
826         throw;
827     }
828 }
829
830 // This performs authorization functions to limit access.
831 // On all versions, this runs any RequestMap-attached plugins.
832 // For pre-2.4 versions, the RequestMap will always find an htAccess plugin
833 // that runs code to parse and enforce Apache Require rules.
834 // On 2.4, we have to short-circuit that and let Apache run callbacks
835 // for each Require rule we handle.
836 extern "C" int shib_auth_checker(request_rec* r)
837 {
838     // Short-circuit entirely?
839     shib_dir_config* dc = (shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib);
840     if (dc->bOff == 1
841 #ifdef SHIB_APACHE_24
842         || dc->bRequestMapperAuthz == 0     // this allows for bypass of the full auth_checker hook if only htaccess is used
843 #endif
844         ) {
845         return DECLINED;
846     }
847
848     ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker entered in pid (%d)", (int)getpid());
849
850     string threadid("[");
851     threadid += lexical_cast<string>(getpid()) + "] shib_auth_checker";
852     xmltooling::NDC ndc(threadid.c_str());
853
854     try {
855 #ifndef SHIB_APACHE_24
856         ShibTargetApache sta(r);
857         ShibTargetApache* psta = &sta;
858 #else
859         shib_request_config* rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
860         if (!rc || !rc->sta) {
861             ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker found no per-request structure");
862             return SERVER_ERROR;
863         }
864         ShibTargetApache* psta = rc->sta;
865 #endif
866         if (!psta->init(false, false)) {
867             ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker unable to initialize SP request object");
868             return SERVER_ERROR;
869         }
870
871         pair<bool,long> res = psta->getServiceProvider().doAuthorization(*psta);
872         if (res.first) return res.second;
873
874         // The SP method should always return true, so if we get this far, something unusual happened.
875         // Just let Apache (or some other module) decide what to do.
876         return DECLINED;
877     }
878     catch (std::exception& e) {
879         ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an exception: %s", e.what());
880         return SERVER_ERROR;
881     }
882     catch (...) {
883         ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an unknown exception!");
884         if (g_catchAll)
885           return SERVER_ERROR;
886         throw;
887     }
888 }
889
890 // Overlays environment variables on top of subprocess table.
891 extern "C" int shib_fixups(request_rec* r)
892 {
893     shib_dir_config *dc = (shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib);
894     if (dc->bOff==1 || dc->bUseEnvVars==0)
895         return DECLINED;
896
897     ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "shib_fixups entered in pid (%d)", (int)getpid());
898
899     shib_request_config *rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
900     if (rc==nullptr || rc->env==nullptr || ap_is_empty_table(rc->env))
901         return DECLINED;
902
903     ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "shib_fixups adding %d vars", ap_table_elts(rc->env)->nelts);
904     r->subprocess_env = ap_overlay_tables(r->pool, r->subprocess_env, rc->env);
905
906     return OK;
907 }
908
909
910 // Access control plugin that enforces pre-2.4 htaccess rules.
911 // Post-2.4, we have to register individual methods to respond
912 // to each require rule we want to handle, and have those call
913 // into these methods directly.
914 class htAccessControl : virtual public AccessControl
915 {
916 public:
917     htAccessControl() {}
918     ~htAccessControl() {}
919     Lockable* lock() {return this;}
920     void unlock() {}
921     aclresult_t authorized(const SPRequest& request, const Session* session) const;
922
923     aclresult_t doAccessControl(const ShibTargetApache& sta, const Session* session, const char* plugin) const;
924     aclresult_t doUser(const ShibTargetApache& sta, const char* params) const;
925 #ifndef SHIB_APACHE_24
926     aclresult_t doGroup(const ShibTargetApache& sta, const char* params) const;
927 #endif
928     aclresult_t doAuthnContext(const ShibTargetApache& sta, const char* acRef, const char* params) const;
929     aclresult_t doShibAttr(const ShibTargetApache& sta, const Session* session, const char* rule, const char* params) const;
930
931 private:
932     bool checkAttribute(const SPRequest& request, const Attribute* attr, const char* toMatch, RegularExpression* re) const;
933 };
934
935 AccessControl* htAccessFactory(const xercesc::DOMElement* const & e)
936 {
937     return new htAccessControl();
938 }
939
940 AccessControl::aclresult_t htAccessControl::doAccessControl(const ShibTargetApache& sta, const Session* session, const char* plugin) const
941 {
942         aclresult_t result = shib_acl_false;
943         try {
944         ifstream aclfile(plugin);
945         if (!aclfile)
946             throw ConfigurationException("Unable to open access control file ($1).", params(1, plugin));
947         xercesc::DOMDocument* acldoc = XMLToolingConfig::getConfig().getParser().parse(aclfile);
948                 XercesJanitor<xercesc::DOMDocument> docjanitor(acldoc);
949                 static XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
950         string t(XMLHelper::getAttrString(acldoc ? acldoc->getDocumentElement() : nullptr, nullptr, _type));
951         if (t.empty())
952             throw ConfigurationException("Missing type attribute in AccessControl plugin configuration.");
953         scoped_ptr<AccessControl> aclplugin(SPConfig::getConfig().AccessControlManager.newPlugin(t.c_str(), acldoc->getDocumentElement()));
954                 Locker acllock(aclplugin.get());
955                 result = aclplugin->authorized(sta, session);
956         }
957         catch (std::exception& ex) {
958                 sta.log(SPRequest::SPError, ex.what());
959         }
960     return result;
961 }
962
963 AccessControl::aclresult_t htAccessControl::doUser(const ShibTargetApache& sta, const char* params) const
964 {
965     bool regexp = false;
966     bool negated = false;
967     while (*params) {
968         const char* w = ap_getword_conf(sta.m_req->pool, &params);
969         if (*w == '~') {
970             regexp = true;
971             continue;
972         }
973         else if (*w == '!') {
974             // A negated rule presumes success unless a match is found.
975             negated = true;
976             if (*(w+1) == '~')
977                 regexp = true;
978             continue;
979         }
980
981         // Figure out if there's a match.
982         bool match = false;
983         if (regexp) {
984             try {
985                 // To do regex matching, we have to convert from UTF-8.
986                 auto_arrayptr<XMLCh> trans(fromUTF8(w));
987                 RegularExpression re(trans.get());
988                 auto_arrayptr<XMLCh> trans2(fromUTF8(sta.getRemoteUser().c_str()));
989                 match = re.matches(trans2.get());
990             }
991             catch (XMLException& ex) {
992                 auto_ptr_char tmp(ex.getMessage());
993                 sta.log(SPRequest::SPError,
994                     string("htaccess plugin caught exception while parsing regular expression (") + w + "): " + tmp.get());
995             }
996         }
997         else if (sta.getRemoteUser() == w) {
998             match = true;
999         }
1000
1001         if (match) {
1002             if (sta.isPriorityEnabled(SPRequest::SPDebug))
1003                 sta.log(SPRequest::SPDebug,
1004                     string("htaccess: require user ") + (negated ? "rejecting (" : "accepting (") + sta.getRemoteUser() + ")");
1005             return (negated ? shib_acl_false : shib_acl_true);
1006         }
1007     }
1008     return (negated ? shib_acl_true : shib_acl_false);
1009 }
1010
1011 #ifndef SHIB_APACHE_24
1012 static SH_AP_TABLE* groups_for_user(request_rec* r, const char* user, char* grpfile)
1013 {
1014     SH_AP_CONFIGFILE* f;
1015     SH_AP_TABLE* grps=ap_make_table(r->pool,15);
1016     char l[MAX_STRING_LEN];
1017     const char *group_name, *ll, *w;
1018
1019 #ifdef SHIB_APACHE_13
1020     if (!(f=ap_pcfg_openfile(r->pool, grpfile))) {
1021 #else
1022     if (ap_pcfg_openfile(&f,r->pool,grpfile) != APR_SUCCESS) {
1023 #endif
1024         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, SH_AP_R(r), "groups_for_user: could not open group file: %s\n", grpfile);
1025         return nullptr;
1026     }
1027
1028     SH_AP_POOL* sp;
1029 #ifdef SHIB_APACHE_13
1030     sp=ap_make_sub_pool(r->pool);
1031 #else
1032     if (apr_pool_create(&sp,r->pool) != APR_SUCCESS) {
1033         ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,
1034             "groups_for_user: could not create a subpool");
1035         return nullptr;
1036     }
1037 #endif
1038
1039     while (!(ap_cfg_getline(l,MAX_STRING_LEN,f))) {
1040         if ((*l=='#') || (!*l))
1041             continue;
1042         ll = l;
1043         ap_clear_pool(sp);
1044         group_name = ap_getword(sp,&ll,':');
1045         while (*ll) {
1046             w=ap_getword_conf(sp,&ll);
1047             if (!strcmp(w,user)) {
1048                 ap_table_setn(grps,ap_pstrdup(r->pool,group_name),"in");
1049                 break;
1050             }
1051         }
1052     }
1053     ap_cfg_closefile(f);
1054     ap_destroy_pool(sp);
1055     return grps;
1056 }
1057
1058 AccessControl::aclresult_t htAccessControl::doGroup(const ShibTargetApache& sta, const char* params) const
1059 {
1060     SH_AP_TABLE* grpstatus = nullptr;
1061     if (sta.m_dc->szAuthGrpFile) {
1062         if (sta.isPriorityEnabled(SPRequest::SPDebug))
1063             sta.log(SPRequest::SPDebug, string("htaccess plugin using groups file: ") + sta.m_dc->szAuthGrpFile);
1064         grpstatus = groups_for_user(sta.m_req, sta.getRemoteUser().c_str(), sta.m_dc->szAuthGrpFile);
1065     }
1066
1067     bool negated = false;
1068     while (*params) {
1069         const char* w = ap_getword_conf(sta.m_req->pool, &params);
1070         if (*w == '!') {
1071             // A negated rule presumes success unless a match is found.
1072             negated = true;
1073             continue;
1074         }
1075
1076         if (grpstatus && ap_table_get(grpstatus, w)) {
1077             // If we matched, then we're done with this rule either way and we flip status to reflect the outcome.
1078             sta.log(SPRequest::SPDebug, string("htaccess: require group ") + (negated ? "rejecting (" : "accepting (") + w + ")");
1079             return (negated ? shib_acl_false : shib_acl_true);
1080         }
1081     }
1082
1083     return (negated ? shib_acl_true : shib_acl_false);
1084 }
1085 #endif
1086
1087 AccessControl::aclresult_t htAccessControl::doAuthnContext(const ShibTargetApache& sta, const char* ref, const char* params) const
1088 {
1089     if (ref && *ref) {
1090         bool regexp = false;
1091         bool negated = false;
1092         while (ref && *params) {
1093             const char* w = ap_getword_conf(sta.m_req->pool, &params);
1094             if (*w == '~') {
1095                 regexp = true;
1096                 continue;
1097             }
1098             else if (*w == '!') {
1099                 // A negated rule presumes success unless a match is found.
1100                 negated = true;
1101                 if (*(w+1) == '~')
1102                     regexp = true;
1103                 continue;
1104             }
1105
1106             // Figure out if there's a match.
1107             bool match = false;
1108             if (regexp) {
1109                 try {
1110                     RegularExpression re(w);
1111                     match = re.matches(ref);
1112                 }
1113                 catch (XMLException& ex) {
1114                     auto_ptr_char tmp(ex.getMessage());
1115                     sta.log(SPRequest::SPError,
1116                         string("htaccess plugin caught exception while parsing regular expression (") + w + "): " + tmp.get());
1117                 }
1118             }
1119             else if (!strcmp(w, ref)) {
1120                 match = true;
1121             }
1122
1123             if (match) {
1124                 if (sta.isPriorityEnabled(SPRequest::SPDebug))
1125                     sta.log(SPRequest::SPDebug,
1126                         string("htaccess: require authnContext ") + (negated ? "rejecting (" : "accepting (") + ref + ")");
1127                 return (negated ? shib_acl_false : shib_acl_true);
1128             }
1129         }
1130         return (negated ? shib_acl_true : shib_acl_false);
1131     }
1132
1133     if (sta.isPriorityEnabled(SPRequest::SPDebug))
1134         sta.log(SPRequest::SPDebug, "htaccess: require authnContext rejecting session with no context associated");
1135     return shib_acl_false;
1136 }
1137
1138 bool htAccessControl::checkAttribute(const SPRequest& request, const Attribute* attr, const char* toMatch, RegularExpression* re) const
1139 {
1140     bool caseSensitive = attr->isCaseSensitive();
1141     const vector<string>& vals = attr->getSerializedValues();
1142     for (vector<string>::const_iterator v = vals.begin(); v != vals.end(); ++v) {
1143         if (re) {
1144             auto_arrayptr<XMLCh> trans(fromUTF8(v->c_str()));
1145             if (re->matches(trans.get())) {
1146                 if (request.isPriorityEnabled(SPRequest::SPDebug))
1147                     request.log(SPRequest::SPDebug, string("htaccess: expecting regexp ") + toMatch + ", got " + *v + ": acccepted");
1148                 return true;
1149             }
1150         }
1151         else if ((caseSensitive && *v == toMatch) || (!caseSensitive && !strcasecmp(v->c_str(), toMatch))) {
1152             if (request.isPriorityEnabled(SPRequest::SPDebug))
1153                 request.log(SPRequest::SPDebug, string("htaccess: expecting ") + toMatch + ", got " + *v + ": accepted");
1154             return true;
1155         }
1156         else if (request.isPriorityEnabled(SPRequest::SPDebug)) {
1157             request.log(SPRequest::SPDebug, string("htaccess: expecting ") + toMatch + ", got " + *v + ": rejected");
1158         }
1159     }
1160     return false;
1161 }
1162
1163 AccessControl::aclresult_t htAccessControl::doShibAttr(const ShibTargetApache& sta, const Session* session, const char* rule, const char* params) const
1164 {
1165 #ifndef SHIB_APACHE_24
1166     // Look for the new shib-attr placeholder and move past it.
1167     if (sta.m_dc->bCompatWith24 == 1 && rule && !strcmp(rule, "shib-attr")) {
1168         if (*params)
1169             rule = ap_getword_conf(sta.m_req->pool, &params);
1170     }
1171 #endif
1172
1173     // Find the attribute(s) matching the require rule.
1174     pair<multimap<string,const Attribute*>::const_iterator,multimap<string,const Attribute*>::const_iterator> attrs =
1175         session->getIndexedAttributes().equal_range(rule ? rule : "");
1176
1177     bool regexp = false;
1178     while (attrs.first != attrs.second && *params) {
1179         const char* w = ap_getword_conf(sta.m_req->pool, &params);
1180         if (*w == '~') {
1181             regexp = true;
1182             continue;
1183         }
1184
1185         try {
1186             scoped_ptr<RegularExpression> re;
1187             if (regexp) {
1188                 auto_arrayptr<XMLCh> trans(fromUTF8(w));
1189                 re.reset(new xercesc::RegularExpression(trans.get()));
1190             }
1191                     
1192             pair<multimap<string,const Attribute*>::const_iterator,multimap<string,const Attribute*>::const_iterator> attrs2(attrs);
1193             for (; attrs2.first != attrs2.second; ++attrs2.first) {
1194                 if (checkAttribute(sta, attrs2.first->second, w, regexp ? re.get() : nullptr)) {
1195                     return shib_acl_true;
1196                 }
1197             }
1198         }
1199         catch (XMLException& ex) {
1200             auto_ptr_char tmp(ex.getMessage());
1201             sta.log(SPRequest::SPError, string("htaccess plugin caught exception while parsing regular expression (") + w + "): " + tmp.get());
1202         }
1203     }
1204     return shib_acl_false;
1205 }
1206
1207 AccessControl::aclresult_t htAccessControl::authorized(const SPRequest& request, const Session* session) const
1208 {
1209 #ifdef SHIB_APACHE_24
1210     // We should never be invoked in 2.4 as an SP plugin.
1211     throw ConfigurationException("Save my walrus!");
1212 #else
1213     // Make sure the object is our type.
1214     const ShibTargetApache* sta=dynamic_cast<const ShibTargetApache*>(&request);
1215     if (!sta)
1216         throw ConfigurationException("Request wrapper object was not of correct type.");
1217
1218     int m = sta->m_req->method_number;
1219     bool method_restricted = false;
1220     const char *t, *w;
1221
1222     const array_header* reqs_arr = ap_requires(sta->m_req);
1223     if (!reqs_arr)
1224         return shib_acl_indeterminate;  // should never happen
1225
1226         // Check for an "embedded" AccessControl plugin.
1227         if (sta->m_dc->szAccessControl) {
1228         aclresult_t result = doAccessControl(*sta, session, sta->m_dc->szAccessControl);
1229         if (result == shib_acl_true && sta->m_dc->bRequireAll != 1) {
1230             // If we're not insisting that all rules be met, then we're done.
1231             request.log(SPRequest::SPDebug, "htaccess: embedded AccessControl plugin was successful, granting access");
1232             return shib_acl_true;
1233         }
1234         else if (result != shib_acl_true && sta->m_dc->bRequireAll == 1) {
1235             // If we're insisting that all rules be met, which is not something Apache really handles well,
1236             // then we either return false or indeterminate based on the authoritative option, which defaults on.
1237             if (sta->m_dc->bAuthoritative != 0) {
1238                 request.log(SPRequest::SPDebug, "htaccess: embedded AccessControl plugin was unsuccessful, denying access");
1239                 return shib_acl_false;
1240             }
1241
1242             request.log(SPRequest::SPDebug, "htaccess: embedded AccessControl plugin was unsuccessful but not authoritative, leaving it up to Apache");
1243             return shib_acl_indeterminate;
1244         }
1245     }
1246
1247     require_line* reqs = (require_line*)reqs_arr->elts;
1248
1249     for (int x = 0; x < reqs_arr->nelts; ++x) {
1250         // This rule should be completely ignored, the method doesn't fit.
1251         // The rule just doesn't exist for our purposes.
1252         if (!(reqs[x].method_mask & (1 << m)))
1253             continue;
1254
1255         method_restricted = true; // this lets us know at the end that at least one rule was potentially enforcable.
1256
1257         // Tracks status of this rule's evaluation.
1258         bool status = false;
1259
1260         string remote_user = request.getRemoteUser();
1261
1262         t = reqs[x].requirement;
1263         w = ap_getword_white(sta->m_req->pool, &t);
1264
1265         if (!strcasecmp(w,"shibboleth")) {
1266             // This is a dummy rule needed because Apache conflates authn and authz.
1267             // Without some require rule, AuthType is ignored and no check_user hooks run.
1268
1269             // We evaluate to false if ShibAccessControl is used and ShibRequireAll is off.
1270             // This allows actual rules to dictate the result, since ShibAccessControl returned
1271             // non-true, and if nothing else is used, access will be denied.
1272             if (!sta->m_dc->szAccessControl || sta->m_dc->bRequireAll == 1) {
1273                 // We evaluate to true, because ShibRequireAll is enabled (so a true is just a no-op)
1274                 // or because there was no other AccessControl rule in place, so this may be the only
1275                 // rule in effect.
1276                 status = true;
1277             }
1278         }
1279         else if (!strcmp(w,"valid-user") && session) {
1280             request.log(SPRequest::SPDebug, "htaccess: accepting valid-user based on active session");
1281             status = true;
1282         }
1283         else if (!strcmp(w,"user") && !remote_user.empty()) {
1284             status = (doUser(*sta, t) == shib_acl_true);
1285         }
1286         else if (!strcmp(w,"group")  && !remote_user.empty()) {
1287             status = (doGroup(*sta, t) == shib_acl_true);
1288         }
1289         else if (!strcmp(w,"authnContextClassRef") || !strcmp(w,"authnContextDeclRef")) {
1290             const char* ref = !strcmp(w, "authnContextClassRef") ? session->getAuthnContextClassRef() : session->getAuthnContextDeclRef();
1291             status = (doAuthnContext(*sta, ref, t) == shib_acl_true);
1292         }
1293         else if (!session) {
1294             request.log(SPRequest::SPError, string("htaccess: require ") + w + " not given a valid session, are you using lazy sessions?");
1295         }
1296         else if (sta->m_dc->bCompatWith24 == 1 && !strcmp(w,"shib-plugin")) {
1297             w = ap_getword_conf(sta->m_req->pool, &t);
1298             if (w) {
1299                 status = (doAccessControl(*sta, session, w) == shib_acl_true);
1300             }
1301         }
1302         else {
1303             status = (doShibAttr(*sta, session, w, t) == shib_acl_true);
1304         }
1305
1306         // If status is false, we found a rule we couldn't satisfy.
1307         // Could be an unknown rule to us, or it just didn't match.
1308
1309         if (status && sta->m_dc->bRequireAll != 1) {
1310             // If we're not insisting that all rules be met, then we're done.
1311             request.log(SPRequest::SPDebug, "htaccess: a rule was successful, granting access");
1312             return shib_acl_true;
1313         }
1314         else if (!status && sta->m_dc->bRequireAll == 1) {
1315             // If we're insisting that all rules be met, which is not something Apache really handles well,
1316             // then we either return false or indeterminate based on the authoritative option, which defaults on.
1317             if (sta->m_dc->bAuthoritative != 0) {
1318                 request.log(SPRequest::SPDebug, "htaccess: a rule was unsuccessful, denying access");
1319                 return shib_acl_false;
1320             }
1321
1322             request.log(SPRequest::SPDebug, "htaccess: a rule was unsuccessful but not authoritative, leaving it up to Apache");
1323             return shib_acl_indeterminate;
1324         }
1325
1326         // Otherwise, we keep going. If we're requring all, then we have to check every rule.
1327         // If not we just didn't find a successful rule yet, so we keep going anyway.
1328     }
1329
1330     // If we get here, we either "failed" or we're in require all mode (but not both).
1331     // If no rules possibly apply or we insisted that all rules check out, then we're good.
1332     if (!method_restricted) {
1333         request.log(SPRequest::SPDebug, "htaccess: no rules applied to this request method, granting access");
1334         return shib_acl_true;
1335     }
1336     else if (sta->m_dc->bRequireAll == 1) {
1337         request.log(SPRequest::SPDebug, "htaccess: all rules successful, granting access");
1338         return shib_acl_true;
1339     }
1340     else if (sta->m_dc->bAuthoritative != 0) {
1341         request.log(SPRequest::SPDebug, "htaccess: no rules were successful, denying access");
1342         return shib_acl_false;
1343     }
1344
1345     request.log(SPRequest::SPDebug, "htaccess: no rules were successful but not authoritative, leaving it up to Apache");
1346     return shib_acl_indeterminate;
1347 #endif
1348 }
1349
1350 class ApacheRequestMapper : public virtual RequestMapper, public virtual PropertySet
1351 {
1352 public:
1353     ApacheRequestMapper(const xercesc::DOMElement* e);
1354     ~ApacheRequestMapper() {}
1355     Lockable* lock() { return m_mapper->lock(); }
1356     void unlock() { m_staKey->setData(nullptr); m_propsKey->setData(nullptr); m_mapper->unlock(); }
1357     Settings getSettings(const HTTPRequest& request) const;
1358
1359     const PropertySet* getParent() const { return nullptr; }
1360     void setParent(const PropertySet*) {}
1361     pair<bool,bool> getBool(const char* name, const char* ns=nullptr) const;
1362     pair<bool,const char*> getString(const char* name, const char* ns=nullptr) const;
1363     pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=nullptr) const;
1364     pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=nullptr) const;
1365     pair<bool,int> getInt(const char* name, const char* ns=nullptr) const;
1366     void getAll(map<string,const char*>& properties) const;
1367     const PropertySet* getPropertySet(const char* name, const char* ns=shibspconstants::ASCII_SHIB2SPCONFIG_NS) const;
1368     const xercesc::DOMElement* getElement() const;
1369
1370     const htAccessControl& getHTAccessControl() const { return m_htaccess; }
1371
1372 private:
1373     scoped_ptr<RequestMapper> m_mapper;
1374     scoped_ptr<ThreadKey> m_staKey,m_propsKey;
1375     mutable htAccessControl m_htaccess;
1376 };
1377
1378 RequestMapper* ApacheRequestMapFactory(const xercesc::DOMElement* const & e)
1379 {
1380     return new ApacheRequestMapper(e);
1381 }
1382
1383 ApacheRequestMapper::ApacheRequestMapper(const xercesc::DOMElement* e)
1384     : m_mapper(SPConfig::getConfig().RequestMapperManager.newPlugin(XML_REQUEST_MAPPER,e)),
1385         m_staKey(ThreadKey::create(nullptr)), m_propsKey(ThreadKey::create(nullptr))
1386 {
1387 }
1388
1389 RequestMapper::Settings ApacheRequestMapper::getSettings(const HTTPRequest& request) const
1390 {
1391     Settings s = m_mapper->getSettings(request);
1392     m_staKey->setData((void*)dynamic_cast<const ShibTargetApache*>(&request));
1393     m_propsKey->setData((void*)s.first);
1394     // Only return the htAccess plugin for pre-2.4 servers.
1395 #ifdef SHIB_APACHE_24
1396     return pair<const PropertySet*,AccessControl*>(this, s.second);
1397 #else
1398     return pair<const PropertySet*,AccessControl*>(this, s.second ? s.second : &m_htaccess);
1399 #endif
1400 }
1401
1402 pair<bool,bool> ApacheRequestMapper::getBool(const char* name, const char* ns) const
1403 {
1404     const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
1405     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
1406     if (sta && !ns) {
1407         // Override Apache-settable boolean properties.
1408         if (name && !strcmp(name,"requireSession") && sta->m_dc->bRequireSession != -1)
1409             return make_pair(true, sta->m_dc->bRequireSession==1);
1410         else if (name && !strcmp(name,"exportAssertion") && sta->m_dc->bExportAssertion != -1)
1411             return make_pair(true, sta->m_dc->bExportAssertion==1);
1412         else if (sta->m_dc->tSettings) {
1413             const char* prop = ap_table_get(sta->m_dc->tSettings, name);
1414             if (prop)
1415                 return make_pair(true, !strcmp(prop, "true") || !strcmp(prop, "1") || !strcmp(prop, "On"));
1416         }
1417     }
1418     return s ? s->getBool(name,ns) : make_pair(false,false);
1419 }
1420
1421 pair<bool,const char*> ApacheRequestMapper::getString(const char* name, const char* ns) const
1422 {
1423     const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
1424     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
1425     if (sta && !ns) {
1426         // Override Apache-settable string properties.
1427         if (name && !strcmp(name,"authType")) {
1428             const char* auth_type = ap_auth_type(sta->m_req);
1429             if (auth_type) {
1430                 // Check for Basic Hijack
1431                 if (!strcasecmp(auth_type, "basic") && sta->m_dc->bBasicHijack == 1)
1432                     auth_type = "shibboleth";
1433                 return make_pair(true, auth_type);
1434             }
1435         }
1436         else if (name && !strcmp(name,"applicationId") && sta->m_dc->szApplicationId)
1437             return pair<bool,const char*>(true,sta->m_dc->szApplicationId);
1438         else if (name && !strcmp(name,"requireSessionWith") && sta->m_dc->szRequireWith)
1439             return pair<bool,const char*>(true,sta->m_dc->szRequireWith);
1440         else if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
1441             return pair<bool,const char*>(true,sta->m_dc->szRedirectToSSL);
1442         else if (sta->m_dc->tSettings) {
1443             const char* prop = ap_table_get(sta->m_dc->tSettings, name);
1444             if (prop)
1445                 return make_pair(true, prop);
1446         }
1447     }
1448     return s ? s->getString(name,ns) : pair<bool,const char*>(false,nullptr);
1449 }
1450
1451 pair<bool,const XMLCh*> ApacheRequestMapper::getXMLString(const char* name, const char* ns) const
1452 {
1453     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
1454     return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,nullptr);
1455 }
1456
1457 pair<bool,unsigned int> ApacheRequestMapper::getUnsignedInt(const char* name, const char* ns) const
1458 {
1459     const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
1460     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
1461     if (sta && !ns) {
1462         // Override Apache-settable int properties.
1463         if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
1464             return pair<bool,unsigned int>(true, strtol(sta->m_dc->szRedirectToSSL, nullptr, 10));
1465         else if (sta->m_dc->tSettings) {
1466             const char* prop = ap_table_get(sta->m_dc->tSettings, name);
1467             if (prop)
1468                 return pair<bool,unsigned int>(true, atoi(prop));
1469         }
1470     }
1471     return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
1472 }
1473
1474 pair<bool,int> ApacheRequestMapper::getInt(const char* name, const char* ns) const
1475 {
1476     const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
1477     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
1478     if (sta && !ns) {
1479         // Override Apache-settable int properties.
1480         if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
1481             return pair<bool,int>(true,atoi(sta->m_dc->szRedirectToSSL));
1482         else if (sta->m_dc->tSettings) {
1483             const char* prop = ap_table_get(sta->m_dc->tSettings, name);
1484             if (prop)
1485                 return make_pair(true, atoi(prop));
1486         }
1487     }
1488     return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
1489 }
1490
1491 static int _rm_get_all_table_walk(void *v, const char *key, const char *value)
1492 {
1493     reinterpret_cast<map<string,const char*>*>(v)->insert(pair<string,const char*>(key, value));
1494     return 1;
1495 }
1496
1497 void ApacheRequestMapper::getAll(map<string,const char*>& properties) const
1498 {
1499     const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
1500     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
1501
1502     if (s)
1503         s->getAll(properties);
1504     if (!sta)
1505         return;
1506
1507     const char* auth_type=ap_auth_type(sta->m_req);
1508     if (auth_type) {
1509         // Check for Basic Hijack
1510         if (!strcasecmp(auth_type, "basic") && sta->m_dc->bBasicHijack == 1)
1511             auth_type = "shibboleth";
1512         properties["authType"] = auth_type;
1513     }
1514
1515     if (sta->m_dc->szApplicationId)
1516         properties["applicationId"] = sta->m_dc->szApplicationId;
1517     if (sta->m_dc->szRequireWith)
1518         properties["requireSessionWith"] = sta->m_dc->szRequireWith;
1519     if (sta->m_dc->szRedirectToSSL)
1520         properties["redirectToSSL"] = sta->m_dc->szRedirectToSSL;
1521     if (sta->m_dc->bRequireSession != 0)
1522         properties["requireSession"] = (sta->m_dc->bRequireSession==1) ? "true" : "false";
1523     if (sta->m_dc->bExportAssertion != 0)
1524         properties["exportAssertion"] = (sta->m_dc->bExportAssertion==1) ? "true" : "false";
1525
1526     if (sta->m_dc->tSettings)
1527         ap_table_do(_rm_get_all_table_walk, &properties, sta->m_dc->tSettings, NULL);
1528 }
1529
1530 const PropertySet* ApacheRequestMapper::getPropertySet(const char* name, const char* ns) const
1531 {
1532     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
1533     return s ? s->getPropertySet(name,ns) : nullptr;
1534 }
1535
1536 const xercesc::DOMElement* ApacheRequestMapper::getElement() const
1537 {
1538     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
1539     return s ? s->getElement() : nullptr;
1540 }
1541
1542 // Authz callbacks for Apache 2.4
1543 // For some reason, these get run twice for each request, once before hooks like check_user, etc.
1544 // and once after. The first time through, the request object exists, but isn't initialized.
1545 // The other case is subrequests of some kinds: then post_read doesn't run, and the objects
1546 // themselves don't exist. We do deferred creation of the objects in check_user to fix that case.
1547 // In each screwed up case, we return "denied" so that nothing bad happens.
1548 #ifdef SHIB_APACHE_24
1549 pair<ShibTargetApache*,authz_status> shib_base_check_authz(request_rec* r)
1550 {
1551     shib_request_config* rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
1552     if (!rc || !rc->sta) {
1553         ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "shib_base_check_authz found no per-request structure");
1554         return make_pair((ShibTargetApache*)nullptr, AUTHZ_DENIED_NO_USER);
1555     }
1556     else if (!rc->sta->isInitialized()) {
1557         ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "shib_base_check_authz found uninitialized request object");
1558         return make_pair((ShibTargetApache*)nullptr, AUTHZ_DENIED_NO_USER);
1559     }
1560     return make_pair(rc->sta, AUTHZ_GRANTED);
1561 }
1562
1563 extern "C" authz_status shib_shibboleth_check_authz(request_rec* r, const char* require_line, const void*)
1564 {
1565     pair<ShibTargetApache*,authz_status> sta = shib_base_check_authz(r);
1566     if (!sta.first)
1567         return sta.second;
1568     return AUTHZ_GRANTED;
1569 }
1570
1571 extern "C" authz_status shib_validuser_check_authz(request_rec* r, const char* require_line, const void*)
1572 {
1573     pair<ShibTargetApache*,authz_status> sta = shib_base_check_authz(r);
1574     if (!sta.first)
1575         return sta.second;
1576
1577     try {
1578         const Session* session = sta.first->getSession(false);
1579         if (session) {
1580             sta.first->log(SPRequest::SPDebug, "htaccess: accepting valid-user based on active session");
1581             return AUTHZ_GRANTED;
1582         }
1583     }
1584     catch (std::exception& e) {
1585         sta.first->log(SPRequest::SPWarn, string("htaccess: unable to obtain session for access control check: ") +  e.what());
1586     }
1587
1588     return AUTHZ_DENIED_NO_USER;
1589 }
1590
1591 extern "C" authz_status shib_user_check_authz(request_rec* r, const char* require_line, const void*)
1592 {
1593     if (!r->user || !*(r->user))
1594         return AUTHZ_DENIED_NO_USER;
1595     pair<ShibTargetApache*,authz_status> sta = shib_base_check_authz(r);
1596     if (!sta.first)
1597         return sta.second;
1598
1599     const htAccessControl& hta = dynamic_cast<const ApacheRequestMapper*>(sta.first->getRequestSettings().first)->getHTAccessControl();
1600     if (hta.doUser(*sta.first, require_line) == AccessControl::shib_acl_true)
1601         return AUTHZ_GRANTED;
1602     return AUTHZ_DENIED;
1603 }
1604
1605 extern "C" authz_status shib_acclass_check_authz(request_rec* r, const char* require_line, const void*)
1606 {
1607     pair<ShibTargetApache*,authz_status> sta = shib_base_check_authz(r);
1608     if (!sta.first)
1609         return sta.second;
1610
1611     const htAccessControl& hta = dynamic_cast<const ApacheRequestMapper*>(sta.first->getRequestSettings().first)->getHTAccessControl();
1612
1613     try {
1614         const Session* session = sta.first->getSession(false);
1615         if (session && hta.doAuthnContext(*sta.first, session->getAuthnContextClassRef(), require_line) == AccessControl::shib_acl_true)
1616             return AUTHZ_GRANTED;
1617         return session ? AUTHZ_DENIED : AUTHZ_DENIED_NO_USER;
1618     }
1619     catch (std::exception& e) {
1620         sta.first->log(SPRequest::SPWarn, string("htaccess: unable to obtain session for access control check: ") +  e.what());
1621     }
1622
1623     return AUTHZ_GENERAL_ERROR;
1624 }
1625
1626 extern "C" authz_status shib_acdecl_check_authz(request_rec* r, const char* require_line, const void*)
1627 {
1628     pair<ShibTargetApache*,authz_status> sta = shib_base_check_authz(r);
1629     if (!sta.first)
1630         return sta.second;
1631
1632     const htAccessControl& hta = dynamic_cast<const ApacheRequestMapper*>(sta.first->getRequestSettings().first)->getHTAccessControl();
1633
1634     try {
1635         const Session* session = sta.first->getSession(false);
1636         if (session && hta.doAuthnContext(*sta.first, session->getAuthnContextDeclRef(), require_line) == AccessControl::shib_acl_true)
1637             return AUTHZ_GRANTED;
1638         return session ? AUTHZ_DENIED : AUTHZ_DENIED_NO_USER;
1639     }
1640     catch (std::exception& e) {
1641         sta.first->log(SPRequest::SPWarn, string("htaccess: unable to obtain session for access control check: ") +  e.what());
1642     }
1643
1644     return AUTHZ_GENERAL_ERROR;
1645 }
1646
1647 extern "C" authz_status shib_attr_check_authz(request_rec* r, const char* require_line, const void*)
1648 {
1649     pair<ShibTargetApache*,authz_status> sta = shib_base_check_authz(r);
1650     if (!sta.first)
1651         return sta.second;
1652
1653     const htAccessControl& hta = dynamic_cast<const ApacheRequestMapper*>(sta.first->getRequestSettings().first)->getHTAccessControl();
1654
1655     try {
1656         const Session* session = sta.first->getSession(false);
1657         if (session) {
1658             const char* rule = ap_getword_conf(r->pool, &require_line);
1659             if (rule && hta.doShibAttr(*sta.first, session, rule, require_line) == AccessControl::shib_acl_true)
1660                 return AUTHZ_GRANTED;
1661         }
1662         return session ? AUTHZ_DENIED : AUTHZ_DENIED_NO_USER;
1663     }
1664     catch (std::exception& e) {
1665         sta.first->log(SPRequest::SPWarn, string("htaccess: unable to obtain session for access control check: ") +  e.what());
1666     }
1667
1668     return AUTHZ_GENERAL_ERROR;
1669 }
1670
1671 extern "C" authz_status shib_plugin_check_authz(request_rec* r, const char* require_line, const void*)
1672 {
1673     pair<ShibTargetApache*,authz_status> sta = shib_base_check_authz(r);
1674     if (!sta.first)
1675         return sta.second;
1676
1677     const htAccessControl& hta = dynamic_cast<const ApacheRequestMapper*>(sta.first->getRequestSettings().first)->getHTAccessControl();
1678
1679     try {
1680         const Session* session = sta.first->getSession(false);
1681         if (session) {
1682             const char* config = ap_getword_conf(r->pool, &require_line);
1683             if (config && hta.doAccessControl(*sta.first, session, config) == AccessControl::shib_acl_true)
1684                 return AUTHZ_GRANTED;
1685         }
1686         return session ? AUTHZ_DENIED : AUTHZ_DENIED_NO_USER;
1687     }
1688     catch (std::exception& e) {
1689         sta.first->log(SPRequest::SPWarn, string("htaccess: unable to obtain session for access control check: ") +  e.what());
1690     }
1691
1692     return AUTHZ_GENERAL_ERROR;
1693 }
1694 #endif
1695
1696 // Command manipulation functions
1697
1698 extern "C" const char* ap_set_global_string_slot(cmd_parms* parms, void*, const char* arg)
1699 {
1700     *((char**)(parms->info))=ap_pstrdup(parms->pool,arg);
1701     return nullptr;
1702 }
1703
1704 extern "C" const char* shib_set_server_string_slot(cmd_parms* parms, void*, const char* arg)
1705 {
1706     char* base=(char*)ap_get_module_config(parms->server->module_config,&mod_shib);
1707     size_t offset=(size_t)parms->info;
1708     *((char**)(base + offset))=ap_pstrdup(parms->pool,arg);
1709     return nullptr;
1710 }
1711
1712 extern "C" const char* shib_ap_set_file_slot(cmd_parms* parms,
1713 #ifdef SHIB_APACHE_13
1714                                              char* arg1, char* arg2
1715 #else
1716                                              void* arg1, const char* arg2
1717 #endif
1718                                              )
1719 {
1720   ap_set_file_slot(parms, arg1, arg2);
1721   return DECLINE_CMD;
1722 }
1723
1724 extern "C" const char* shib_table_set(cmd_parms* parms, shib_dir_config* dc, const char* arg1, const char* arg2)
1725 {
1726     if (!dc->tSettings)
1727         dc->tSettings = ap_make_table(parms->pool, 4);
1728     ap_table_set(dc->tSettings, arg1, arg2);
1729     return nullptr;
1730 }
1731
1732 #ifndef SHIB_APACHE_24
1733 extern "C" const char* shib_set_acl_slot(cmd_parms* params, shib_dir_config* dc, char* arg)
1734 {
1735     bool absolute;
1736     switch (*arg) {
1737         case 0:
1738             absolute = false;
1739             break;
1740         case '/':
1741         case '\\':
1742             absolute = true;
1743             break;
1744         case '.':
1745             absolute = (*(arg+1) == '.' || *(arg+1) == '/' || *(arg+1) == '\\');
1746             break;
1747         default:
1748             absolute = *(arg+1) == ':';
1749     }
1750
1751     if (absolute || !params->path)
1752         dc->szAccessControl = ap_pstrdup(params->pool, arg);
1753     else
1754         dc->szAccessControl = ap_pstrcat(params->pool, params->path, arg, NULL);
1755     return nullptr;
1756 }
1757 #endif
1758
1759
1760 #ifdef SHIB_APACHE_13
1761 /*
1762  * shib_child_exit()
1763  *  Cleanup the (per-process) pool info.
1764  */
1765 extern "C" void shib_child_exit(server_rec* s, SH_AP_POOL* p)
1766 {
1767     if (g_Config) {
1768         g_Config->term();
1769         g_Config = nullptr;
1770     }
1771     ap_log_error(APLOG_MARK, APLOG_INFO|APLOG_NOERRNO, SH_AP_R(s), "child_exit: mod_shib shutdown in pid (%d)", (int)getpid());
1772 }
1773 #else
1774 /*
1775  * shib_exit()
1776  *  Apache 2.x doesn't allow for per-child cleanup, causes CGI forks to hang.
1777  */
1778 extern "C" apr_status_t shib_exit(void* data)
1779 {
1780     if (g_Config) {
1781         g_Config->term();
1782         g_Config = nullptr;
1783     }
1784     server_rec* s = reinterpret_cast<server_rec*>(data);
1785     ap_log_error(APLOG_MARK, APLOG_INFO|APLOG_NOERRNO, SH_AP_R(s), "shib_exit: mod_shib shutdown in pid (%d)", (int)getpid());
1786     return OK;
1787 }
1788
1789 /*
1790  * shib_post_config()
1791  *  We do the library init/term work here for 2.x to reduce overhead and
1792  *  get default logging established before the fork happens.
1793  */
1794 apr_status_t shib_post_config(apr_pool_t* p, apr_pool_t*, apr_pool_t*, server_rec* s)
1795 {
1796     // Initialize runtime components.
1797     ap_log_error(APLOG_MARK, APLOG_INFO|APLOG_NOERRNO, SH_AP_R(s),"post_config: mod_shib initializing in pid (%d)", (int)getpid());
1798
1799     if (g_Config) {
1800         ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(s), "post_config: mod_shib already initialized");
1801         return !OK;
1802     }
1803
1804     g_Config = &SPConfig::getConfig();
1805     g_Config->setFeatures(
1806         SPConfig::Listener |
1807         SPConfig::Caching |
1808         SPConfig::RequestMapping |
1809         SPConfig::InProcess |
1810         SPConfig::Logging |
1811         SPConfig::Handlers
1812         );
1813     if (!g_Config->init(g_szSchemaDir, g_szPrefix)) {
1814         ap_log_error(APLOG_MARK, APLOG_CRIT|APLOG_NOERRNO, SH_AP_R(s), "post_config: mod_shib failed to initialize libraries");
1815         return !OK;
1816     }
1817 #ifndef SHIB_APACHE_24
1818     g_Config->AccessControlManager.registerFactory(HT_ACCESS_CONTROL, &htAccessFactory);
1819 #endif
1820     g_Config->RequestMapperManager.registerFactory(NATIVE_REQUEST_MAPPER, &ApacheRequestMapFactory);
1821
1822     // Set the cleanup handler, passing in the server_rec for logging.
1823     apr_pool_cleanup_register(p, s, &shib_exit, apr_pool_cleanup_null);
1824
1825     return OK;
1826 }
1827
1828 #endif
1829
1830 /*
1831  * shib_child_init()
1832  *  Things to do when the child process is initialized.
1833  *  We can't use post-config for all of it on 2.x because only the forking thread shows
1834  *  up in the child, losing the internal threads spun up by plugins in the SP.
1835  */
1836 #ifdef SHIB_APACHE_13
1837 extern "C" void shib_child_init(server_rec* s, SH_AP_POOL* p)
1838 #else
1839 extern "C" void shib_child_init(apr_pool_t* p, server_rec* s)
1840 #endif
1841 {
1842     // Initialize runtime components.
1843
1844     ap_log_error(APLOG_MARK, APLOG_INFO|APLOG_NOERRNO, SH_AP_R(s),"child_init: mod_shib initializing in pid (%d)", (int)getpid());
1845
1846     // 2.x versions have already initialized the libraries.
1847 #ifdef SHIB_APACHE_13
1848     if (g_Config) {
1849         ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(s), "child_init: mod_shib already initialized, exiting");
1850         exit(1);
1851     }
1852
1853     g_Config = &SPConfig::getConfig();
1854     g_Config->setFeatures(
1855         SPConfig::Listener |
1856         SPConfig::Caching |
1857         SPConfig::RequestMapping |
1858         SPConfig::InProcess |
1859         SPConfig::Logging |
1860         SPConfig::Handlers
1861         );
1862     if (!g_Config->init(g_szSchemaDir, g_szPrefix)) {
1863         ap_log_error(APLOG_MARK, APLOG_CRIT|APLOG_NOERRNO, SH_AP_R(s), "child_init: mod_shib failed to initialize libraries");
1864         exit(1);
1865     }
1866     g_Config->AccessControlManager.registerFactory(HT_ACCESS_CONTROL, &htAccessFactory);
1867     g_Config->RequestMapperManager.registerFactory(NATIVE_REQUEST_MAPPER, &ApacheRequestMapFactory);
1868 #endif
1869
1870     // The config gets installed for all versions here due to the background thread/fork issues.
1871     try {
1872         if (!g_Config->instantiate(g_szSHIBConfig, true))
1873             throw runtime_error("unknown error");
1874     }
1875     catch (std::exception& ex) {
1876         ap_log_error(APLOG_MARK, APLOG_CRIT|APLOG_NOERRNO, SH_AP_R(s), "child_init: mod_shib failed to load configuration: %s", ex.what());
1877         g_Config->term();
1878         exit(1);
1879     }
1880
1881     ServiceProvider* sp = g_Config->getServiceProvider();
1882     xmltooling::Locker locker(sp);
1883     const PropertySet* props = sp->getPropertySet("InProcess");
1884     if (props) {
1885         pair<bool,const char*> unsetValue = props->getString("unsetHeaderValue");
1886         if (unsetValue.first)
1887             g_unsetHeaderValue = unsetValue.second;
1888         pair<bool,bool> flag=props->getBool("checkSpoofing");
1889         g_checkSpoofing = !flag.first || flag.second;
1890         if (g_checkSpoofing) {
1891             unsetValue=props->getString("spoofKey");
1892             if (unsetValue.first)
1893                 g_spoofKey = unsetValue.second;
1894         }
1895         flag=props->getBool("catchAll");
1896         g_catchAll = flag.first && flag.second;
1897     }
1898
1899     // Set the cleanup handler, passing in the server_rec for logging.
1900     apr_pool_cleanup_register(p, s, &shib_exit, apr_pool_cleanup_null);
1901
1902     ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(s), "child_init: mod_shib config initialized");
1903 }
1904
1905 // Output filters
1906 #ifdef SHIB_DEFERRED_HEADERS
1907 static void set_output_filter(request_rec *r)
1908 {
1909    ap_add_output_filter("SHIB_HEADERS_OUT", nullptr, r, r->connection);
1910 }
1911
1912 static void set_error_filter(request_rec *r)
1913 {
1914    ap_add_output_filter("SHIB_HEADERS_ERR", nullptr, r, r->connection);
1915 }
1916
1917 static int _table_add(void *v, const char *key, const char *value)
1918 {
1919     apr_table_addn((apr_table_t*)v, key, value);
1920     return 1;
1921 }
1922
1923 static apr_status_t do_output_filter(ap_filter_t *f, apr_bucket_brigade *in)
1924 {
1925     request_rec *r = f->r;
1926     shib_request_config *rc = (shib_request_config*) ap_get_module_config(r->request_config, &mod_shib);
1927
1928     if (rc && rc->hdr_out) {
1929         ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "output_filter: merging %d headers", apr_table_elts(rc->hdr_out)->nelts);
1930         // can't use overlap call because it will collapse Set-Cookie headers
1931         //apr_table_overlap(r->headers_out, rc->hdr_out, APR_OVERLAP_TABLES_MERGE);
1932         apr_table_do(_table_add,r->headers_out, rc->hdr_out,NULL);
1933     }
1934
1935     /* remove ourselves from the filter chain */
1936     ap_remove_output_filter(f);
1937
1938     /* send the data up the stack */
1939     return ap_pass_brigade(f->next,in);
1940 }
1941
1942 static apr_status_t do_error_filter(ap_filter_t *f, apr_bucket_brigade *in)
1943 {
1944     request_rec *r = f->r;
1945     shib_request_config *rc = (shib_request_config*) ap_get_module_config(r->request_config, &mod_shib);
1946
1947     if (rc && rc->hdr_out) {
1948         ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "error_filter: merging %d headers", apr_table_elts(rc->hdr_out)->nelts);
1949         // can't use overlap call because it will collapse Set-Cookie headers
1950         //apr_table_overlap(r->err_headers_out, rc->hdr_out, APR_OVERLAP_TABLES_MERGE);
1951         apr_table_do(_table_add,r->err_headers_out, rc->hdr_out,NULL);
1952     }
1953
1954     /* remove ourselves from the filter chain */
1955     ap_remove_output_filter(f);
1956
1957     /* send the data up the stack */
1958     return ap_pass_brigade(f->next,in);
1959 }
1960 #endif // SHIB_DEFERRED_HEADERS
1961
1962 typedef const char* (*config_fn_t)(void);
1963
1964 #ifdef SHIB_APACHE_13
1965
1966 // SHIB Module commands
1967
1968 static command_rec shire_cmds[] = {
1969   {"ShibPrefix", (config_fn_t)ap_set_global_string_slot, &g_szPrefix,
1970    RSRC_CONF, TAKE1, "Shibboleth installation directory"},
1971   {"ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1972    RSRC_CONF, TAKE1, "Path to shibboleth2.xml config file"},
1973   {"ShibCatalogs", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1974    RSRC_CONF, TAKE1, "Paths of XML schema catalogs"},
1975
1976   {"ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
1977    (void *) XtOffsetOf (shib_server_config, szScheme),
1978    RSRC_CONF, TAKE1, "URL scheme to force into generated URLs for a vhost"},
1979
1980   {"ShibRequestSetting", (config_fn_t)shib_table_set, nullptr,
1981    OR_AUTHCFG, TAKE2, "Set arbitrary Shibboleth request property for content"},
1982
1983   {"ShibAccessControl", (config_fn_t)shib_set_acl_slot, nullptr,
1984    OR_AUTHCFG, TAKE1, "Set arbitrary Shibboleth access control plugin for content"},
1985
1986   {"ShibDisable", (config_fn_t)ap_set_flag_slot,
1987    (void *) XtOffsetOf (shib_dir_config, bOff),
1988    OR_AUTHCFG, FLAG, "Disable all Shib module activity here to save processing effort"},
1989   {"ShibApplicationId", (config_fn_t)ap_set_string_slot,
1990    (void *) XtOffsetOf (shib_dir_config, szApplicationId),
1991    OR_AUTHCFG, TAKE1, "Set Shibboleth applicationId property for content"},
1992   {"ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1993    (void *) XtOffsetOf (shib_dir_config, bBasicHijack),
1994    OR_AUTHCFG, FLAG, "(DEPRECATED) Respond to AuthType Basic and convert to shibboleth"},
1995   {"ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1996    (void *) XtOffsetOf (shib_dir_config, bRequireSession),
1997    OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist"},
1998   {"ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
1999    (void *) XtOffsetOf (shib_dir_config, szRequireWith),
2000    OR_AUTHCFG, TAKE1, "Initiates a new session if one does not exist using a specific SessionInitiator"},
2001   {"ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
2002    (void *) XtOffsetOf (shib_dir_config, bExportAssertion),
2003    OR_AUTHCFG, FLAG, "Export SAML attribute assertion(s) to Shib-Attributes header"},
2004   {"ShibRedirectToSSL", (config_fn_t)ap_set_string_slot,
2005    (void *) XtOffsetOf (shib_dir_config, szRedirectToSSL),
2006    OR_AUTHCFG, TAKE1, "Redirect non-SSL requests to designated port" },
2007   {"AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
2008    (void *) XtOffsetOf (shib_dir_config, szAuthGrpFile),
2009    OR_AUTHCFG, TAKE1, "text file containing group names and member user IDs"},
2010   {"ShibRequireAll", (config_fn_t)ap_set_flag_slot,
2011    (void *) XtOffsetOf (shib_dir_config, bRequireAll),
2012    OR_AUTHCFG, FLAG, "All require directives must match"},
2013   {"AuthzShibAuthoritative", (config_fn_t)ap_set_flag_slot,
2014    (void *) XtOffsetOf (shib_dir_config, bAuthoritative),
2015    OR_AUTHCFG, FLAG, "Allow failed mod_shib htaccess authorization to fall through to other modules"},
2016   {"ShibCompatWith24", (config_fn_t)ap_set_flag_slot,
2017    (void *) XtOffsetOf (shib_dir_config, bCompatWith24),
2018    OR_AUTHCFG, FLAG, "Support Apache 2.4-style require rules"},
2019   {"ShibUseEnvironment", (config_fn_t)ap_set_flag_slot,
2020    (void *) XtOffsetOf (shib_dir_config, bUseEnvVars),
2021    OR_AUTHCFG, FLAG, "Export attributes using environment variables (default)"},
2022   {"ShibUseHeaders", (config_fn_t)ap_set_flag_slot,
2023    (void *) XtOffsetOf (shib_dir_config, bUseHeaders),
2024    OR_AUTHCFG, FLAG, "Export attributes using custom HTTP headers"},
2025   {"ShibExpireRedirects", (config_fn_t)ap_set_flag_slot,
2026    (void *) XtOffsetOf (shib_dir_config, bExpireRedirects),
2027    OR_AUTHCFG, FLAG, "Expire SP-generated redirects"},
2028
2029   {nullptr}
2030 };
2031
2032 extern "C"{
2033 handler_rec shib_handlers[] = {
2034   { "shib-handler", shib_handler },
2035   { nullptr }
2036 };
2037
2038 module MODULE_VAR_EXPORT mod_shib = {
2039     STANDARD_MODULE_STUFF,
2040     nullptr,                        /* initializer */
2041     create_shib_dir_config,     /* dir config creater */
2042     merge_shib_dir_config,      /* dir merger --- default is to override */
2043     create_shib_server_config, /* server config */
2044     merge_shib_server_config,   /* merge server config */
2045     shire_cmds,                 /* command table */
2046     shib_handlers,              /* handlers */
2047     nullptr,                    /* filename translation */
2048     shib_check_user,            /* check_user_id */
2049     shib_auth_checker,          /* check auth */
2050     nullptr,                    /* check access */
2051     nullptr,                    /* type_checker */
2052     shib_fixups,                /* fixups */
2053     nullptr,                    /* logger */
2054     nullptr,                    /* header parser */
2055     shib_child_init,            /* child_init */
2056     shib_child_exit,            /* child_exit */
2057     shib_post_read              /* post read-request */
2058 };
2059
2060 #else
2061
2062 #ifdef SHIB_APACHE_24
2063 extern "C" const authz_provider shib_authz_shibboleth_provider = { &shib_shibboleth_check_authz, nullptr };
2064 extern "C" const authz_provider shib_authz_validuser_provider = { &shib_validuser_check_authz, nullptr };
2065 extern "C" const authz_provider shib_authz_user_provider = { &shib_user_check_authz, nullptr };
2066 extern "C" const authz_provider shib_authz_acclass_provider = { &shib_acclass_check_authz, nullptr };
2067 extern "C" const authz_provider shib_authz_acdecl_provider = { &shib_acdecl_check_authz, nullptr };
2068 extern "C" const authz_provider shib_authz_attr_provider = { &shib_attr_check_authz, nullptr };
2069 extern "C" const authz_provider shib_authz_plugin_provider = { &shib_plugin_check_authz, nullptr };
2070 #endif
2071
2072 extern "C" void shib_register_hooks (apr_pool_t *p)
2073 {
2074 #ifdef SHIB_DEFERRED_HEADERS
2075     ap_register_output_filter("SHIB_HEADERS_OUT", do_output_filter, nullptr, AP_FTYPE_CONTENT_SET);
2076     ap_hook_insert_filter(set_output_filter, nullptr, nullptr, APR_HOOK_LAST);
2077     ap_register_output_filter("SHIB_HEADERS_ERR", do_error_filter, nullptr, AP_FTYPE_CONTENT_SET);
2078     ap_hook_insert_error_filter(set_error_filter, nullptr, nullptr, APR_HOOK_LAST);
2079     ap_hook_post_read_request(shib_post_read, nullptr, nullptr, APR_HOOK_MIDDLE);
2080 #endif
2081     ap_hook_post_config(shib_post_config, nullptr, nullptr, APR_HOOK_MIDDLE);
2082     ap_hook_child_init(shib_child_init, nullptr, nullptr, APR_HOOK_MIDDLE);
2083     const char* prereq = getenv("SHIBSP_APACHE_PREREQ");
2084 #ifdef SHIB_APACHE_24
2085     if (prereq && *prereq) {
2086         const char* const authnPre[] = { prereq, nullptr };
2087         ap_hook_check_authn(shib_check_user, authnPre, nullptr, APR_HOOK_MIDDLE, AP_AUTH_INTERNAL_PER_URI);
2088     }
2089     else {
2090         ap_hook_check_authn(shib_check_user, nullptr, nullptr, APR_HOOK_MIDDLE, AP_AUTH_INTERNAL_PER_URI);
2091     }
2092     ap_hook_check_authz(shib_auth_checker, nullptr, nullptr, APR_HOOK_FIRST, AP_AUTH_INTERNAL_PER_URI);
2093 #else
2094     if (prereq && *prereq) {
2095         const char* const authnPre[] = { prereq, nullptr };
2096         ap_hook_check_user_id(shib_check_user, authnPre, nullptr, APR_HOOK_MIDDLE);
2097     }
2098     else {
2099         ap_hook_check_user_id(shib_check_user, nullptr, nullptr, APR_HOOK_MIDDLE);
2100     }
2101     ap_hook_auth_checker(shib_auth_checker, nullptr, nullptr, APR_HOOK_FIRST);
2102 #endif
2103     ap_hook_handler(shib_handler, nullptr, nullptr, APR_HOOK_LAST);
2104     ap_hook_fixups(shib_fixups, nullptr, nullptr, APR_HOOK_MIDDLE);
2105
2106 #ifdef SHIB_APACHE_24
2107     ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "shibboleth", AUTHZ_PROVIDER_VERSION, &shib_authz_shibboleth_provider, AP_AUTH_INTERNAL_PER_CONF);
2108     ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "valid-user", AUTHZ_PROVIDER_VERSION, &shib_authz_validuser_provider, AP_AUTH_INTERNAL_PER_CONF);
2109     ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "user", AUTHZ_PROVIDER_VERSION, &shib_authz_user_provider, AP_AUTH_INTERNAL_PER_CONF);
2110     ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "authnContextClassRef", AUTHZ_PROVIDER_VERSION, &shib_authz_acclass_provider, AP_AUTH_INTERNAL_PER_CONF);
2111     ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "authnContextDeclRef", AUTHZ_PROVIDER_VERSION, &shib_authz_acdecl_provider, AP_AUTH_INTERNAL_PER_CONF);
2112     ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "shib-attr", AUTHZ_PROVIDER_VERSION, &shib_authz_attr_provider, AP_AUTH_INTERNAL_PER_CONF);
2113     ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "shib-plugin", AUTHZ_PROVIDER_VERSION, &shib_authz_plugin_provider, AP_AUTH_INTERNAL_PER_CONF);
2114 #endif
2115 }
2116
2117 // SHIB Module commands
2118
2119 extern "C" {
2120 static command_rec shib_cmds[] = {
2121     AP_INIT_TAKE1("ShibPrefix", (config_fn_t)ap_set_global_string_slot, &g_szPrefix,
2122         RSRC_CONF, "Shibboleth installation directory"),
2123     AP_INIT_TAKE1("ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
2124         RSRC_CONF, "Path to shibboleth2.xml config file"),
2125     AP_INIT_TAKE1("ShibCatalogs", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
2126         RSRC_CONF, "Paths of XML schema catalogs"),
2127     AP_INIT_TAKE1("ShibGSSKey", (config_fn_t)ap_set_global_string_slot, &g_szGSSContextKey,
2128         RSRC_CONF, "Name of user data key containing GSS context established by GSS module"),
2129
2130     AP_INIT_TAKE1("ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
2131         (void *) offsetof (shib_server_config, szScheme),
2132         RSRC_CONF, "URL scheme to force into generated URLs for a vhost"),
2133
2134     AP_INIT_TAKE2("ShibRequestSetting", (config_fn_t)shib_table_set, nullptr,
2135         OR_AUTHCFG, "Set arbitrary Shibboleth request property for content"),
2136
2137     AP_INIT_FLAG("ShibDisable", (config_fn_t)ap_set_flag_slot,
2138         (void *) offsetof (shib_dir_config, bOff),
2139         OR_AUTHCFG, "Disable all Shib module activity here to save processing effort"),
2140     AP_INIT_TAKE1("ShibApplicationId", (config_fn_t)ap_set_string_slot,
2141         (void *) offsetof (shib_dir_config, szApplicationId),
2142         OR_AUTHCFG, "Set Shibboleth applicationId property for content"),
2143     AP_INIT_FLAG("ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
2144         (void *) offsetof (shib_dir_config, bBasicHijack),
2145         OR_AUTHCFG, "(DEPRECATED) Respond to AuthType Basic and convert to shibboleth"),
2146     AP_INIT_FLAG("ShibRequireSession", (config_fn_t)ap_set_flag_slot,
2147         (void *) offsetof (shib_dir_config, bRequireSession),
2148         OR_AUTHCFG, "Initiates a new session if one does not exist"),
2149     AP_INIT_TAKE1("ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
2150         (void *) offsetof (shib_dir_config, szRequireWith),
2151         OR_AUTHCFG, "Initiates a new session if one does not exist using a specific SessionInitiator"),
2152     AP_INIT_FLAG("ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
2153         (void *) offsetof (shib_dir_config, bExportAssertion),
2154         OR_AUTHCFG, "Export SAML attribute assertion(s) to Shib-Attributes header"),
2155     AP_INIT_TAKE1("ShibRedirectToSSL", (config_fn_t)ap_set_string_slot,
2156         (void *) offsetof (shib_dir_config, szRedirectToSSL),
2157         OR_AUTHCFG, "Redirect non-SSL requests to designated port"),
2158 #ifdef SHIB_APACHE_24
2159     AP_INIT_FLAG("ShibRequestMapperAuthz", (config_fn_t)ap_set_flag_slot,
2160         (void *) offsetof (shib_dir_config, bRequestMapperAuthz),
2161         OR_AUTHCFG, "Support access control via shibboleth2.xml / RequestMapper"),
2162 #else
2163     AP_INIT_TAKE1("AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
2164         (void *) offsetof (shib_dir_config, szAuthGrpFile),
2165         OR_AUTHCFG, "Text file containing group names and member user IDs"),
2166     AP_INIT_TAKE1("ShibAccessControl", (config_fn_t)shib_set_acl_slot, nullptr,
2167         OR_AUTHCFG, "Set arbitrary Shibboleth access control plugin for content"),
2168     AP_INIT_FLAG("ShibRequireAll", (config_fn_t)ap_set_flag_slot,
2169         (void *) offsetof (shib_dir_config, bRequireAll),
2170         OR_AUTHCFG, "All require directives must match"),
2171     AP_INIT_FLAG("AuthzShibAuthoritative", (config_fn_t)ap_set_flag_slot,
2172         (void *) offsetof (shib_dir_config, bAuthoritative),
2173         OR_AUTHCFG, "Allow failed mod_shib htaccess authorization to fall through to other modules"),
2174     AP_INIT_FLAG("ShibCompatWith24", (config_fn_t)ap_set_flag_slot,
2175         (void *) offsetof (shib_dir_config, bCompatWith24),
2176         OR_AUTHCFG, "Support Apache 2.4-style require rules"),
2177 #endif
2178     AP_INIT_FLAG("ShibUseEnvironment", (config_fn_t)ap_set_flag_slot,
2179         (void *) offsetof (shib_dir_config, bUseEnvVars),
2180         OR_AUTHCFG, "Export attributes using environment variables (default)"),
2181     AP_INIT_FLAG("ShibUseHeaders", (config_fn_t)ap_set_flag_slot,
2182         (void *) offsetof (shib_dir_config, bUseHeaders),
2183         OR_AUTHCFG, "Export attributes using custom HTTP headers"),
2184     AP_INIT_FLAG("ShibExpireRedirects", (config_fn_t)ap_set_flag_slot,
2185         (void *) offsetof (shib_dir_config, bExpireRedirects),
2186         OR_AUTHCFG, "Expire SP-generated redirects"),
2187
2188     {nullptr}
2189 };
2190
2191 module AP_MODULE_DECLARE_DATA mod_shib = {
2192     STANDARD20_MODULE_STUFF,
2193     create_shib_dir_config,     /* create dir config */
2194     merge_shib_dir_config,      /* merge dir config --- default is to override */
2195     create_shib_server_config,  /* create server config */
2196     merge_shib_server_config,   /* merge server config */
2197     shib_cmds,                  /* command table */
2198     shib_register_hooks         /* register hooks */
2199 };
2200
2201 #endif
2202
2203 }