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