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