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