Tagging 2.4RC1 release.
[shibboleth/sp.git] / apache / mod_apache.cpp
1 /*
2  *  Copyright 2001-2010 Internet2
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /**
18  * mod_apache.cpp
19  *
20  * Apache module implementation.
21  */
22
23 #define SHIBSP_LITE
24
25 #ifdef SOLARIS2
26 #undef _XOPEN_SOURCE    // causes gethostname conflict in unistd.h
27 #endif
28
29 #ifdef WIN32
30 # define _CRT_NONSTDC_NO_DEPRECATE 1
31 # define _CRT_SECURE_NO_DEPRECATE 1
32 #endif
33
34 #include <shibsp/exceptions.h>
35 #include <shibsp/AbstractSPRequest.h>
36 #include <shibsp/AccessControl.h>
37 #include <shibsp/GSSRequest.h>
38 #include <shibsp/RequestMapper.h>
39 #include <shibsp/SPConfig.h>
40 #include <shibsp/ServiceProvider.h>
41 #include <shibsp/SessionCache.h>
42 #include <shibsp/attribute/Attribute.h>
43
44 #include <xercesc/util/XMLUniDefs.hpp>
45 #include <xercesc/util/regx/RegularExpression.hpp>
46 #include <xmltooling/XMLToolingConfig.h>
47 #include <xmltooling/util/NDC.h>
48 #include <xmltooling/util/Threads.h>
49 #include <xmltooling/util/XMLConstants.h>
50 #include <xmltooling/util/XMLHelper.h>
51
52 #ifdef WIN32
53 # include <winsock.h>
54 #endif
55
56 #undef _XPG4_2
57
58 // Apache specific header files
59 #include <httpd.h>
60 #include <http_config.h>
61 #include <http_protocol.h>
62 #include <http_main.h>
63 #define CORE_PRIVATE
64 #include <http_core.h>
65 #include <http_log.h>
66 #include <http_request.h>
67
68 #ifndef SHIB_APACHE_13
69 #include <apr_buckets.h>
70 #include <apr_strings.h>
71 #include <apr_pools.h>
72 #endif
73
74 #include <set>
75 #include <memory>
76 #include <fstream>
77 #include <sstream>
78 #include <stdexcept>
79
80 #ifdef HAVE_UNISTD_H
81 #include <unistd.h>             // for getpid()
82 #endif
83
84 using namespace shibsp;
85 using namespace xmltooling;
86 using namespace std;
87 using xercesc::RegularExpression;
88 using xercesc::XMLException;
89
90 extern "C" module MODULE_VAR_EXPORT mod_shib;
91
92 namespace {
93     char* g_szSHIBConfig = nullptr;
94     char* g_szSchemaDir = nullptr;
95     char* g_szPrefix = nullptr;
96     SPConfig* g_Config = nullptr;
97     string g_unsetHeaderValue,g_spoofKey;
98     bool g_checkSpoofing = true;
99     bool g_catchAll = false;
100 #ifndef SHIB_APACHE_13
101     char* g_szGSSContextKey = "mod_auth_gssapi:gss_ctx";
102 #endif
103     static const char* g_UserDataKey = "urn:mace:shibboleth:Apache:shib_check_user";
104 }
105
106 /* Apache 2.2.x headers must be accumulated and set in the output filter.
107    Apache 2.0.49+ supports the filter method.
108    Apache 1.3.x and lesser 2.0.x must write the headers directly. */
109
110 #if (defined(SHIB_APACHE_20) || defined(SHIB_APACHE_22)) && AP_MODULE_MAGIC_AT_LEAST(20020903,6)
111 #define SHIB_DEFERRED_HEADERS
112 #endif
113
114 /********************************************************************************/
115 // Basic Apache Configuration code.
116 //
117
118 // per-server module configuration structure
119 struct shib_server_config
120 {
121     char* szScheme;
122 };
123
124 // creates the per-server configuration
125 extern "C" void* create_shib_server_config(SH_AP_POOL* p, server_rec* s)
126 {
127     shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
128     sc->szScheme = nullptr;
129     return sc;
130 }
131
132 // overrides server configuration in virtual servers
133 extern "C" void* merge_shib_server_config (SH_AP_POOL* p, void* base, void* sub)
134 {
135     shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
136     shib_server_config* parent=(shib_server_config*)base;
137     shib_server_config* child=(shib_server_config*)sub;
138
139     if (child->szScheme)
140         sc->szScheme=ap_pstrdup(p,child->szScheme);
141     else if (parent->szScheme)
142         sc->szScheme=ap_pstrdup(p,parent->szScheme);
143     else
144         sc->szScheme=nullptr;
145
146     return sc;
147 }
148
149 // per-dir module configuration structure
150 struct shib_dir_config
151 {
152     SH_AP_TABLE* tSettings; // generic table of extensible settings
153
154     // RM Configuration
155     char* szAuthGrpFile;    // Auth GroupFile name
156     int bRequireAll;        // all "known" require directives must match, otherwise OR logic
157     int bAuthoritative;     // allow htaccess plugin to DECLINE when authz fails
158
159     // Content Configuration
160     char* szApplicationId;  // Shib applicationId value
161     char* szRequireWith;    // require a session using a specific initiator?
162     char* szRedirectToSSL;  // redirect non-SSL requests to SSL port
163     int bOff;               // flat-out disable all Shib processing
164     int bBasicHijack;       // activate for AuthType Basic?
165     int bRequireSession;    // require a session?
166     int bExportAssertion;   // export SAML assertion to the environment?
167     int bUseEnvVars;        // use environment?
168     int bUseHeaders;        // use headers?
169 };
170
171 // creates per-directory config structure
172 extern "C" void* create_shib_dir_config (SH_AP_POOL* p, char* d)
173 {
174     shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
175     dc->tSettings = nullptr;
176     dc->szAuthGrpFile = nullptr;
177     dc->bRequireAll = -1;
178     dc->bAuthoritative = -1;
179     dc->szApplicationId = nullptr;
180     dc->szRequireWith = nullptr;
181     dc->szRedirectToSSL = nullptr;
182     dc->bOff = -1;
183     dc->bBasicHijack = -1;
184     dc->bRequireSession = -1;
185     dc->bExportAssertion = -1;
186     dc->bUseEnvVars = -1;
187     dc->bUseHeaders = -1;
188     return dc;
189 }
190
191 // overrides server configuration in directories
192 extern "C" void* merge_shib_dir_config (SH_AP_POOL* p, void* base, void* sub)
193 {
194     shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
195     shib_dir_config* parent=(shib_dir_config*)base;
196     shib_dir_config* child=(shib_dir_config*)sub;
197
198     // The child supersedes any matching table settings in the parent.
199     dc->tSettings = nullptr;
200     if (parent->tSettings)
201         dc->tSettings = ap_copy_table(p, parent->tSettings);
202     if (child->tSettings) {
203         if (dc->tSettings)
204             ap_overlap_tables(dc->tSettings, child->tSettings, AP_OVERLAP_TABLES_SET);
205         else
206             dc->tSettings = ap_copy_table(p, child->tSettings);
207     }
208
209     if (child->szAuthGrpFile)
210         dc->szAuthGrpFile=ap_pstrdup(p,child->szAuthGrpFile);
211     else if (parent->szAuthGrpFile)
212         dc->szAuthGrpFile=ap_pstrdup(p,parent->szAuthGrpFile);
213     else
214         dc->szAuthGrpFile=nullptr;
215
216     if (child->szApplicationId)
217         dc->szApplicationId=ap_pstrdup(p,child->szApplicationId);
218     else if (parent->szApplicationId)
219         dc->szApplicationId=ap_pstrdup(p,parent->szApplicationId);
220     else
221         dc->szApplicationId=nullptr;
222
223     if (child->szRequireWith)
224         dc->szRequireWith=ap_pstrdup(p,child->szRequireWith);
225     else if (parent->szRequireWith)
226         dc->szRequireWith=ap_pstrdup(p,parent->szRequireWith);
227     else
228         dc->szRequireWith=nullptr;
229
230     if (child->szRedirectToSSL)
231         dc->szRedirectToSSL=ap_pstrdup(p,child->szRedirectToSSL);
232     else if (parent->szRedirectToSSL)
233         dc->szRedirectToSSL=ap_pstrdup(p,parent->szRedirectToSSL);
234     else
235         dc->szRedirectToSSL=nullptr;
236
237     dc->bOff=((child->bOff==-1) ? parent->bOff : child->bOff);
238     dc->bBasicHijack=((child->bBasicHijack==-1) ? parent->bBasicHijack : child->bBasicHijack);
239     dc->bRequireSession=((child->bRequireSession==-1) ? parent->bRequireSession : child->bRequireSession);
240     dc->bExportAssertion=((child->bExportAssertion==-1) ? parent->bExportAssertion : child->bExportAssertion);
241     dc->bRequireAll=((child->bRequireAll==-1) ? parent->bRequireAll : child->bRequireAll);
242     dc->bAuthoritative=((child->bAuthoritative==-1) ? parent->bAuthoritative : child->bAuthoritative);
243     dc->bUseEnvVars=((child->bUseEnvVars==-1) ? parent->bUseEnvVars : child->bUseEnvVars);
244     dc->bUseHeaders=((child->bUseHeaders==-1) ? parent->bUseHeaders : child->bUseHeaders);
245     return dc;
246 }
247
248 // per-request module structure
249 struct shib_request_config
250 {
251     SH_AP_TABLE *env;        // environment vars
252 #ifdef SHIB_DEFERRED_HEADERS
253     SH_AP_TABLE *hdr_out;    // headers to browser
254 #endif
255 };
256
257 // create a request record
258 static shib_request_config *init_request_config(request_rec *r)
259 {
260     shib_request_config* rc=(shib_request_config*)ap_pcalloc(r->pool,sizeof(shib_request_config));
261     ap_set_module_config (r->request_config, &mod_shib, rc);
262     memset(rc, 0, sizeof(shib_request_config));
263     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_init_rc");
264     return rc;
265 }
266
267 // generic global slot handlers
268 extern "C" const char* ap_set_global_string_slot(cmd_parms* parms, void*, const char* arg)
269 {
270     *((char**)(parms->info))=ap_pstrdup(parms->pool,arg);
271     return nullptr;
272 }
273
274 extern "C" const char* shib_set_server_string_slot(cmd_parms* parms, void*, const char* arg)
275 {
276     char* base=(char*)ap_get_module_config(parms->server->module_config,&mod_shib);
277     size_t offset=(size_t)parms->info;
278     *((char**)(base + offset))=ap_pstrdup(parms->pool,arg);
279     return nullptr;
280 }
281
282 extern "C" const char* shib_ap_set_file_slot(cmd_parms* parms,
283 #ifdef SHIB_APACHE_13
284                                              char* arg1, char* arg2
285 #else
286                                              void* arg1, const char* arg2
287 #endif
288                                              )
289 {
290   ap_set_file_slot(parms, arg1, arg2);
291   return DECLINE_CMD;
292 }
293
294 extern "C" const char* shib_table_set(cmd_parms* parms, shib_dir_config* dc, const char* arg1, const char* arg2)
295 {
296     if (!dc->tSettings)
297         dc->tSettings = ap_make_table(parms->pool, 4);
298     ap_table_set(dc->tSettings, arg1, arg2);
299     return nullptr;
300 }
301
302
303 class ShibTargetApache : public AbstractSPRequest
304 #if defined(HAVE_GSSAPI) && !defined(SHIB_APACHE_13)
305     , public GSSRequest
306 #endif
307 {
308   bool m_handler;
309   mutable string m_body;
310   mutable bool m_gotBody,m_firsttime;
311   mutable vector<string> m_certs;
312   set<string> m_allhttp;
313
314 public:
315   request_rec* m_req;
316   shib_dir_config* m_dc;
317   shib_server_config* m_sc;
318   shib_request_config* m_rc;
319
320   ShibTargetApache(request_rec* req, bool handler, bool shib_check_user)
321       : AbstractSPRequest(SHIBSP_LOGCAT".Apache"), m_handler(handler), m_gotBody(false),m_firsttime(true) {
322     m_sc = (shib_server_config*)ap_get_module_config(req->server->module_config, &mod_shib);
323     m_dc = (shib_dir_config*)ap_get_module_config(req->per_dir_config, &mod_shib);
324     m_rc = (shib_request_config*)ap_get_module_config(req->request_config, &mod_shib);
325     m_req = req;
326
327     setRequestURI(m_req->unparsed_uri);
328
329     if (shib_check_user && m_dc->bUseHeaders == 1) {
330         // Try and see if this request was already processed, to skip spoof checking.
331         if (!ap_is_initial_req(m_req)) {
332             m_firsttime = false;
333         }
334         else if (!g_spoofKey.empty()) {
335             const char* hdr = ap_table_get(m_req->headers_in, "Shib-Spoof-Check");
336             if (hdr && g_spoofKey == hdr)
337                 m_firsttime=false;
338         }
339
340         if (!m_firsttime)
341             log(SPDebug, "shib_check_user running more than once");
342     }
343   }
344   virtual ~ShibTargetApache() {}
345
346   const char* getScheme() const {
347     return m_sc->szScheme ? m_sc->szScheme : ap_http_method(m_req);
348   }
349   const char* getHostname() const {
350     return ap_get_server_name(m_req);
351   }
352   int getPort() const {
353     return ap_get_server_port(m_req);
354   }
355   const char* getMethod() const {
356     return m_req->method;
357   }
358   string getContentType() const {
359     const char* type = ap_table_get(m_req->headers_in, "Content-Type");
360     return type ? type : "";
361   }
362   long getContentLength() const {
363       return m_gotBody ? m_body.length() : m_req->remaining;
364   }
365   string getRemoteAddr() const {
366     string ret = AbstractSPRequest::getRemoteAddr();
367     return ret.empty() ? m_req->connection->remote_ip : ret;
368   }
369   void log(SPLogLevel level, const string& msg) const {
370     AbstractSPRequest::log(level,msg);
371     ap_log_rerror(
372         APLOG_MARK,
373         (level == SPDebug ? APLOG_DEBUG :
374         (level == SPInfo ? APLOG_INFO :
375         (level == SPWarn ? APLOG_WARNING :
376         (level == SPError ? APLOG_ERR : APLOG_CRIT))))|APLOG_NOERRNO,
377         SH_AP_R(m_req),
378         msg.c_str()
379         );
380   }
381   const char* getQueryString() const { return m_req->args; }
382   const char* getRequestBody() const {
383     if (m_gotBody || m_req->method_number==M_GET)
384         return m_body.c_str();
385 #ifdef SHIB_APACHE_13
386     // Read the posted data
387     if (ap_setup_client_block(m_req, REQUEST_CHUNKED_DECHUNK) != OK) {
388         m_gotBody=true;
389         log(SPError, "Apache function (setup_client_block) failed while reading request body.");
390         return m_body.c_str();
391     }
392     if (!ap_should_client_block(m_req)) {
393         m_gotBody=true;
394         log(SPError, "Apache function (should_client_block) failed while reading request body.");
395         return m_body.c_str();
396     }
397     if (m_req->remaining > 1024*1024)
398         throw opensaml::SecurityPolicyException("Blocked request body larger than 1M size limit.");
399     m_gotBody=true;
400     int len;
401     char buff[HUGE_STRING_LEN];
402     ap_hard_timeout("[mod_shib] getRequestBody", m_req);
403     while ((len=ap_get_client_block(m_req, buff, sizeof(buff))) > 0) {
404       ap_reset_timeout(m_req);
405       m_body.append(buff, len);
406     }
407     ap_kill_timeout(m_req);
408 #else
409     const char *data;
410     apr_size_t len;
411     int seen_eos = 0;
412     apr_bucket_brigade* bb = apr_brigade_create(m_req->pool, m_req->connection->bucket_alloc);
413     do {
414         apr_bucket *bucket;
415         apr_status_t rv = ap_get_brigade(m_req->input_filters, bb, AP_MODE_READBYTES, APR_BLOCK_READ, HUGE_STRING_LEN);
416         if (rv != APR_SUCCESS) {
417             log(SPError, "Apache function (ap_get_brigade) failed while reading request body.");
418             break;
419         }
420
421         for (bucket = APR_BRIGADE_FIRST(bb); bucket != APR_BRIGADE_SENTINEL(bb); bucket = APR_BUCKET_NEXT(bucket)) {
422             if (APR_BUCKET_IS_EOS(bucket)) {
423                 seen_eos = 1;
424                 break;
425             }
426
427             /* We can't do much with this. */
428             if (APR_BUCKET_IS_FLUSH(bucket))
429                 continue;
430
431             /* read */
432             apr_bucket_read(bucket, &data, &len, APR_BLOCK_READ);
433             if (len > 0)
434                 m_body.append(data, len);
435         }
436         apr_brigade_cleanup(bb);
437     } while (!seen_eos);
438     apr_brigade_destroy(bb);
439     m_gotBody=true;
440 #endif
441     return m_body.c_str();
442   }
443   void clearHeader(const char* rawname, const char* cginame) {
444     if (m_dc->bUseHeaders == 1) {
445        // ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_clear_header: hdr\n");
446         if (g_checkSpoofing && m_firsttime) {
447             if (m_allhttp.empty()) {
448                 // First time, so populate set with "CGI" versions of client-supplied headers.
449 #ifdef SHIB_APACHE_13
450                 array_header *hdrs_arr = ap_table_elts(m_req->headers_in);
451                 table_entry *hdrs = (table_entry *) hdrs_arr->elts;
452 #else
453                 const apr_array_header_t *hdrs_arr = apr_table_elts(m_req->headers_in);
454                 const apr_table_entry_t *hdrs = (const apr_table_entry_t *) hdrs_arr->elts;
455 #endif
456                 for (int i = 0; i < hdrs_arr->nelts; ++i) {
457                     if (!hdrs[i].key)
458                         continue;
459                     string cgiversion("HTTP_");
460                     const char* pch = hdrs[i].key;
461                     while (*pch) {
462                         cgiversion += (isalnum(*pch) ? toupper(*pch) : '_');
463                         pch++;
464                     }
465                     m_allhttp.insert(cgiversion);
466                 }
467             }
468
469             if (m_allhttp.count(cginame) > 0)
470                 throw opensaml::SecurityPolicyException("Attempt to spoof header ($1) was detected.", params(1, rawname));
471         }
472         ap_table_unset(m_req->headers_in, rawname);
473         ap_table_set(m_req->headers_in, rawname, g_unsetHeaderValue.c_str());
474     }
475   }
476   void setHeader(const char* name, const char* value) {
477     if (m_dc->bUseEnvVars != 0) {
478        if (!m_rc) {
479           // this happens on subrequests
480           // ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_setheader: no_m_rc\n");
481           m_rc = init_request_config(m_req);
482        }
483        if (!m_rc->env)
484            m_rc->env = ap_make_table(m_req->pool, 10);
485        // ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_set_env: %s=%s\n", name, value?value:"Null");
486        ap_table_set(m_rc->env, name, value ? value : "");
487     }
488     if (m_dc->bUseHeaders == 1)
489        ap_table_set(m_req->headers_in, name, value);
490   }
491   string getHeader(const char* name) const {
492     const char* hdr = ap_table_get(m_req->headers_in, name);
493     return string(hdr ? hdr : "");
494   }
495   string getSecureHeader(const char* name) const {
496     if (m_dc->bUseEnvVars != 0) {
497        const char *hdr;
498        if (m_rc && m_rc->env)
499            hdr = ap_table_get(m_rc->env, name);
500        else
501            hdr = nullptr;
502        return string(hdr ? hdr : "");
503     }
504     return getHeader(name);
505   }
506   void setRemoteUser(const char* user) {
507       SH_AP_USER(m_req) = user ? ap_pstrdup(m_req->pool, user) : nullptr;
508       if (m_dc->bUseHeaders == 1) {
509           if (user) {
510               ap_table_set(m_req->headers_in, "REMOTE_USER", user);
511           }
512           else {
513               ap_table_unset(m_req->headers_in, "REMOTE_USER");
514               ap_table_set(m_req->headers_in, "REMOTE_USER", g_unsetHeaderValue.c_str());
515           }
516       }
517   }
518   string getRemoteUser() const {
519     return string(SH_AP_USER(m_req) ? SH_AP_USER(m_req) : "");
520   }
521   void setAuthType(const char* authtype) {
522       if (authtype && m_dc->bBasicHijack == 1)
523           authtype = "Basic";
524       SH_AP_AUTH_TYPE(m_req) = authtype ? ap_pstrdup(m_req->pool, authtype) : nullptr;
525   }
526   string getAuthType() const {
527     return string(SH_AP_AUTH_TYPE(m_req) ? SH_AP_AUTH_TYPE(m_req) : "");
528   }
529   void setContentType(const char* type) {
530       m_req->content_type = ap_psprintf(m_req->pool, type);
531   }
532   void setResponseHeader(const char* name, const char* value) {
533    HTTPResponse::setResponseHeader(name, value);
534 #ifdef SHIB_DEFERRED_HEADERS
535    if (!m_rc)
536       // this happens on subrequests
537       m_rc = init_request_config(m_req);
538     if (m_handler) {
539         if (!m_rc->hdr_out)
540             m_rc->hdr_out = ap_make_table(m_req->pool, 5);
541         ap_table_add(m_rc->hdr_out, name, value);
542     }
543     else
544 #endif
545     ap_table_add(m_req->err_headers_out, name, value);
546   }
547   long sendResponse(istream& in, long status) {
548     if (status != XMLTOOLING_HTTP_STATUS_OK)
549         m_req->status = status;
550     ap_send_http_header(m_req);
551     char buf[1024];
552     while (in) {
553         in.read(buf,1024);
554         ap_rwrite(buf,in.gcount(),m_req);
555     }
556 #if (defined(SHIB_APACHE_20) || defined(SHIB_APACHE_22))
557     if (status != XMLTOOLING_HTTP_STATUS_OK && status != XMLTOOLING_HTTP_STATUS_ERROR)
558         return status;
559 #endif
560     return DONE;
561   }
562   long sendRedirect(const char* url) {
563     HTTPResponse::sendRedirect(url);
564     ap_table_set(m_req->headers_out, "Location", url);
565     return REDIRECT;
566   }
567   const vector<string>& getClientCertificates() const {
568       if (m_certs.empty()) {
569           const char* cert = ap_table_get(m_req->subprocess_env, "SSL_CLIENT_CERT");
570           if (cert)
571               m_certs.push_back(cert);
572           int i = 0;
573           do {
574               cert = ap_table_get(m_req->subprocess_env, ap_psprintf(m_req->pool, "SSL_CLIENT_CERT_CHAIN_%d", i++));
575               if (cert)
576                   m_certs.push_back(cert);
577           } while (cert);
578       }
579       return m_certs;
580   }
581   long returnDecline(void) { return DECLINED; }
582   long returnOK(void) { return OK; }
583 #if defined(HAVE_GSSAPI) && !defined(SHIB_APACHE_13)
584   gss_ctx_id_t getGSSContext() const {
585     gss_ctx_id_t ctx = GSS_C_NO_CONTEXT;
586     apr_pool_userdata_get((void**)&ctx, g_szGSSContextKey, m_req->pool);
587     return ctx;
588   }
589 #endif
590 };
591
592 /********************************************************************************/
593 // Apache handlers
594
595 extern "C" int shib_check_user(request_rec* r)
596 {
597   // Short-circuit entirely?
598   if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
599     return DECLINED;
600
601   ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_check_user(%d): ENTER", (int)getpid());
602
603   ostringstream threadid;
604   threadid << "[" << getpid() << "] shib_check_user" << '\0';
605   xmltooling::NDC ndc(threadid.str().c_str());
606
607   try {
608     ShibTargetApache sta(r,false,true);
609
610     // Check user authentication and export information, then set the handler bypass
611     pair<bool,long> res = sta.getServiceProvider().doAuthentication(sta,true);
612     apr_pool_userdata_setn((const void*)42,g_UserDataKey,nullptr,r->pool);
613     // If directed, install a spoof key to recognize when we've already cleared headers.
614     if (!g_spoofKey.empty() && (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bUseHeaders==1))
615         ap_table_set(r->headers_in, "Shib-Spoof-Check", g_spoofKey.c_str());
616     if (res.first) return res.second;
617
618     // user auth was okay -- export the assertions now
619     res = sta.getServiceProvider().doExport(sta);
620     if (res.first) return res.second;
621
622     // export happened successfully..  this user is ok.
623     return OK;
624   }
625   catch (exception& e) {
626     ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user threw an exception: %s", e.what());
627     return SERVER_ERROR;
628   }
629   catch (...) {
630     ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user threw an unknown exception!");
631     if (g_catchAll)
632       return SERVER_ERROR;
633     throw;
634   }
635 }
636
637 extern "C" int shib_handler(request_rec* r)
638 {
639   // Short-circuit entirely?
640   if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
641     return DECLINED;
642
643   ostringstream threadid;
644   threadid << "[" << getpid() << "] shib_handler" << '\0';
645   xmltooling::NDC ndc(threadid.str().c_str());
646
647 #ifndef SHIB_APACHE_13
648   // With 2.x, this handler always runs, though last.
649   // We check if shib_check_user ran, because it will detect a handler request
650   // and dispatch it directly.
651   void* data;
652   apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
653   if (data==(const void*)42) {
654     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler skipped since check_user ran");
655     return DECLINED;
656   }
657 #endif
658
659   ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler(%d): ENTER: %s", (int)getpid(), r->handler);
660
661   try {
662     ShibTargetApache sta(r,true,false);
663
664     pair<bool,long> res = sta.getServiceProvider().doHandler(sta);
665     if (res.first) return res.second;
666
667     ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "doHandler() did not do anything.");
668     return SERVER_ERROR;
669   }
670   catch (exception& e) {
671     ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler threw an exception: %s", e.what());
672     return SERVER_ERROR;
673   }
674   catch (...) {
675     ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler threw an unknown exception!");
676     if (g_catchAll)
677       return SERVER_ERROR;
678     throw;
679   }
680 }
681
682 /*
683  * shib_auth_checker() -- a simple resource manager to
684  * process the .htaccess settings
685  */
686 extern "C" int shib_auth_checker(request_rec* r)
687 {
688   // Short-circuit entirely?
689   if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
690     return DECLINED;
691
692   ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_auth_checker(%d): ENTER", (int)getpid());
693
694   ostringstream threadid;
695   threadid << "[" << getpid() << "] shib_auth_checker" << '\0';
696   xmltooling::NDC ndc(threadid.str().c_str());
697
698   try {
699     ShibTargetApache sta(r,false,false);
700
701     pair<bool,long> res = sta.getServiceProvider().doAuthorization(sta);
702     if (res.first) return res.second;
703
704     // The SP method should always return true, so if we get this far, something unusual happened.
705     // Just let Apache (or some other module) decide what to do.
706     return DECLINED;
707   }
708   catch (exception& e) {
709     ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an exception: %s", e.what());
710     return SERVER_ERROR;
711   }
712   catch (...) {
713     ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an unknown exception!");
714     if (g_catchAll)
715       return SERVER_ERROR;
716     throw;
717   }
718 }
719
720 // Access control plugin that enforces htaccess rules
721 class htAccessControl : virtual public AccessControl
722 {
723 public:
724     htAccessControl() {}
725     ~htAccessControl() {}
726     Lockable* lock() {return this;}
727     void unlock() {}
728     aclresult_t authorized(const SPRequest& request, const Session* session) const;
729 private:
730     bool checkAttribute(const SPRequest& request, const Attribute* attr, const char* toMatch, RegularExpression* re) const;
731 };
732
733 AccessControl* htAccessFactory(const xercesc::DOMElement* const & e)
734 {
735     return new htAccessControl();
736 }
737
738 class ApacheRequestMapper : public virtual RequestMapper, public virtual PropertySet
739 {
740 public:
741     ApacheRequestMapper(const xercesc::DOMElement* e);
742     ~ApacheRequestMapper() { delete m_mapper; delete m_htaccess; delete m_staKey; delete m_propsKey; }
743     Lockable* lock() { return m_mapper->lock(); }
744     void unlock() { m_staKey->setData(nullptr); m_propsKey->setData(nullptr); m_mapper->unlock(); }
745     Settings getSettings(const HTTPRequest& request) const;
746
747     const PropertySet* getParent() const { return nullptr; }
748     void setParent(const PropertySet*) {}
749     pair<bool,bool> getBool(const char* name, const char* ns=nullptr) const;
750     pair<bool,const char*> getString(const char* name, const char* ns=nullptr) const;
751     pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=nullptr) const;
752     pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=nullptr) const;
753     pair<bool,int> getInt(const char* name, const char* ns=nullptr) const;
754     void getAll(map<string,const char*>& properties) const;
755     const PropertySet* getPropertySet(const char* name, const char* ns=shibspconstants::ASCII_SHIB2SPCONFIG_NS) const;
756     const xercesc::DOMElement* getElement() const;
757
758 private:
759     RequestMapper* m_mapper;
760     ThreadKey* m_staKey;
761     ThreadKey* m_propsKey;
762     AccessControl* m_htaccess;
763 };
764
765 RequestMapper* ApacheRequestMapFactory(const xercesc::DOMElement* const & e)
766 {
767     return new ApacheRequestMapper(e);
768 }
769
770 ApacheRequestMapper::ApacheRequestMapper(const xercesc::DOMElement* e) : m_mapper(nullptr), m_staKey(nullptr), m_propsKey(nullptr), m_htaccess(nullptr)
771 {
772     m_mapper=SPConfig::getConfig().RequestMapperManager.newPlugin(XML_REQUEST_MAPPER,e);
773     m_htaccess=new htAccessControl();
774     m_staKey=ThreadKey::create(nullptr);
775     m_propsKey=ThreadKey::create(nullptr);
776 }
777
778 RequestMapper::Settings ApacheRequestMapper::getSettings(const HTTPRequest& request) const
779 {
780     Settings s=m_mapper->getSettings(request);
781     m_staKey->setData((void*)dynamic_cast<const ShibTargetApache*>(&request));
782     m_propsKey->setData((void*)s.first);
783     return pair<const PropertySet*,AccessControl*>(this,s.second ? s.second : m_htaccess);
784 }
785
786 pair<bool,bool> ApacheRequestMapper::getBool(const char* name, const char* ns) const
787 {
788     const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
789     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
790     if (sta && !ns) {
791         // Override Apache-settable boolean properties.
792         if (name && !strcmp(name,"requireSession") && sta->m_dc->bRequireSession != -1)
793             return make_pair(true, sta->m_dc->bRequireSession==1);
794         else if (name && !strcmp(name,"exportAssertion") && sta->m_dc->bExportAssertion != -1)
795             return make_pair(true, sta->m_dc->bExportAssertion==1);
796         else if (sta->m_dc->tSettings) {
797             const char* prop = ap_table_get(sta->m_dc->tSettings, name);
798             if (prop)
799                 return make_pair(true, !strcmp(prop, "true") || !strcmp(prop, "1") || !strcmp(prop, "On"));
800         }
801     }
802     return s ? s->getBool(name,ns) : make_pair(false,false);
803 }
804
805 pair<bool,const char*> ApacheRequestMapper::getString(const char* name, const char* ns) const
806 {
807     const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
808     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
809     if (sta && !ns) {
810         // Override Apache-settable string properties.
811         if (name && !strcmp(name,"authType")) {
812             const char *auth_type=ap_auth_type(sta->m_req);
813             if (auth_type) {
814                 // Check for Basic Hijack
815                 if (!strcasecmp(auth_type, "basic") && sta->m_dc->bBasicHijack == 1)
816                     auth_type = "shibboleth";
817                 return make_pair(true,auth_type);
818             }
819         }
820         else if (name && !strcmp(name,"applicationId") && sta->m_dc->szApplicationId)
821             return pair<bool,const char*>(true,sta->m_dc->szApplicationId);
822         else if (name && !strcmp(name,"requireSessionWith") && sta->m_dc->szRequireWith)
823             return pair<bool,const char*>(true,sta->m_dc->szRequireWith);
824         else if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
825             return pair<bool,const char*>(true,sta->m_dc->szRedirectToSSL);
826         else if (sta->m_dc->tSettings) {
827             const char* prop = ap_table_get(sta->m_dc->tSettings, name);
828             if (prop)
829                 return make_pair(true, prop);
830         }
831     }
832     return s ? s->getString(name,ns) : pair<bool,const char*>(false,nullptr);
833 }
834
835 pair<bool,const XMLCh*> ApacheRequestMapper::getXMLString(const char* name, const char* ns) const
836 {
837     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
838     return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,nullptr);
839 }
840
841 pair<bool,unsigned int> ApacheRequestMapper::getUnsignedInt(const char* name, const char* ns) const
842 {
843     const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
844     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
845     if (sta && !ns) {
846         // Override Apache-settable int properties.
847         if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
848             return pair<bool,unsigned int>(true, strtol(sta->m_dc->szRedirectToSSL, nullptr, 10));
849         else if (sta->m_dc->tSettings) {
850             const char* prop = ap_table_get(sta->m_dc->tSettings, name);
851             if (prop)
852                 return pair<bool,unsigned int>(true, atoi(prop));
853         }
854     }
855     return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
856 }
857
858 pair<bool,int> ApacheRequestMapper::getInt(const char* name, const char* ns) const
859 {
860     const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
861     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
862     if (sta && !ns) {
863         // Override Apache-settable int properties.
864         if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
865             return pair<bool,int>(true,atoi(sta->m_dc->szRedirectToSSL));
866         else if (sta->m_dc->tSettings) {
867             const char* prop = ap_table_get(sta->m_dc->tSettings, name);
868             if (prop)
869                 return make_pair(true, atoi(prop));
870         }
871     }
872     return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
873 }
874
875 static int _rm_get_all_table_walk(void *v, const char *key, const char *value)
876 {
877     reinterpret_cast<map<string,const char*>*>(v)->insert(pair<string,const char*>(key, value));
878     return 1;
879 }
880
881 void ApacheRequestMapper::getAll(map<string,const char*>& properties) const
882 {
883     const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
884     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
885
886     if (s)
887         s->getAll(properties);
888     if (!sta)
889         return;
890
891     const char* auth_type=ap_auth_type(sta->m_req);
892     if (auth_type) {
893         // Check for Basic Hijack
894         if (!strcasecmp(auth_type, "basic") && sta->m_dc->bBasicHijack == 1)
895             auth_type = "shibboleth";
896         properties["authType"] = auth_type;
897     }
898
899     if (sta->m_dc->szApplicationId)
900         properties["applicationId"] = sta->m_dc->szApplicationId;
901     if (sta->m_dc->szRequireWith)
902         properties["requireSessionWith"] = sta->m_dc->szRequireWith;
903     if (sta->m_dc->szRedirectToSSL)
904         properties["redirectToSSL"] = sta->m_dc->szRedirectToSSL;
905     if (sta->m_dc->bRequireSession != 0)
906         properties["requireSession"] = (sta->m_dc->bRequireSession==1) ? "true" : "false";
907     if (sta->m_dc->bExportAssertion != 0)
908         properties["exportAssertion"] = (sta->m_dc->bExportAssertion==1) ? "true" : "false";
909
910     if (sta->m_dc->tSettings)
911         ap_table_do(_rm_get_all_table_walk, &properties, sta->m_dc->tSettings, nullptr);
912 }
913
914 const PropertySet* ApacheRequestMapper::getPropertySet(const char* name, const char* ns) const
915 {
916     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
917     return s ? s->getPropertySet(name,ns) : nullptr;
918 }
919
920 const xercesc::DOMElement* ApacheRequestMapper::getElement() const
921 {
922     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
923     return s ? s->getElement() : nullptr;
924 }
925
926 static SH_AP_TABLE* groups_for_user(request_rec* r, const char* user, char* grpfile)
927 {
928     SH_AP_CONFIGFILE* f;
929     SH_AP_TABLE* grps=ap_make_table(r->pool,15);
930     char l[MAX_STRING_LEN];
931     const char *group_name, *ll, *w;
932
933 #ifdef SHIB_APACHE_13
934     if (!(f=ap_pcfg_openfile(r->pool,grpfile))) {
935 #else
936     if (ap_pcfg_openfile(&f,r->pool,grpfile) != APR_SUCCESS) {
937 #endif
938         ap_log_rerror(APLOG_MARK,APLOG_DEBUG,SH_AP_R(r),"groups_for_user() could not open group file: %s\n",grpfile);
939         return nullptr;
940     }
941
942     SH_AP_POOL* sp;
943 #ifdef SHIB_APACHE_13
944     sp=ap_make_sub_pool(r->pool);
945 #else
946     if (apr_pool_create(&sp,r->pool) != APR_SUCCESS) {
947         ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,
948             "groups_for_user() could not create a subpool");
949         return nullptr;
950     }
951 #endif
952
953     while (!(ap_cfg_getline(l,MAX_STRING_LEN,f))) {
954         if ((*l=='#') || (!*l))
955             continue;
956         ll = l;
957         ap_clear_pool(sp);
958
959         group_name=ap_getword(sp,&ll,':');
960
961         while (*ll) {
962             w=ap_getword_conf(sp,&ll);
963             if (!strcmp(w,user)) {
964                 ap_table_setn(grps,ap_pstrdup(r->pool,group_name),"in");
965                 break;
966             }
967         }
968     }
969     ap_cfg_closefile(f);
970     ap_destroy_pool(sp);
971     return grps;
972 }
973
974 bool htAccessControl::checkAttribute(const SPRequest& request, const Attribute* attr, const char* toMatch, RegularExpression* re) const
975 {
976     bool caseSensitive = attr->isCaseSensitive();
977     const vector<string>& vals = attr->getSerializedValues();
978     for (vector<string>::const_iterator v=vals.begin(); v!=vals.end(); ++v) {
979         if (re) {
980             auto_arrayptr<XMLCh> trans(fromUTF8(v->c_str()));
981             if (re->matches(trans.get())) {
982                 if (request.isPriorityEnabled(SPRequest::SPDebug))
983                     request.log(SPRequest::SPDebug, string("htaccess: expecting regexp ") + toMatch + ", got " + *v + ": acccepted");
984                 return true;
985             }
986         }
987         else if ((caseSensitive && *v == toMatch) || (!caseSensitive && !strcasecmp(v->c_str(), toMatch))) {
988             if (request.isPriorityEnabled(SPRequest::SPDebug))
989                 request.log(SPRequest::SPDebug, string("htaccess: expecting ") + toMatch + ", got " + *v + ": accepted");
990             return true;
991         }
992         else if (request.isPriorityEnabled(SPRequest::SPDebug)) {
993             request.log(SPRequest::SPDebug, string("htaccess: expecting ") + toMatch + ", got " + *v + ": rejected");
994         }
995     }
996     return false;
997 }
998
999 AccessControl::aclresult_t htAccessControl::authorized(const SPRequest& request, const Session* session) const
1000 {
1001     // Make sure the object is our type.
1002     const ShibTargetApache* sta=dynamic_cast<const ShibTargetApache*>(&request);
1003     if (!sta)
1004         throw ConfigurationException("Request wrapper object was not of correct type.");
1005
1006     // mod_auth clone
1007
1008     int m=sta->m_req->method_number;
1009     bool method_restricted=false;
1010     const char *t, *w;
1011
1012     const array_header* reqs_arr=ap_requires(sta->m_req);
1013     if (!reqs_arr)
1014         return shib_acl_indeterminate;  // should never happen
1015
1016     require_line* reqs=(require_line*)reqs_arr->elts;
1017
1018     for (int x=0; x<reqs_arr->nelts; x++) {
1019         // This rule should be completely ignored, the method doesn't fit.
1020         // The rule just doesn't exist for our purposes.
1021         if (!(reqs[x].method_mask & (1 << m)))
1022             continue;
1023
1024         method_restricted=true; // this lets us know at the end that at least one rule was potentially enforcable.
1025
1026         // Tracks status of this rule's evaluation.
1027         bool status = false;
1028
1029         string remote_user = request.getRemoteUser();
1030
1031         t = reqs[x].requirement;
1032         w = ap_getword_white(sta->m_req->pool, &t);
1033
1034         if (!strcasecmp(w,"shibboleth")) {
1035             // This is a dummy rule needed because Apache conflates authn and authz.
1036             // Without some require rule, AuthType is ignored and no check_user hooks run.
1037             status = true;  // treat it as an "accepted" rule
1038         }
1039         else if (!strcmp(w,"valid-user") && session) {
1040             request.log(SPRequest::SPDebug, "htaccess: accepting valid-user based on active session");
1041             status = true;
1042         }
1043         else if (!strcmp(w,"user") && !remote_user.empty()) {
1044             bool regexp = false;
1045             while (*t) {
1046                 w = ap_getword_conf(sta->m_req->pool,&t);
1047                 if (*w == '~') {
1048                     regexp = true;
1049                     continue;
1050                 }
1051                 else if (*w == '!') {
1052                     // A negated rule presumes success unless a match is found.
1053                     status = true;
1054                     if (*(w+1) == '~')
1055                         regexp = true;
1056                     continue;
1057                 }
1058
1059                 // Figure out if there's a match.
1060                 bool match = false;
1061                 if (regexp) {
1062                     try {
1063                         // To do regex matching, we have to convert from UTF-8.
1064                         auto_arrayptr<XMLCh> trans(fromUTF8(w));
1065                         RegularExpression re(trans.get());
1066                         auto_arrayptr<XMLCh> trans2(fromUTF8(remote_user.c_str()));
1067                         match = re.matches(trans2.get());
1068                     }
1069                     catch (XMLException& ex) {
1070                         auto_ptr_char tmp(ex.getMessage());
1071                         request.log(SPRequest::SPError,
1072                             string("htaccess plugin caught exception while parsing regular expression (") + w + "): " + tmp.get());
1073                     }
1074                 }
1075                 else if (remote_user == w) {
1076                     match = true;
1077                 }
1078
1079                 if (match) {
1080                     // If we matched, then we're done with this rule either way and we flip status to reflect the outcome.
1081                     status = !status;
1082                     if (request.isPriorityEnabled(SPRequest::SPDebug))
1083                         request.log(SPRequest::SPDebug,
1084                             string("htaccess: require user ") + (!status ? "rejecting (" : "accepting (") + remote_user + ")");
1085                     break;
1086                 }
1087             }
1088         }
1089         else if (!strcmp(w,"group")  && !remote_user.empty()) {
1090             SH_AP_TABLE* grpstatus = nullptr;
1091             if (sta->m_dc->szAuthGrpFile) {
1092                 if (request.isPriorityEnabled(SPRequest::SPDebug))
1093                     request.log(SPRequest::SPDebug,string("htaccess plugin using groups file: ") + sta->m_dc->szAuthGrpFile);
1094                 grpstatus = groups_for_user(sta->m_req,remote_user.c_str(),sta->m_dc->szAuthGrpFile);
1095             }
1096
1097             while (*t) {
1098                 w = ap_getword_conf(sta->m_req->pool,&t);
1099                 if (*w == '!') {
1100                     // A negated rule presumes success unless a match is found.
1101                     status = true;
1102                     continue;
1103                 }
1104
1105                 if (grpstatus && ap_table_get(grpstatus,w)) {
1106                     // If we matched, then we're done with this rule either way and we flip status to reflect the outcome.
1107                     status = !status;
1108                     request.log(SPRequest::SPDebug, string("htaccess: require group ") + (!status ? "rejecting (" : "accepting (") + w + ")");
1109                     break;
1110                 }
1111             }
1112         }
1113         else if (!strcmp(w,"authnContextClassRef") || !strcmp(w,"authnContextDeclRef")) {
1114             const char* ref = !strcmp(w,"authnContextClassRef") ? session->getAuthnContextClassRef() : session->getAuthnContextDeclRef();
1115             if (ref && *ref) {
1116                 bool regexp = false;
1117                 while (ref && *t) {
1118                     w = ap_getword_conf(sta->m_req->pool,&t);
1119                     if (*w == '~') {
1120                         regexp=true;
1121                         continue;
1122                     }
1123                     else if (*w == '!') {
1124                         // A negated rule presumes success unless a match is found.
1125                         status = true;
1126                         if (*(w+1)=='~')
1127                             regexp = true;
1128                         continue;
1129                     }
1130
1131                     // Figure out if there's a match.
1132                     bool match = false;
1133                     if (regexp) {
1134                         try {
1135                             // To do regex matching, we have to convert from UTF-8.
1136                             RegularExpression re(w);
1137                             match = re.matches(ref);
1138                         }
1139                         catch (XMLException& ex) {
1140                             auto_ptr_char tmp(ex.getMessage());
1141                             request.log(SPRequest::SPError,
1142                                 string("htaccess plugin caught exception while parsing regular expression (") + w + "): " + tmp.get());
1143                         }
1144                     }
1145                     else if (!strcmp(w,ref)) {
1146                         match = true;
1147                     }
1148
1149                     if (match) {
1150                         // If we matched, then we're done with this rule either way and we flip status to reflect the outcome.
1151                         status = !status;
1152                         if (request.isPriorityEnabled(SPRequest::SPDebug))
1153                             request.log(SPRequest::SPDebug,
1154                                 string("htaccess: require authnContext ") + (!status ? "rejecting (" : "accepting (") + ref + ")");
1155                         break;
1156                     }
1157                 }
1158             }
1159             else if (request.isPriorityEnabled(SPRequest::SPDebug)) {
1160                 request.log(SPRequest::SPDebug, "htaccess: require authnContext rejecting session with no context associated");
1161             }
1162         }
1163         else if (!session) {
1164             request.log(SPRequest::SPError, string("htaccess: require ") + w + " not given a valid session, are you using lazy sessions?");
1165         }
1166         else {
1167             // Find the attribute(s) matching the require rule.
1168             pair<multimap<string,const Attribute*>::const_iterator,multimap<string,const Attribute*>::const_iterator> attrs =
1169                 session->getIndexedAttributes().equal_range(w);
1170
1171             bool regexp=false;
1172             while (!status && attrs.first!=attrs.second && *t) {
1173                 w=ap_getword_conf(sta->m_req->pool,&t);
1174                 if (*w=='~') {
1175                     regexp=true;
1176                     continue;
1177                 }
1178
1179                 try {
1180                     auto_ptr<RegularExpression> re;
1181                     if (regexp) {
1182                         delete re.release();
1183                         auto_arrayptr<XMLCh> trans(fromUTF8(w));
1184                         auto_ptr<xercesc::RegularExpression> temp(new xercesc::RegularExpression(trans.get()));
1185                         re=temp;
1186                     }
1187                     
1188                     pair<multimap<string,const Attribute*>::const_iterator,multimap<string,const Attribute*>::const_iterator> attrs2(attrs);
1189                     for (; !status && attrs2.first!=attrs2.second; ++attrs2.first) {
1190                         if (checkAttribute(request, attrs2.first->second, w, regexp ? re.get() : nullptr)) {
1191                             status = true;
1192                         }
1193                     }
1194                 }
1195                 catch (XMLException& ex) {
1196                     auto_ptr_char tmp(ex.getMessage());
1197                     request.log(SPRequest::SPError,
1198                         string("htaccess plugin caught exception while parsing regular expression (") + w + "): " + tmp.get()
1199                         );
1200                 }
1201             }
1202         }
1203
1204         // If status is false, we found a rule we couldn't satisfy.
1205         // Could be an unknown rule to us, or it just didn't match.
1206
1207         if (status && sta->m_dc->bRequireAll != 1) {
1208             // If we're not insisting that all rules be met, then we're done.
1209             request.log(SPRequest::SPDebug, "htaccess: a rule was successful, granting access");
1210             return shib_acl_true;
1211         }
1212         else if (!status && sta->m_dc->bRequireAll == 1) {
1213             // If we're insisting that all rules be met, which is not something Apache really handles well,
1214             // then we either return false or indeterminate based on the authoritative option, which defaults on.
1215             if (sta->m_dc->bAuthoritative != 0) {
1216                 request.log(SPRequest::SPDebug, "htaccess: a rule was unsuccessful, denying access");
1217                 return shib_acl_false;
1218             }
1219
1220             request.log(SPRequest::SPDebug, "htaccess: a rule was unsuccessful but not authoritative, leaving it up to Apache");
1221             return shib_acl_indeterminate;
1222         }
1223
1224         // Otherwise, we keep going. If we're requring all, then we have to check every rule.
1225         // If not we just didn't find a successful rule yet, so we keep going anyway.
1226     }
1227
1228     // If we get here, we either "failed" or we're in require all mode (but not both).
1229     // If no rules possibly apply or we insisted that all rules check out, then we're good.
1230     if (!method_restricted) {
1231         request.log(SPRequest::SPDebug, "htaccess: no rules applied to this request method, granting access");
1232         return shib_acl_true;
1233     }
1234     else if (sta->m_dc->bRequireAll == 1) {
1235         request.log(SPRequest::SPDebug, "htaccess: all rules successful, granting access");
1236         return shib_acl_true;
1237     }
1238     else if (sta->m_dc->bAuthoritative != 0) {
1239         request.log(SPRequest::SPDebug, "htaccess: no rules were successful, denying access");
1240         return shib_acl_false;
1241     }
1242
1243     request.log(SPRequest::SPDebug, "htaccess: no rules were successful but not authoritative, leaving it up to Apache");
1244     return shib_acl_indeterminate;
1245 }
1246
1247
1248 // Initial look at a request - create the per-request structure
1249 static int shib_post_read(request_rec *r)
1250 {
1251     shib_request_config* rc = init_request_config(r);
1252     //ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_post_read");
1253     return DECLINED;
1254 }
1255
1256 // fixups: set environment vars
1257
1258 extern "C" int shib_fixups(request_rec* r)
1259 {
1260   shib_request_config *rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
1261   shib_dir_config *dc = (shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib);
1262   if (dc->bOff==1 || dc->bUseEnvVars==0)
1263     return DECLINED;
1264
1265   ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_fixup(%d): ENTER", (int)getpid());
1266
1267   if (rc==nullptr || rc->env==nullptr || ap_is_empty_table(rc->env))
1268         return DECLINED;
1269
1270   ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_fixup adding %d vars", ap_table_elts(rc->env)->nelts);
1271   r->subprocess_env = ap_overlay_tables(r->pool, r->subprocess_env, rc->env);
1272
1273   return OK;
1274 }
1275
1276 #ifdef SHIB_APACHE_13
1277 /*
1278  * shib_child_exit()
1279  *  Cleanup the (per-process) pool info.
1280  */
1281 extern "C" void shib_child_exit(server_rec* s, SH_AP_POOL* p)
1282 {
1283     if (g_Config) {
1284         ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit(%d) dealing with g_Config..", (int)getpid());
1285         g_Config->term();
1286         g_Config = nullptr;
1287         ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit() done");
1288     }
1289 }
1290 #else
1291 /*
1292  * shib_exit()
1293  *  Apache 2.x doesn't allow for per-child cleanup, causes CGI forks to hang.
1294  */
1295 extern "C" apr_status_t shib_exit(void* data)
1296 {
1297     if (g_Config) {
1298         g_Config->term();
1299         g_Config = nullptr;
1300     }
1301     ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,0,nullptr,"shib_exit() done");
1302     return OK;
1303 }
1304 #endif
1305
1306 /*
1307  * shire_child_init()
1308  *  Things to do when the child process is initialized.
1309  *  (or after the configs are read in apache-2)
1310  */
1311 #ifdef SHIB_APACHE_13
1312 extern "C" void shib_child_init(server_rec* s, SH_AP_POOL* p)
1313 #else
1314 extern "C" void shib_child_init(apr_pool_t* p, server_rec* s)
1315 #endif
1316 {
1317     // Initialize runtime components.
1318
1319     ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init(%d) starting", (int)getpid());
1320
1321     if (g_Config) {
1322         ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() already initialized!");
1323         exit(1);
1324     }
1325
1326     g_Config=&SPConfig::getConfig();
1327     g_Config->setFeatures(
1328         SPConfig::Listener |
1329         SPConfig::Caching |
1330         SPConfig::RequestMapping |
1331         SPConfig::InProcess |
1332         SPConfig::Logging |
1333         SPConfig::Handlers
1334         );
1335     if (!g_Config->init(g_szSchemaDir, g_szPrefix)) {
1336         ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize libraries");
1337         exit(1);
1338     }
1339     g_Config->AccessControlManager.registerFactory(HT_ACCESS_CONTROL,&htAccessFactory);
1340     g_Config->RequestMapperManager.registerFactory(NATIVE_REQUEST_MAPPER,&ApacheRequestMapFactory);
1341
1342     try {
1343         if (!g_Config->instantiate(g_szSHIBConfig, true))
1344             throw runtime_error("unknown error");
1345     }
1346     catch (exception& ex) {
1347         ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),ex.what());
1348         ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to load configuration");
1349         exit(1);
1350     }
1351
1352     ServiceProvider* sp=g_Config->getServiceProvider();
1353     xmltooling::Locker locker(sp);
1354     const PropertySet* props=sp->getPropertySet("InProcess");
1355     if (props) {
1356         pair<bool,const char*> unsetValue=props->getString("unsetHeaderValue");
1357         if (unsetValue.first)
1358             g_unsetHeaderValue = unsetValue.second;
1359         pair<bool,bool> flag=props->getBool("checkSpoofing");
1360         g_checkSpoofing = !flag.first || flag.second;
1361         if (g_checkSpoofing) {
1362             unsetValue=props->getString("spoofKey");
1363             if (unsetValue.first)
1364                 g_spoofKey = unsetValue.second;
1365         }
1366         flag=props->getBool("catchAll");
1367         g_catchAll = flag.first && flag.second;
1368     }
1369
1370     // Set the cleanup handler
1371     apr_pool_cleanup_register(p, nullptr, &shib_exit, apr_pool_cleanup_null);
1372
1373     ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() done");
1374 }
1375
1376 // Output filters
1377 #ifdef SHIB_DEFERRED_HEADERS
1378 static void set_output_filter(request_rec *r)
1379 {
1380    ap_add_output_filter("SHIB_HEADERS_OUT", nullptr, r, r->connection);
1381 }
1382
1383 static void set_error_filter(request_rec *r)
1384 {
1385    ap_add_output_filter("SHIB_HEADERS_ERR", nullptr, r, r->connection);
1386 }
1387
1388 static int _table_add(void *v, const char *key, const char *value)
1389 {
1390     apr_table_addn((apr_table_t*)v, key, value);
1391     return 1;
1392 }
1393
1394 static apr_status_t do_output_filter(ap_filter_t *f, apr_bucket_brigade *in)
1395 {
1396     request_rec *r = f->r;
1397     shib_request_config *rc = (shib_request_config*) ap_get_module_config(r->request_config, &mod_shib);
1398
1399     if (rc && rc->hdr_out) {
1400         ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_out_filter: merging %d headers", apr_table_elts(rc->hdr_out)->nelts);
1401         // can't use overlap call because it will collapse Set-Cookie headers
1402         //apr_table_overlap(r->headers_out, rc->hdr_out, APR_OVERLAP_TABLES_MERGE);
1403         apr_table_do(_table_add,r->headers_out, rc->hdr_out,nullptr);
1404     }
1405
1406     /* remove ourselves from the filter chain */
1407     ap_remove_output_filter(f);
1408
1409     /* send the data up the stack */
1410     return ap_pass_brigade(f->next,in);
1411 }
1412
1413 static apr_status_t do_error_filter(ap_filter_t *f, apr_bucket_brigade *in)
1414 {
1415     request_rec *r = f->r;
1416     shib_request_config *rc = (shib_request_config*) ap_get_module_config(r->request_config, &mod_shib);
1417
1418     if (rc && rc->hdr_out) {
1419         ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_err_filter: merging %d headers", apr_table_elts(rc->hdr_out)->nelts);
1420         // can't use overlap call because it will collapse Set-Cookie headers
1421         //apr_table_overlap(r->err_headers_out, rc->hdr_out, APR_OVERLAP_TABLES_MERGE);
1422         apr_table_do(_table_add,r->err_headers_out, rc->hdr_out,nullptr);
1423     }
1424
1425     /* remove ourselves from the filter chain */
1426     ap_remove_output_filter(f);
1427
1428     /* send the data up the stack */
1429     return ap_pass_brigade(f->next,in);
1430 }
1431 #endif // SHIB_DEFERRED_HEADERS
1432
1433 typedef const char* (*config_fn_t)(void);
1434
1435 #ifdef SHIB_APACHE_13
1436
1437 // SHIB Module commands
1438
1439 static command_rec shire_cmds[] = {
1440   {"ShibPrefix", (config_fn_t)ap_set_global_string_slot, &g_szPrefix,
1441    RSRC_CONF, TAKE1, "Shibboleth installation directory"},
1442   {"ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1443    RSRC_CONF, TAKE1, "Path to shibboleth2.xml config file"},
1444   {"ShibCatalogs", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1445    RSRC_CONF, TAKE1, "Paths of XML schema catalogs"},
1446
1447   {"ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
1448    (void *) XtOffsetOf (shib_server_config, szScheme),
1449    RSRC_CONF, TAKE1, "URL scheme to force into generated URLs for a vhost"},
1450
1451   {"ShibRequestSetting", (config_fn_t)shib_table_set, nullptr,
1452    OR_AUTHCFG, TAKE2, "Set arbitrary Shibboleth request property for content"},
1453
1454   {"ShibDisable", (config_fn_t)ap_set_flag_slot,
1455    (void *) XtOffsetOf (shib_dir_config, bOff),
1456    OR_AUTHCFG, FLAG, "Disable all Shib module activity here to save processing effort"},
1457   {"ShibApplicationId", (config_fn_t)ap_set_string_slot,
1458    (void *) XtOffsetOf (shib_dir_config, szApplicationId),
1459    OR_AUTHCFG, TAKE1, "Set Shibboleth applicationId property for content"},
1460   {"ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1461    (void *) XtOffsetOf (shib_dir_config, bBasicHijack),
1462    OR_AUTHCFG, FLAG, "(DEPRECATED) Respond to AuthType Basic and convert to shibboleth"},
1463   {"ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1464    (void *) XtOffsetOf (shib_dir_config, bRequireSession),
1465    OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist"},
1466   {"ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
1467    (void *) XtOffsetOf (shib_dir_config, szRequireWith),
1468    OR_AUTHCFG, TAKE1, "Initiates a new session if one does not exist using a specific SessionInitiator"},
1469   {"ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1470    (void *) XtOffsetOf (shib_dir_config, bExportAssertion),
1471    OR_AUTHCFG, FLAG, "Export SAML attribute assertion(s) to Shib-Attributes header"},
1472   {"ShibRedirectToSSL", (config_fn_t)ap_set_string_slot,
1473    (void *) XtOffsetOf (shib_dir_config, szRedirectToSSL),
1474    OR_AUTHCFG, TAKE1, "Redirect non-SSL requests to designated port" },
1475   {"AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
1476    (void *) XtOffsetOf (shib_dir_config, szAuthGrpFile),
1477    OR_AUTHCFG, TAKE1, "text file containing group names and member user IDs"},
1478   {"ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1479    (void *) XtOffsetOf (shib_dir_config, bRequireAll),
1480    OR_AUTHCFG, FLAG, "All require directives must match"},
1481   {"AuthzShibAuthoritative", (config_fn_t)ap_set_flag_slot,
1482    (void *) XtOffsetOf (shib_dir_config, bAuthoritative),
1483    OR_AUTHCFG, FLAG, "Allow failed mod_shib htaccess authorization to fall through to other modules"},
1484   {"ShibUseEnvironment", (config_fn_t)ap_set_flag_slot,
1485    (void *) XtOffsetOf (shib_dir_config, bUseEnvVars),
1486    OR_AUTHCFG, FLAG, "Export attributes using environment variables (default)"},
1487   {"ShibUseHeaders", (config_fn_t)ap_set_flag_slot,
1488    (void *) XtOffsetOf (shib_dir_config, bUseHeaders),
1489    OR_AUTHCFG, FLAG, "Export attributes using custom HTTP headers"},
1490
1491   {nullptr}
1492 };
1493
1494 extern "C"{
1495 handler_rec shib_handlers[] = {
1496   { "shib-handler", shib_handler },
1497   { nullptr }
1498 };
1499
1500 module MODULE_VAR_EXPORT mod_shib = {
1501     STANDARD_MODULE_STUFF,
1502     nullptr,                        /* initializer */
1503     create_shib_dir_config,     /* dir config creater */
1504     merge_shib_dir_config,      /* dir merger --- default is to override */
1505     create_shib_server_config, /* server config */
1506     merge_shib_server_config,   /* merge server config */
1507     shire_cmds,                 /* command table */
1508     shib_handlers,              /* handlers */
1509     nullptr,                    /* filename translation */
1510     shib_check_user,            /* check_user_id */
1511     shib_auth_checker,          /* check auth */
1512     nullptr,                    /* check access */
1513     nullptr,                    /* type_checker */
1514     shib_fixups,                /* fixups */
1515     nullptr,                    /* logger */
1516     nullptr,                    /* header parser */
1517     shib_child_init,            /* child_init */
1518     shib_child_exit,            /* child_exit */
1519     shib_post_read              /* post read-request */
1520 };
1521
1522 #elif defined(SHIB_APACHE_20) || defined(SHIB_APACHE_22)
1523
1524 //static const char * const authnPre[] = { "mod_gss.c", nullptr };
1525
1526 extern "C" void shib_register_hooks (apr_pool_t *p)
1527 {
1528 #ifdef SHIB_DEFERRED_HEADERS
1529   ap_register_output_filter("SHIB_HEADERS_OUT", do_output_filter, nullptr, AP_FTYPE_CONTENT_SET);
1530   ap_hook_insert_filter(set_output_filter, nullptr, nullptr, APR_HOOK_LAST);
1531   ap_register_output_filter("SHIB_HEADERS_ERR", do_error_filter, nullptr, AP_FTYPE_CONTENT_SET);
1532   ap_hook_insert_error_filter(set_error_filter, nullptr, nullptr, APR_HOOK_LAST);
1533   ap_hook_post_read_request(shib_post_read, nullptr, nullptr, APR_HOOK_MIDDLE);
1534 #endif
1535   ap_hook_child_init(shib_child_init, nullptr, nullptr, APR_HOOK_MIDDLE);
1536   const char* prereq = getenv("SHIBSP_APACHE_PREREQ");
1537   if (prereq && *prereq) {
1538     const char* const authnPre[] = { prereq, nullptr };
1539     ap_hook_check_user_id(shib_check_user, authnPre, nullptr, APR_HOOK_MIDDLE);
1540   }
1541   else {
1542     ap_hook_check_user_id(shib_check_user, nullptr, nullptr, APR_HOOK_MIDDLE);
1543   }
1544   ap_hook_auth_checker(shib_auth_checker, nullptr, nullptr, APR_HOOK_FIRST);
1545   ap_hook_handler(shib_handler, nullptr, nullptr, APR_HOOK_LAST);
1546   ap_hook_fixups(shib_fixups, nullptr, nullptr, APR_HOOK_MIDDLE);
1547 }
1548
1549 // SHIB Module commands
1550
1551 extern "C" {
1552 static command_rec shib_cmds[] = {
1553     AP_INIT_TAKE1("ShibPrefix", (config_fn_t)ap_set_global_string_slot, &g_szPrefix,
1554         RSRC_CONF, "Shibboleth installation directory"),
1555     AP_INIT_TAKE1("ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1556         RSRC_CONF, "Path to shibboleth2.xml config file"),
1557     AP_INIT_TAKE1("ShibCatalogs", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1558         RSRC_CONF, "Paths of XML schema catalogs"),
1559     AP_INIT_TAKE1("ShibGSSKey", (config_fn_t)ap_set_global_string_slot, &g_szGSSContextKey,
1560         RSRC_CONF, "Name of user data key containing GSS context established by GSS module"),
1561
1562     AP_INIT_TAKE1("ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
1563         (void *) offsetof (shib_server_config, szScheme),
1564         RSRC_CONF, "URL scheme to force into generated URLs for a vhost"),
1565
1566     AP_INIT_TAKE2("ShibRequestSetting", (config_fn_t)shib_table_set, nullptr,
1567         OR_AUTHCFG, "Set arbitrary Shibboleth request property for content"),
1568
1569     AP_INIT_FLAG("ShibDisable", (config_fn_t)ap_set_flag_slot,
1570         (void *) offsetof (shib_dir_config, bOff),
1571         OR_AUTHCFG, "Disable all Shib module activity here to save processing effort"),
1572     AP_INIT_TAKE1("ShibApplicationId", (config_fn_t)ap_set_string_slot,
1573         (void *) offsetof (shib_dir_config, szApplicationId),
1574         OR_AUTHCFG, "Set Shibboleth applicationId property for content"),
1575     AP_INIT_FLAG("ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1576         (void *) offsetof (shib_dir_config, bBasicHijack),
1577         OR_AUTHCFG, "(DEPRECATED) Respond to AuthType Basic and convert to shibboleth"),
1578     AP_INIT_FLAG("ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1579         (void *) offsetof (shib_dir_config, bRequireSession),
1580         OR_AUTHCFG, "Initiates a new session if one does not exist"),
1581     AP_INIT_TAKE1("ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
1582         (void *) offsetof (shib_dir_config, szRequireWith),
1583         OR_AUTHCFG, "Initiates a new session if one does not exist using a specific SessionInitiator"),
1584     AP_INIT_FLAG("ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1585         (void *) offsetof (shib_dir_config, bExportAssertion),
1586         OR_AUTHCFG, "Export SAML attribute assertion(s) to Shib-Attributes header"),
1587     AP_INIT_TAKE1("ShibRedirectToSSL", (config_fn_t)ap_set_string_slot,
1588         (void *) offsetof (shib_dir_config, szRedirectToSSL),
1589         OR_AUTHCFG, "Redirect non-SSL requests to designated port"),
1590     AP_INIT_TAKE1("AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
1591         (void *) offsetof (shib_dir_config, szAuthGrpFile),
1592         OR_AUTHCFG, "Text file containing group names and member user IDs"),
1593     AP_INIT_FLAG("ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1594         (void *) offsetof (shib_dir_config, bRequireAll),
1595         OR_AUTHCFG, "All require directives must match"),
1596     AP_INIT_FLAG("AuthzShibAuthoritative", (config_fn_t)ap_set_flag_slot,
1597         (void *) offsetof (shib_dir_config, bAuthoritative),
1598         OR_AUTHCFG, "Allow failed mod_shib htaccess authorization to fall through to other modules"),
1599     AP_INIT_FLAG("ShibUseEnvironment", (config_fn_t)ap_set_flag_slot,
1600         (void *) offsetof (shib_dir_config, bUseEnvVars),
1601         OR_AUTHCFG, "Export attributes using environment variables (default)"),
1602     AP_INIT_FLAG("ShibUseHeaders", (config_fn_t)ap_set_flag_slot,
1603         (void *) offsetof (shib_dir_config, bUseHeaders),
1604         OR_AUTHCFG, "Export attributes using custom HTTP headers"),
1605
1606     {nullptr}
1607 };
1608
1609 module AP_MODULE_DECLARE_DATA mod_shib = {
1610     STANDARD20_MODULE_STUFF,
1611     create_shib_dir_config,     /* create dir config */
1612     merge_shib_dir_config,      /* merge dir config --- default is to override */
1613     create_shib_server_config,  /* create server config */
1614     merge_shib_server_config,   /* merge server config */
1615     shib_cmds,                  /* command table */
1616     shib_register_hooks         /* register hooks */
1617 };
1618
1619 #else
1620 #error "unsupported Apache version"
1621 #endif
1622
1623 }