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