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