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