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