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