2 * Copyright 2001-2010 Internet2
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
20 * Apache module implementation.
26 #undef _XOPEN_SOURCE // causes gethostname conflict in unistd.h
30 # define _CRT_NONSTDC_NO_DEPRECATE 1
31 # define _CRT_SECURE_NO_DEPRECATE 1
34 #include <shibsp/AbstractSPRequest.h>
35 #include <shibsp/AccessControl.h>
36 #include <shibsp/exceptions.h>
37 #include <shibsp/RequestMapper.h>
38 #include <shibsp/SPConfig.h>
39 #include <shibsp/ServiceProvider.h>
40 #include <shibsp/SessionCache.h>
41 #include <shibsp/attribute/Attribute.h>
42 #include <xercesc/util/XMLUniDefs.hpp>
43 #include <xercesc/util/regx/RegularExpression.hpp>
44 #include <xmltooling/XMLToolingConfig.h>
45 #include <xmltooling/util/NDC.h>
46 #include <xmltooling/util/Threads.h>
47 #include <xmltooling/util/XMLConstants.h>
48 #include <xmltooling/util/XMLHelper.h>
56 // Apache specific header files
58 #include <http_config.h>
59 #include <http_protocol.h>
60 #include <http_main.h>
62 #include <http_core.h>
64 #include <http_request.h>
66 #ifndef SHIB_APACHE_13
67 #include <apr_buckets.h>
68 #include <apr_strings.h>
69 #include <apr_pools.h>
79 #include <unistd.h> // for getpid()
82 using namespace shibsp;
83 using namespace xmltooling;
85 using xercesc::RegularExpression;
86 using xercesc::XMLException;
88 extern "C" module MODULE_VAR_EXPORT mod_shib;
91 char* g_szSHIBConfig = nullptr;
92 char* g_szSchemaDir = nullptr;
93 char* g_szPrefix = nullptr;
94 SPConfig* g_Config = nullptr;
95 string g_unsetHeaderValue,g_spoofKey;
96 bool g_checkSpoofing = true;
97 bool g_catchAll = false;
98 static const char* g_UserDataKey = "_shib_check_user_";
101 /* Apache 2.2.x headers must be accumulated and set in the output filter.
102 Apache 2.0.49+ supports the filter method.
103 Apache 1.3.x and lesser 2.0.x must write the headers directly. */
105 #if (defined(SHIB_APACHE_20) || defined(SHIB_APACHE_22)) && AP_MODULE_MAGIC_AT_LEAST(20020903,6)
106 #define SHIB_DEFERRED_HEADERS
109 /********************************************************************************/
110 // Basic Apache Configuration code.
113 // per-server module configuration structure
114 struct shib_server_config
119 // creates the per-server configuration
120 extern "C" void* create_shib_server_config(SH_AP_POOL* p, server_rec* s)
122 shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
123 sc->szScheme = nullptr;
127 // overrides server configuration in virtual servers
128 extern "C" void* merge_shib_server_config (SH_AP_POOL* p, void* base, void* sub)
130 shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
131 shib_server_config* parent=(shib_server_config*)base;
132 shib_server_config* child=(shib_server_config*)sub;
135 sc->szScheme=ap_pstrdup(p,child->szScheme);
136 else if (parent->szScheme)
137 sc->szScheme=ap_pstrdup(p,parent->szScheme);
139 sc->szScheme=nullptr;
144 // per-dir module configuration structure
145 struct shib_dir_config
147 SH_AP_TABLE* tSettings; // generic table of extensible settings
150 char* szAuthGrpFile; // Auth GroupFile name
151 int bRequireAll; // all "known" require directives must match, otherwise OR logic
152 int bAuthoritative; // allow htaccess plugin to DECLINE when authz fails
154 // Content Configuration
155 char* szApplicationId; // Shib applicationId value
156 char* szRequireWith; // require a session using a specific initiator?
157 char* szRedirectToSSL; // redirect non-SSL requests to SSL port
158 int bOff; // flat-out disable all Shib processing
159 int bBasicHijack; // activate for AuthType Basic?
160 int bRequireSession; // require a session?
161 int bExportAssertion; // export SAML assertion to the environment?
162 int bUseEnvVars; // use environment?
163 int bUseHeaders; // use headers?
166 // creates per-directory config structure
167 extern "C" void* create_shib_dir_config (SH_AP_POOL* p, char* d)
169 shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
170 dc->tSettings = nullptr;
171 dc->szAuthGrpFile = nullptr;
172 dc->bRequireAll = -1;
173 dc->bAuthoritative = -1;
174 dc->szApplicationId = nullptr;
175 dc->szRequireWith = nullptr;
176 dc->szRedirectToSSL = nullptr;
178 dc->bBasicHijack = -1;
179 dc->bRequireSession = -1;
180 dc->bExportAssertion = -1;
181 dc->bUseEnvVars = -1;
182 dc->bUseHeaders = -1;
186 // overrides server configuration in directories
187 extern "C" void* merge_shib_dir_config (SH_AP_POOL* p, void* base, void* sub)
189 shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
190 shib_dir_config* parent=(shib_dir_config*)base;
191 shib_dir_config* child=(shib_dir_config*)sub;
193 // The child supersedes any matching table settings in the parent.
194 dc->tSettings = nullptr;
195 if (parent->tSettings)
196 dc->tSettings = ap_copy_table(p, parent->tSettings);
197 if (child->tSettings) {
199 ap_overlap_tables(dc->tSettings, child->tSettings, AP_OVERLAP_TABLES_SET);
201 dc->tSettings = ap_copy_table(p, child->tSettings);
204 if (child->szAuthGrpFile)
205 dc->szAuthGrpFile=ap_pstrdup(p,child->szAuthGrpFile);
206 else if (parent->szAuthGrpFile)
207 dc->szAuthGrpFile=ap_pstrdup(p,parent->szAuthGrpFile);
209 dc->szAuthGrpFile=nullptr;
211 if (child->szApplicationId)
212 dc->szApplicationId=ap_pstrdup(p,child->szApplicationId);
213 else if (parent->szApplicationId)
214 dc->szApplicationId=ap_pstrdup(p,parent->szApplicationId);
216 dc->szApplicationId=nullptr;
218 if (child->szRequireWith)
219 dc->szRequireWith=ap_pstrdup(p,child->szRequireWith);
220 else if (parent->szRequireWith)
221 dc->szRequireWith=ap_pstrdup(p,parent->szRequireWith);
223 dc->szRequireWith=nullptr;
225 if (child->szRedirectToSSL)
226 dc->szRedirectToSSL=ap_pstrdup(p,child->szRedirectToSSL);
227 else if (parent->szRedirectToSSL)
228 dc->szRedirectToSSL=ap_pstrdup(p,parent->szRedirectToSSL);
230 dc->szRedirectToSSL=nullptr;
232 dc->bOff=((child->bOff==-1) ? parent->bOff : child->bOff);
233 dc->bBasicHijack=((child->bBasicHijack==-1) ? parent->bBasicHijack : child->bBasicHijack);
234 dc->bRequireSession=((child->bRequireSession==-1) ? parent->bRequireSession : child->bRequireSession);
235 dc->bExportAssertion=((child->bExportAssertion==-1) ? parent->bExportAssertion : child->bExportAssertion);
236 dc->bRequireAll=((child->bRequireAll==-1) ? parent->bRequireAll : child->bRequireAll);
237 dc->bAuthoritative=((child->bAuthoritative==-1) ? parent->bAuthoritative : child->bAuthoritative);
238 dc->bUseEnvVars=((child->bUseEnvVars==-1) ? parent->bUseEnvVars : child->bUseEnvVars);
239 dc->bUseHeaders=((child->bUseHeaders==-1) ? parent->bUseHeaders : child->bUseHeaders);
243 // per-request module structure
244 struct shib_request_config
246 SH_AP_TABLE *env; // environment vars
247 #ifdef SHIB_DEFERRED_HEADERS
248 SH_AP_TABLE *hdr_out; // headers to browser
252 // create a request record
253 static shib_request_config *init_request_config(request_rec *r)
255 shib_request_config* rc=(shib_request_config*)ap_pcalloc(r->pool,sizeof(shib_request_config));
256 ap_set_module_config (r->request_config, &mod_shib, rc);
257 memset(rc, 0, sizeof(shib_request_config));
258 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_init_rc");
262 // generic global slot handlers
263 extern "C" const char* ap_set_global_string_slot(cmd_parms* parms, void*, const char* arg)
265 *((char**)(parms->info))=ap_pstrdup(parms->pool,arg);
269 extern "C" const char* shib_set_server_string_slot(cmd_parms* parms, void*, const char* arg)
271 char* base=(char*)ap_get_module_config(parms->server->module_config,&mod_shib);
272 size_t offset=(size_t)parms->info;
273 *((char**)(base + offset))=ap_pstrdup(parms->pool,arg);
277 extern "C" const char* shib_ap_set_file_slot(cmd_parms* parms,
278 #ifdef SHIB_APACHE_13
279 char* arg1, char* arg2
281 void* arg1, const char* arg2
285 ap_set_file_slot(parms, arg1, arg2);
289 extern "C" const char* shib_table_set(cmd_parms* parms, shib_dir_config* dc, const char* arg1, const char* arg2)
292 dc->tSettings = ap_make_table(parms->pool, 4);
293 ap_table_set(dc->tSettings, arg1, arg2);
297 /********************************************************************************/
298 // Apache ShibTarget subclass(es) here.
300 class ShibTargetApache : public AbstractSPRequest
303 mutable string m_body;
304 mutable bool m_gotBody,m_firsttime;
305 mutable vector<string> m_certs;
306 set<string> m_allhttp;
310 shib_dir_config* m_dc;
311 shib_server_config* m_sc;
312 shib_request_config* m_rc;
314 ShibTargetApache(request_rec* req, bool handler, bool shib_check_user)
315 : AbstractSPRequest(SHIBSP_LOGCAT".Apache"), m_handler(handler), m_gotBody(false),m_firsttime(true) {
316 m_sc = (shib_server_config*)ap_get_module_config(req->server->module_config, &mod_shib);
317 m_dc = (shib_dir_config*)ap_get_module_config(req->per_dir_config, &mod_shib);
318 m_rc = (shib_request_config*)ap_get_module_config(req->request_config, &mod_shib);
321 setRequestURI(m_req->unparsed_uri);
323 if (shib_check_user && m_dc->bUseHeaders == 1) {
324 // Try and see if this request was already processed, to skip spoof checking.
325 if (!ap_is_initial_req(m_req)) {
328 else if (!g_spoofKey.empty()) {
329 const char* hdr = ap_table_get(m_req->headers_in, "Shib-Spoof-Check");
330 if (hdr && g_spoofKey == hdr)
335 log(SPDebug, "shib_check_user running more than once");
338 virtual ~ShibTargetApache() {}
340 const char* getScheme() const {
341 return m_sc->szScheme ? m_sc->szScheme : ap_http_method(m_req);
343 const char* getHostname() const {
344 return ap_get_server_name(m_req);
346 int getPort() const {
347 return ap_get_server_port(m_req);
349 const char* getMethod() const {
350 return m_req->method;
352 string getContentType() const {
353 const char* type = ap_table_get(m_req->headers_in, "Content-Type");
354 return type ? type : "";
356 long getContentLength() const {
357 return m_gotBody ? m_body.length() : m_req->remaining;
359 string getRemoteAddr() const {
360 string ret = AbstractSPRequest::getRemoteAddr();
361 return ret.empty() ? m_req->connection->remote_ip : ret;
363 void log(SPLogLevel level, const string& msg) const {
364 AbstractSPRequest::log(level,msg);
367 (level == SPDebug ? APLOG_DEBUG :
368 (level == SPInfo ? APLOG_INFO :
369 (level == SPWarn ? APLOG_WARNING :
370 (level == SPError ? APLOG_ERR : APLOG_CRIT))))|APLOG_NOERRNO,
375 const char* getQueryString() const { return m_req->args; }
376 const char* getRequestBody() const {
377 if (m_gotBody || m_req->method_number==M_GET)
378 return m_body.c_str();
379 #ifdef SHIB_APACHE_13
380 // Read the posted data
381 if (ap_setup_client_block(m_req, REQUEST_CHUNKED_DECHUNK) != OK) {
383 log(SPError, "Apache function (setup_client_block) failed while reading request body.");
384 return m_body.c_str();
386 if (!ap_should_client_block(m_req)) {
388 log(SPError, "Apache function (should_client_block) failed while reading request body.");
389 return m_body.c_str();
391 if (m_req->remaining > 1024*1024)
392 throw opensaml::SecurityPolicyException("Blocked request body larger than 1M size limit.");
395 char buff[HUGE_STRING_LEN];
396 ap_hard_timeout("[mod_shib] getRequestBody", m_req);
397 while ((len=ap_get_client_block(m_req, buff, sizeof(buff))) > 0) {
398 ap_reset_timeout(m_req);
399 m_body.append(buff, len);
401 ap_kill_timeout(m_req);
406 apr_bucket_brigade* bb = apr_brigade_create(m_req->pool, m_req->connection->bucket_alloc);
409 apr_status_t rv = ap_get_brigade(m_req->input_filters, bb, AP_MODE_READBYTES, APR_BLOCK_READ, HUGE_STRING_LEN);
410 if (rv != APR_SUCCESS) {
411 log(SPError, "Apache function (ap_get_brigade) failed while reading request body.");
415 for (bucket = APR_BRIGADE_FIRST(bb); bucket != APR_BRIGADE_SENTINEL(bb); bucket = APR_BUCKET_NEXT(bucket)) {
416 if (APR_BUCKET_IS_EOS(bucket)) {
421 /* We can't do much with this. */
422 if (APR_BUCKET_IS_FLUSH(bucket))
426 apr_bucket_read(bucket, &data, &len, APR_BLOCK_READ);
428 m_body.append(data, len);
430 apr_brigade_cleanup(bb);
432 apr_brigade_destroy(bb);
435 return m_body.c_str();
437 void clearHeader(const char* rawname, const char* cginame) {
438 if (m_dc->bUseHeaders == 1) {
439 // ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_clear_header: hdr\n");
440 if (g_checkSpoofing && m_firsttime) {
441 if (m_allhttp.empty()) {
442 // First time, so populate set with "CGI" versions of client-supplied headers.
443 #ifdef SHIB_APACHE_13
444 array_header *hdrs_arr = ap_table_elts(m_req->headers_in);
445 table_entry *hdrs = (table_entry *) hdrs_arr->elts;
447 const apr_array_header_t *hdrs_arr = apr_table_elts(m_req->headers_in);
448 const apr_table_entry_t *hdrs = (const apr_table_entry_t *) hdrs_arr->elts;
450 for (int i = 0; i < hdrs_arr->nelts; ++i) {
453 string cgiversion("HTTP_");
454 const char* pch = hdrs[i].key;
456 cgiversion += (isalnum(*pch) ? toupper(*pch) : '_');
459 m_allhttp.insert(cgiversion);
463 if (m_allhttp.count(cginame) > 0)
464 throw opensaml::SecurityPolicyException("Attempt to spoof header ($1) was detected.", params(1, rawname));
466 ap_table_unset(m_req->headers_in, rawname);
467 ap_table_set(m_req->headers_in, rawname, g_unsetHeaderValue.c_str());
470 void setHeader(const char* name, const char* value) {
471 if (m_dc->bUseEnvVars != 0) {
473 // this happens on subrequests
474 // ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_setheader: no_m_rc\n");
475 m_rc = init_request_config(m_req);
478 m_rc->env = ap_make_table(m_req->pool, 10);
479 // ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_set_env: %s=%s\n", name, value?value:"Null");
480 ap_table_set(m_rc->env, name, value ? value : "");
482 if (m_dc->bUseHeaders == 1)
483 ap_table_set(m_req->headers_in, name, value);
485 string getHeader(const char* name) const {
486 const char* hdr = ap_table_get(m_req->headers_in, name);
487 return string(hdr ? hdr : "");
489 string getSecureHeader(const char* name) const {
490 if (m_dc->bUseEnvVars != 0) {
492 if (m_rc && m_rc->env)
493 hdr = ap_table_get(m_rc->env, name);
496 return string(hdr ? hdr : "");
498 return getHeader(name);
500 void setRemoteUser(const char* user) {
501 SH_AP_USER(m_req) = user ? ap_pstrdup(m_req->pool, user) : nullptr;
502 if (m_dc->bUseHeaders == 1) {
504 ap_table_set(m_req->headers_in, "REMOTE_USER", user);
507 ap_table_unset(m_req->headers_in, "REMOTE_USER");
508 ap_table_set(m_req->headers_in, "REMOTE_USER", g_unsetHeaderValue.c_str());
512 string getRemoteUser() const {
513 return string(SH_AP_USER(m_req) ? SH_AP_USER(m_req) : "");
515 void setAuthType(const char* authtype) {
516 if (authtype && m_dc->bBasicHijack == 1)
518 SH_AP_AUTH_TYPE(m_req) = authtype ? ap_pstrdup(m_req->pool, authtype) : nullptr;
520 string getAuthType() const {
521 return string(SH_AP_AUTH_TYPE(m_req) ? SH_AP_AUTH_TYPE(m_req) : "");
523 void setContentType(const char* type) {
524 m_req->content_type = ap_psprintf(m_req->pool, type);
526 void setResponseHeader(const char* name, const char* value) {
527 HTTPResponse::setResponseHeader(name, value);
528 #ifdef SHIB_DEFERRED_HEADERS
530 // this happens on subrequests
531 m_rc = init_request_config(m_req);
534 m_rc->hdr_out = ap_make_table(m_req->pool, 5);
535 ap_table_add(m_rc->hdr_out, name, value);
539 ap_table_add(m_req->err_headers_out, name, value);
541 long sendResponse(istream& in, long status) {
542 if (status != XMLTOOLING_HTTP_STATUS_OK)
543 m_req->status = status;
544 ap_send_http_header(m_req);
548 ap_rwrite(buf,in.gcount(),m_req);
550 #if (defined(SHIB_APACHE_20) || defined(SHIB_APACHE_22))
551 if (status != XMLTOOLING_HTTP_STATUS_OK && status != XMLTOOLING_HTTP_STATUS_ERROR)
556 long sendRedirect(const char* url) {
557 HTTPResponse::sendRedirect(url);
558 ap_table_set(m_req->headers_out, "Location", url);
561 const vector<string>& getClientCertificates() const {
562 if (m_certs.empty()) {
563 const char* cert = ap_table_get(m_req->subprocess_env, "SSL_CLIENT_CERT");
565 m_certs.push_back(cert);
568 cert = ap_table_get(m_req->subprocess_env, ap_psprintf(m_req->pool, "SSL_CLIENT_CERT_CHAIN_%d", i++));
570 m_certs.push_back(cert);
575 long returnDecline(void) { return DECLINED; }
576 long returnOK(void) { return OK; }
579 /********************************************************************************/
582 extern "C" int shib_check_user(request_rec* r)
584 // Short-circuit entirely?
585 if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
588 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_check_user(%d): ENTER", (int)getpid());
590 ostringstream threadid;
591 threadid << "[" << getpid() << "] shib_check_user" << '\0';
592 xmltooling::NDC ndc(threadid.str().c_str());
595 ShibTargetApache sta(r,false,true);
597 // Check user authentication and export information, then set the handler bypass
598 pair<bool,long> res = sta.getServiceProvider().doAuthentication(sta,true);
599 apr_pool_userdata_setn((const void*)42,g_UserDataKey,nullptr,r->pool);
600 // If directed, install a spoof key to recognize when we've already cleared headers.
601 if (!g_spoofKey.empty() && (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bUseHeaders==1))
602 ap_table_set(r->headers_in, "Shib-Spoof-Check", g_spoofKey.c_str());
603 if (res.first) return res.second;
605 // user auth was okay -- export the assertions now
606 res = sta.getServiceProvider().doExport(sta);
607 if (res.first) return res.second;
609 // export happened successfully.. this user is ok.
612 catch (exception& e) {
613 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user threw an exception: %s", e.what());
617 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user threw an unknown exception!");
624 extern "C" int shib_handler(request_rec* r)
626 // Short-circuit entirely?
627 if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
630 ostringstream threadid;
631 threadid << "[" << getpid() << "] shib_handler" << '\0';
632 xmltooling::NDC ndc(threadid.str().c_str());
634 #ifndef SHIB_APACHE_13
635 // With 2.x, this handler always runs, though last.
636 // We check if shib_check_user ran, because it will detect a handler request
637 // and dispatch it directly.
639 apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
640 if (data==(const void*)42) {
641 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler skipped since check_user ran");
646 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler(%d): ENTER: %s", (int)getpid(), r->handler);
649 ShibTargetApache sta(r,true,false);
651 pair<bool,long> res = sta.getServiceProvider().doHandler(sta);
652 if (res.first) return res.second;
654 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "doHandler() did not do anything.");
657 catch (exception& e) {
658 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler threw an exception: %s", e.what());
662 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler threw an unknown exception!");
670 * shib_auth_checker() -- a simple resource manager to
671 * process the .htaccess settings
673 extern "C" int shib_auth_checker(request_rec* r)
675 // Short-circuit entirely?
676 if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
679 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_auth_checker(%d): ENTER", (int)getpid());
681 ostringstream threadid;
682 threadid << "[" << getpid() << "] shib_auth_checker" << '\0';
683 xmltooling::NDC ndc(threadid.str().c_str());
686 ShibTargetApache sta(r,false,false);
688 pair<bool,long> res = sta.getServiceProvider().doAuthorization(sta);
689 if (res.first) return res.second;
691 // The SP method should always return true, so if we get this far, something unusual happened.
692 // Just let Apache (or some other module) decide what to do.
695 catch (exception& e) {
696 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an exception: %s", e.what());
700 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an unknown exception!");
707 // Access control plugin that enforces htaccess rules
708 class htAccessControl : virtual public AccessControl
712 ~htAccessControl() {}
713 Lockable* lock() {return this;}
715 aclresult_t authorized(const SPRequest& request, const Session* session) const;
717 bool checkAttribute(const SPRequest& request, const Attribute* attr, const char* toMatch, RegularExpression* re) const;
720 AccessControl* htAccessFactory(const xercesc::DOMElement* const & e)
722 return new htAccessControl();
725 class ApacheRequestMapper : public virtual RequestMapper, public virtual PropertySet
728 ApacheRequestMapper(const xercesc::DOMElement* e);
729 ~ApacheRequestMapper() { delete m_mapper; delete m_htaccess; delete m_staKey; delete m_propsKey; }
730 Lockable* lock() { return m_mapper->lock(); }
731 void unlock() { m_staKey->setData(nullptr); m_propsKey->setData(nullptr); m_mapper->unlock(); }
732 Settings getSettings(const HTTPRequest& request) const;
734 const PropertySet* getParent() const { return nullptr; }
735 void setParent(const PropertySet*) {}
736 pair<bool,bool> getBool(const char* name, const char* ns=nullptr) const;
737 pair<bool,const char*> getString(const char* name, const char* ns=nullptr) const;
738 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=nullptr) const;
739 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=nullptr) const;
740 pair<bool,int> getInt(const char* name, const char* ns=nullptr) const;
741 void getAll(map<string,const char*>& properties) const;
742 const PropertySet* getPropertySet(const char* name, const char* ns=shibspconstants::ASCII_SHIB2SPCONFIG_NS) const;
743 const xercesc::DOMElement* getElement() const;
746 RequestMapper* m_mapper;
748 ThreadKey* m_propsKey;
749 AccessControl* m_htaccess;
752 RequestMapper* ApacheRequestMapFactory(const xercesc::DOMElement* const & e)
754 return new ApacheRequestMapper(e);
757 ApacheRequestMapper::ApacheRequestMapper(const xercesc::DOMElement* e) : m_mapper(nullptr), m_staKey(nullptr), m_propsKey(nullptr), m_htaccess(nullptr)
759 m_mapper=SPConfig::getConfig().RequestMapperManager.newPlugin(XML_REQUEST_MAPPER,e);
760 m_htaccess=new htAccessControl();
761 m_staKey=ThreadKey::create(nullptr);
762 m_propsKey=ThreadKey::create(nullptr);
765 RequestMapper::Settings ApacheRequestMapper::getSettings(const HTTPRequest& request) const
767 Settings s=m_mapper->getSettings(request);
768 m_staKey->setData((void*)dynamic_cast<const ShibTargetApache*>(&request));
769 m_propsKey->setData((void*)s.first);
770 return pair<const PropertySet*,AccessControl*>(this,s.second ? s.second : m_htaccess);
773 pair<bool,bool> ApacheRequestMapper::getBool(const char* name, const char* ns) const
775 const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
776 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
778 // Override Apache-settable boolean properties.
779 if (name && !strcmp(name,"requireSession") && sta->m_dc->bRequireSession != -1)
780 return make_pair(true, sta->m_dc->bRequireSession==1);
781 else if (name && !strcmp(name,"exportAssertion") && sta->m_dc->bExportAssertion != -1)
782 return make_pair(true, sta->m_dc->bExportAssertion==1);
783 else if (sta->m_dc->tSettings) {
784 const char* prop = ap_table_get(sta->m_dc->tSettings, name);
786 return make_pair(true, !strcmp(prop, "true") || !strcmp(prop, "1") || !strcmp(prop, "On"));
789 return s ? s->getBool(name,ns) : make_pair(false,false);
792 pair<bool,const char*> ApacheRequestMapper::getString(const char* name, const char* ns) const
794 const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
795 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
797 // Override Apache-settable string properties.
798 if (name && !strcmp(name,"authType")) {
799 const char *auth_type=ap_auth_type(sta->m_req);
801 // Check for Basic Hijack
802 if (!strcasecmp(auth_type, "basic") && sta->m_dc->bBasicHijack == 1)
803 auth_type = "shibboleth";
804 return make_pair(true,auth_type);
807 else if (name && !strcmp(name,"applicationId") && sta->m_dc->szApplicationId)
808 return pair<bool,const char*>(true,sta->m_dc->szApplicationId);
809 else if (name && !strcmp(name,"requireSessionWith") && sta->m_dc->szRequireWith)
810 return pair<bool,const char*>(true,sta->m_dc->szRequireWith);
811 else if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
812 return pair<bool,const char*>(true,sta->m_dc->szRedirectToSSL);
813 else if (sta->m_dc->tSettings) {
814 const char* prop = ap_table_get(sta->m_dc->tSettings, name);
816 return make_pair(true, prop);
819 return s ? s->getString(name,ns) : pair<bool,const char*>(false,nullptr);
822 pair<bool,const XMLCh*> ApacheRequestMapper::getXMLString(const char* name, const char* ns) const
824 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
825 return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,nullptr);
828 pair<bool,unsigned int> ApacheRequestMapper::getUnsignedInt(const char* name, const char* ns) const
830 const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
831 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
833 // Override Apache-settable int properties.
834 if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
835 return pair<bool,unsigned int>(true, strtol(sta->m_dc->szRedirectToSSL, nullptr, 10));
836 else if (sta->m_dc->tSettings) {
837 const char* prop = ap_table_get(sta->m_dc->tSettings, name);
839 return pair<bool,unsigned int>(true, atoi(prop));
842 return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
845 pair<bool,int> ApacheRequestMapper::getInt(const char* name, const char* ns) const
847 const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
848 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
850 // Override Apache-settable int properties.
851 if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
852 return pair<bool,int>(true,atoi(sta->m_dc->szRedirectToSSL));
853 else if (sta->m_dc->tSettings) {
854 const char* prop = ap_table_get(sta->m_dc->tSettings, name);
856 return make_pair(true, atoi(prop));
859 return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
862 static int _rm_get_all_table_walk(void *v, const char *key, const char *value)
864 reinterpret_cast<map<string,const char*>*>(v)->insert(pair<string,const char*>(key, value));
868 void ApacheRequestMapper::getAll(map<string,const char*>& properties) const
870 const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
871 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
874 s->getAll(properties);
878 const char* auth_type=ap_auth_type(sta->m_req);
880 // Check for Basic Hijack
881 if (!strcasecmp(auth_type, "basic") && sta->m_dc->bBasicHijack == 1)
882 auth_type = "shibboleth";
883 properties["authType"] = auth_type;
886 if (sta->m_dc->szApplicationId)
887 properties["applicationId"] = sta->m_dc->szApplicationId;
888 if (sta->m_dc->szRequireWith)
889 properties["requireSessionWith"] = sta->m_dc->szRequireWith;
890 if (sta->m_dc->szRedirectToSSL)
891 properties["redirectToSSL"] = sta->m_dc->szRedirectToSSL;
892 if (sta->m_dc->bRequireSession != 0)
893 properties["requireSession"] = (sta->m_dc->bRequireSession==1) ? "true" : "false";
894 if (sta->m_dc->bExportAssertion != 0)
895 properties["exportAssertion"] = (sta->m_dc->bExportAssertion==1) ? "true" : "false";
897 if (sta->m_dc->tSettings)
898 ap_table_do(_rm_get_all_table_walk, &properties, sta->m_dc->tSettings, nullptr);
901 const PropertySet* ApacheRequestMapper::getPropertySet(const char* name, const char* ns) const
903 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
904 return s ? s->getPropertySet(name,ns) : nullptr;
907 const xercesc::DOMElement* ApacheRequestMapper::getElement() const
909 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
910 return s ? s->getElement() : nullptr;
913 static SH_AP_TABLE* groups_for_user(request_rec* r, const char* user, char* grpfile)
916 SH_AP_TABLE* grps=ap_make_table(r->pool,15);
917 char l[MAX_STRING_LEN];
918 const char *group_name, *ll, *w;
920 #ifdef SHIB_APACHE_13
921 if (!(f=ap_pcfg_openfile(r->pool,grpfile))) {
923 if (ap_pcfg_openfile(&f,r->pool,grpfile) != APR_SUCCESS) {
925 ap_log_rerror(APLOG_MARK,APLOG_DEBUG,SH_AP_R(r),"groups_for_user() could not open group file: %s\n",grpfile);
930 #ifdef SHIB_APACHE_13
931 sp=ap_make_sub_pool(r->pool);
933 if (apr_pool_create(&sp,r->pool) != APR_SUCCESS) {
934 ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,
935 "groups_for_user() could not create a subpool");
940 while (!(ap_cfg_getline(l,MAX_STRING_LEN,f))) {
941 if ((*l=='#') || (!*l))
946 group_name=ap_getword(sp,&ll,':');
949 w=ap_getword_conf(sp,&ll);
950 if (!strcmp(w,user)) {
951 ap_table_setn(grps,ap_pstrdup(r->pool,group_name),"in");
961 bool htAccessControl::checkAttribute(const SPRequest& request, const Attribute* attr, const char* toMatch, RegularExpression* re) const
963 bool caseSensitive = attr->isCaseSensitive();
964 const vector<string>& vals = attr->getSerializedValues();
965 for (vector<string>::const_iterator v=vals.begin(); v!=vals.end(); ++v) {
967 auto_arrayptr<XMLCh> trans(fromUTF8(v->c_str()));
968 if (re->matches(trans.get())) {
969 if (request.isPriorityEnabled(SPRequest::SPDebug))
970 request.log(SPRequest::SPDebug, string("htaccess: expecting regexp ") + toMatch + ", got " + *v + ": acccepted");
974 else if ((caseSensitive && *v == toMatch) || (!caseSensitive && !strcasecmp(v->c_str(), toMatch))) {
975 if (request.isPriorityEnabled(SPRequest::SPDebug))
976 request.log(SPRequest::SPDebug, string("htaccess: expecting ") + toMatch + ", got " + *v + ": accepted");
979 else if (request.isPriorityEnabled(SPRequest::SPDebug)) {
980 request.log(SPRequest::SPDebug, string("htaccess: expecting ") + toMatch + ", got " + *v + ": rejected");
986 AccessControl::aclresult_t htAccessControl::authorized(const SPRequest& request, const Session* session) const
988 // Make sure the object is our type.
989 const ShibTargetApache* sta=dynamic_cast<const ShibTargetApache*>(&request);
991 throw ConfigurationException("Request wrapper object was not of correct type.");
995 int m=sta->m_req->method_number;
996 bool method_restricted=false;
999 const array_header* reqs_arr=ap_requires(sta->m_req);
1001 return shib_acl_indeterminate; // should never happen
1003 require_line* reqs=(require_line*)reqs_arr->elts;
1005 for (int x=0; x<reqs_arr->nelts; x++) {
1006 // This rule should be completely ignored, the method doesn't fit.
1007 // The rule just doesn't exist for our purposes.
1008 if (!(reqs[x].method_mask & (1 << m)))
1011 method_restricted=true; // this lets us know at the end that at least one rule was potentially enforcable.
1013 // Tracks status of this rule's evaluation.
1014 bool status = false;
1016 string remote_user = request.getRemoteUser();
1018 t = reqs[x].requirement;
1019 w = ap_getword_white(sta->m_req->pool, &t);
1021 if (!strcasecmp(w,"shibboleth")) {
1022 // This is a dummy rule needed because Apache conflates authn and authz.
1023 // Without some require rule, AuthType is ignored and no check_user hooks run.
1024 status = true; // treat it as an "accepted" rule
1026 else if (!strcmp(w,"valid-user") && session) {
1027 request.log(SPRequest::SPDebug, "htaccess: accepting valid-user based on active session");
1030 else if (!strcmp(w,"user") && !remote_user.empty()) {
1031 bool regexp=false,negate=false;
1033 w=ap_getword_conf(sta->m_req->pool,&t);
1045 // Figure out if there's a match.
1049 // To do regex matching, we have to convert from UTF-8.
1050 auto_arrayptr<XMLCh> trans(fromUTF8(w));
1051 RegularExpression re(trans.get());
1052 auto_arrayptr<XMLCh> trans2(fromUTF8(remote_user.c_str()));
1053 match = re.matches(trans2.get());
1055 catch (XMLException& ex) {
1056 auto_ptr_char tmp(ex.getMessage());
1057 request.log(SPRequest::SPError,
1058 string("htaccess plugin caught exception while parsing regular expression (") + w + "): " + tmp.get());
1061 else if (remote_user==w) {
1066 // If we matched, then we're done with this rule either way and status is set to reflect the outcome.
1068 if (request.isPriorityEnabled(SPRequest::SPDebug))
1069 request.log(SPRequest::SPDebug,
1070 string("htaccess: require user ") + (negate ? "rejecting (" : "accepting (") + remote_user + ")");
1075 else if (!strcmp(w,"group") && !remote_user.empty()) {
1076 SH_AP_TABLE* grpstatus=nullptr;
1077 if (sta->m_dc->szAuthGrpFile) {
1078 if (request.isPriorityEnabled(SPRequest::SPDebug))
1079 request.log(SPRequest::SPDebug,string("htaccess plugin using groups file: ") + sta->m_dc->szAuthGrpFile);
1080 grpstatus=groups_for_user(sta->m_req,remote_user.c_str(),sta->m_dc->szAuthGrpFile);
1085 w=ap_getword_conf(sta->m_req->pool,&t);
1091 if (grpstatus && ap_table_get(grpstatus,w)) {
1092 // If we matched, then we're done with this rule either way and status is set to reflect the outcome.
1094 request.log(SPRequest::SPDebug, string("htaccess: require group ") + (negate ? "rejecting (" : "accepting (") + w + ")");
1099 else if (!strcmp(w,"authnContextClassRef") || !strcmp(w,"authnContextDeclRef")) {
1100 const char* ref = !strcmp(w,"authnContextClassRef") ? session->getAuthnContextClassRef() : session->getAuthnContextDeclRef();
1101 bool regexp=false,negate=false;
1103 w=ap_getword_conf(sta->m_req->pool,&t);
1115 // Figure out if there's a match.
1119 // To do regex matching, we have to convert from UTF-8.
1120 RegularExpression re(w);
1121 match = re.matches(ref);
1123 catch (XMLException& ex) {
1124 auto_ptr_char tmp(ex.getMessage());
1125 request.log(SPRequest::SPError,
1126 string("htaccess plugin caught exception while parsing regular expression (") + w + "): " + tmp.get());
1129 else if (!strcmp(w,ref)) {
1134 // If we matched, then we're done with this rule either way and status is set to reflect the outcome.
1136 if (request.isPriorityEnabled(SPRequest::SPDebug))
1137 request.log(SPRequest::SPDebug,
1138 string("htaccess: require authnContext ") + (negate ? "rejecting (" : "accepting (") + ref + ")");
1143 else if (!session) {
1144 request.log(SPRequest::SPError, string("htaccess: require ") + w + " not given a valid session, are you using lazy sessions?");
1147 // Find the attribute(s) matching the require rule.
1148 pair<multimap<string,const Attribute*>::const_iterator,multimap<string,const Attribute*>::const_iterator> attrs =
1149 session->getIndexedAttributes().equal_range(w);
1152 while (!status && attrs.first!=attrs.second && *t) {
1153 w=ap_getword_conf(sta->m_req->pool,&t);
1160 auto_ptr<RegularExpression> re;
1162 delete re.release();
1163 auto_arrayptr<XMLCh> trans(fromUTF8(w));
1164 auto_ptr<xercesc::RegularExpression> temp(new xercesc::RegularExpression(trans.get()));
1168 pair<multimap<string,const Attribute*>::const_iterator,multimap<string,const Attribute*>::const_iterator> attrs2(attrs);
1169 for (; !status && attrs2.first!=attrs2.second; ++attrs2.first) {
1170 if (checkAttribute(request, attrs2.first->second, w, regexp ? re.get() : nullptr)) {
1175 catch (XMLException& ex) {
1176 auto_ptr_char tmp(ex.getMessage());
1177 request.log(SPRequest::SPError,
1178 string("htaccess plugin caught exception while parsing regular expression (") + w + "): " + tmp.get()
1184 // If status is false, we found a rule we couldn't satisfy.
1185 // Could be an unknown rule to us, or it just didn't match.
1187 if (status && sta->m_dc->bRequireAll != 1) {
1188 // If we're not insisting that all rules be met, then we're done.
1189 request.log(SPRequest::SPDebug, "htaccess: a rule was successful, granting access");
1190 return shib_acl_true;
1192 else if (!status && sta->m_dc->bRequireAll == 1) {
1193 // If we're insisting that all rules be met, which is not something Apache really handles well,
1194 // then we either return false or indeterminate based on the authoritative option, which defaults on.
1195 if (sta->m_dc->bAuthoritative != 0) {
1196 request.log(SPRequest::SPDebug, "htaccess: a rule was unsuccessful, denying access");
1197 return shib_acl_false;
1200 request.log(SPRequest::SPDebug, "htaccess: a rule was unsuccessful but not authoritative, leaving it up to Apache");
1201 return shib_acl_indeterminate;
1204 // Otherwise, we keep going. If we're requring all, then we have to check every rule.
1205 // If not we just didn't find a successful rule yet, so we keep going anyway.
1208 // If we get here, we either "failed" or we're in require all mode (but not both).
1209 // If no rules possibly apply or we insisted that all rules check out, then we're good.
1210 if (!method_restricted) {
1211 request.log(SPRequest::SPDebug, "htaccess: no rules applied to this request method, granting access");
1212 return shib_acl_true;
1214 else if (sta->m_dc->bRequireAll == 1) {
1215 request.log(SPRequest::SPDebug, "htaccess: all rules successful, granting access");
1216 return shib_acl_true;
1218 else if (sta->m_dc->bAuthoritative != 0) {
1219 request.log(SPRequest::SPDebug, "htaccess: no rules were successful, denying access");
1220 return shib_acl_false;
1223 request.log(SPRequest::SPDebug, "htaccess: no rules were successful but not authoritative, leaving it up to Apache");
1224 return shib_acl_indeterminate;
1228 // Initial look at a request - create the per-request structure
1229 static int shib_post_read(request_rec *r)
1231 shib_request_config* rc = init_request_config(r);
1232 //ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_post_read");
1236 // fixups: set environment vars
1238 extern "C" int shib_fixups(request_rec* r)
1240 shib_request_config *rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
1241 shib_dir_config *dc = (shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib);
1242 if (dc->bOff==1 || dc->bUseEnvVars==0)
1245 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_fixup(%d): ENTER", (int)getpid());
1247 if (rc==nullptr || rc->env==nullptr || ap_is_empty_table(rc->env))
1250 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_fixup adding %d vars", ap_table_elts(rc->env)->nelts);
1251 r->subprocess_env = ap_overlay_tables(r->pool, r->subprocess_env, rc->env);
1256 #ifdef SHIB_APACHE_13
1259 * Cleanup the (per-process) pool info.
1261 extern "C" void shib_child_exit(server_rec* s, SH_AP_POOL* p)
1264 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit(%d) dealing with g_Config..", (int)getpid());
1267 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit() done");
1273 * Apache 2.x doesn't allow for per-child cleanup, causes CGI forks to hang.
1275 extern "C" apr_status_t shib_exit(void* data)
1281 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,0,nullptr,"shib_exit() done");
1287 * shire_child_init()
1288 * Things to do when the child process is initialized.
1289 * (or after the configs are read in apache-2)
1291 #ifdef SHIB_APACHE_13
1292 extern "C" void shib_child_init(server_rec* s, SH_AP_POOL* p)
1294 extern "C" void shib_child_init(apr_pool_t* p, server_rec* s)
1297 // Initialize runtime components.
1299 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init(%d) starting", (int)getpid());
1302 ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() already initialized!");
1306 g_Config=&SPConfig::getConfig();
1307 g_Config->setFeatures(
1308 SPConfig::Listener |
1310 SPConfig::RequestMapping |
1311 SPConfig::InProcess |
1315 if (!g_Config->init(g_szSchemaDir, g_szPrefix)) {
1316 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize libraries");
1319 g_Config->AccessControlManager.registerFactory(HT_ACCESS_CONTROL,&htAccessFactory);
1320 g_Config->RequestMapperManager.registerFactory(NATIVE_REQUEST_MAPPER,&ApacheRequestMapFactory);
1323 if (!g_Config->instantiate(g_szSHIBConfig, true))
1324 throw runtime_error("unknown error");
1326 catch (exception& ex) {
1327 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),ex.what());
1328 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to load configuration");
1332 ServiceProvider* sp=g_Config->getServiceProvider();
1333 xmltooling::Locker locker(sp);
1334 const PropertySet* props=sp->getPropertySet("InProcess");
1336 pair<bool,const char*> unsetValue=props->getString("unsetHeaderValue");
1337 if (unsetValue.first)
1338 g_unsetHeaderValue = unsetValue.second;
1339 pair<bool,bool> flag=props->getBool("checkSpoofing");
1340 g_checkSpoofing = !flag.first || flag.second;
1341 if (g_checkSpoofing) {
1342 unsetValue=props->getString("spoofKey");
1343 if (unsetValue.first)
1344 g_spoofKey = unsetValue.second;
1346 flag=props->getBool("catchAll");
1347 g_catchAll = flag.first && flag.second;
1350 // Set the cleanup handler
1351 apr_pool_cleanup_register(p, nullptr, &shib_exit, apr_pool_cleanup_null);
1353 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() done");
1357 #ifdef SHIB_DEFERRED_HEADERS
1358 static void set_output_filter(request_rec *r)
1360 ap_add_output_filter("SHIB_HEADERS_OUT", nullptr, r, r->connection);
1363 static void set_error_filter(request_rec *r)
1365 ap_add_output_filter("SHIB_HEADERS_ERR", nullptr, r, r->connection);
1368 static int _table_add(void *v, const char *key, const char *value)
1370 apr_table_addn((apr_table_t*)v, key, value);
1374 static apr_status_t do_output_filter(ap_filter_t *f, apr_bucket_brigade *in)
1376 request_rec *r = f->r;
1377 shib_request_config *rc = (shib_request_config*) ap_get_module_config(r->request_config, &mod_shib);
1379 if (rc && rc->hdr_out) {
1380 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_out_filter: merging %d headers", apr_table_elts(rc->hdr_out)->nelts);
1381 // can't use overlap call because it will collapse Set-Cookie headers
1382 //apr_table_overlap(r->headers_out, rc->hdr_out, APR_OVERLAP_TABLES_MERGE);
1383 apr_table_do(_table_add,r->headers_out, rc->hdr_out,nullptr);
1386 /* remove ourselves from the filter chain */
1387 ap_remove_output_filter(f);
1389 /* send the data up the stack */
1390 return ap_pass_brigade(f->next,in);
1393 static apr_status_t do_error_filter(ap_filter_t *f, apr_bucket_brigade *in)
1395 request_rec *r = f->r;
1396 shib_request_config *rc = (shib_request_config*) ap_get_module_config(r->request_config, &mod_shib);
1398 if (rc && rc->hdr_out) {
1399 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_err_filter: merging %d headers", apr_table_elts(rc->hdr_out)->nelts);
1400 // can't use overlap call because it will collapse Set-Cookie headers
1401 //apr_table_overlap(r->err_headers_out, rc->hdr_out, APR_OVERLAP_TABLES_MERGE);
1402 apr_table_do(_table_add,r->err_headers_out, rc->hdr_out,nullptr);
1405 /* remove ourselves from the filter chain */
1406 ap_remove_output_filter(f);
1408 /* send the data up the stack */
1409 return ap_pass_brigade(f->next,in);
1411 #endif // SHIB_DEFERRED_HEADERS
1413 typedef const char* (*config_fn_t)(void);
1415 #ifdef SHIB_APACHE_13
1417 // SHIB Module commands
1419 static command_rec shire_cmds[] = {
1420 {"ShibPrefix", (config_fn_t)ap_set_global_string_slot, &g_szPrefix,
1421 RSRC_CONF, TAKE1, "Shibboleth installation directory"},
1422 {"ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1423 RSRC_CONF, TAKE1, "Path to shibboleth2.xml config file"},
1424 {"ShibCatalogs", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1425 RSRC_CONF, TAKE1, "Paths of XML schema catalogs"},
1427 {"ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
1428 (void *) XtOffsetOf (shib_server_config, szScheme),
1429 RSRC_CONF, TAKE1, "URL scheme to force into generated URLs for a vhost"},
1431 {"ShibRequestSetting", (config_fn_t)shib_table_set, nullptr,
1432 OR_AUTHCFG, TAKE2, "Set arbitrary Shibboleth request property for content"},
1434 {"ShibDisable", (config_fn_t)ap_set_flag_slot,
1435 (void *) XtOffsetOf (shib_dir_config, bOff),
1436 OR_AUTHCFG, FLAG, "Disable all Shib module activity here to save processing effort"},
1437 {"ShibApplicationId", (config_fn_t)ap_set_string_slot,
1438 (void *) XtOffsetOf (shib_dir_config, szApplicationId),
1439 OR_AUTHCFG, TAKE1, "Set Shibboleth applicationId property for content"},
1440 {"ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1441 (void *) XtOffsetOf (shib_dir_config, bBasicHijack),
1442 OR_AUTHCFG, FLAG, "Respond to AuthType Basic and convert to shibboleth"},
1443 {"ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1444 (void *) XtOffsetOf (shib_dir_config, bRequireSession),
1445 OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist"},
1446 {"ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
1447 (void *) XtOffsetOf (shib_dir_config, szRequireWith),
1448 OR_AUTHCFG, TAKE1, "Initiates a new session if one does not exist using a specific SessionInitiator"},
1449 {"ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1450 (void *) XtOffsetOf (shib_dir_config, bExportAssertion),
1451 OR_AUTHCFG, FLAG, "Export SAML attribute assertion(s) to Shib-Attributes header"},
1452 {"ShibRedirectToSSL", (config_fn_t)ap_set_string_slot,
1453 (void *) XtOffsetOf (shib_dir_config, szRedirectToSSL),
1454 OR_AUTHCFG, TAKE1, "Redirect non-SSL requests to designated port" },
1455 {"AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
1456 (void *) XtOffsetOf (shib_dir_config, szAuthGrpFile),
1457 OR_AUTHCFG, TAKE1, "text file containing group names and member user IDs"},
1458 {"ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1459 (void *) XtOffsetOf (shib_dir_config, bRequireAll),
1460 OR_AUTHCFG, FLAG, "All require directives must match"},
1461 {"AuthzShibAuthoritative", (config_fn_t)ap_set_flag_slot,
1462 (void *) XtOffsetOf (shib_dir_config, bAuthoritative),
1463 OR_AUTHCFG, FLAG, "Allow failed mod_shib htaccess authorization to fall through to other modules"},
1464 {"ShibUseEnvironment", (config_fn_t)ap_set_flag_slot,
1465 (void *) XtOffsetOf (shib_dir_config, bUseEnvVars),
1466 OR_AUTHCFG, FLAG, "Export attributes using environment variables (default)"},
1467 {"ShibUseHeaders", (config_fn_t)ap_set_flag_slot,
1468 (void *) XtOffsetOf (shib_dir_config, bUseHeaders),
1469 OR_AUTHCFG, FLAG, "Export attributes using custom HTTP headers"},
1475 handler_rec shib_handlers[] = {
1476 { "shib-handler", shib_handler },
1480 module MODULE_VAR_EXPORT mod_shib = {
1481 STANDARD_MODULE_STUFF,
1482 nullptr, /* initializer */
1483 create_shib_dir_config, /* dir config creater */
1484 merge_shib_dir_config, /* dir merger --- default is to override */
1485 create_shib_server_config, /* server config */
1486 merge_shib_server_config, /* merge server config */
1487 shire_cmds, /* command table */
1488 shib_handlers, /* handlers */
1489 nullptr, /* filename translation */
1490 shib_check_user, /* check_user_id */
1491 shib_auth_checker, /* check auth */
1492 nullptr, /* check access */
1493 nullptr, /* type_checker */
1494 shib_fixups, /* fixups */
1495 nullptr, /* logger */
1496 nullptr, /* header parser */
1497 shib_child_init, /* child_init */
1498 shib_child_exit, /* child_exit */
1499 shib_post_read /* post read-request */
1502 #elif defined(SHIB_APACHE_20) || defined(SHIB_APACHE_22)
1504 extern "C" void shib_register_hooks (apr_pool_t *p)
1506 #ifdef SHIB_DEFERRED_HEADERS
1507 ap_register_output_filter("SHIB_HEADERS_OUT", do_output_filter, nullptr, AP_FTYPE_CONTENT_SET);
1508 ap_hook_insert_filter(set_output_filter, nullptr, nullptr, APR_HOOK_LAST);
1509 ap_register_output_filter("SHIB_HEADERS_ERR", do_error_filter, nullptr, AP_FTYPE_CONTENT_SET);
1510 ap_hook_insert_error_filter(set_error_filter, nullptr, nullptr, APR_HOOK_LAST);
1511 ap_hook_post_read_request(shib_post_read, nullptr, nullptr, APR_HOOK_MIDDLE);
1513 ap_hook_child_init(shib_child_init, nullptr, nullptr, APR_HOOK_MIDDLE);
1514 ap_hook_check_user_id(shib_check_user, nullptr, nullptr, APR_HOOK_MIDDLE);
1515 ap_hook_auth_checker(shib_auth_checker, nullptr, nullptr, APR_HOOK_FIRST);
1516 ap_hook_handler(shib_handler, nullptr, nullptr, APR_HOOK_LAST);
1517 ap_hook_fixups(shib_fixups, nullptr, nullptr, APR_HOOK_MIDDLE);
1520 // SHIB Module commands
1523 static command_rec shib_cmds[] = {
1524 AP_INIT_TAKE1("ShibPrefix", (config_fn_t)ap_set_global_string_slot, &g_szPrefix,
1525 RSRC_CONF, "Shibboleth installation directory"),
1526 AP_INIT_TAKE1("ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1527 RSRC_CONF, "Path to shibboleth2.xml config file"),
1528 AP_INIT_TAKE1("ShibCatalogs", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1529 RSRC_CONF, "Paths of XML schema catalogs"),
1531 AP_INIT_TAKE1("ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
1532 (void *) offsetof (shib_server_config, szScheme),
1533 RSRC_CONF, "URL scheme to force into generated URLs for a vhost"),
1535 AP_INIT_TAKE2("ShibRequestSetting", (config_fn_t)shib_table_set, nullptr,
1536 OR_AUTHCFG, "Set arbitrary Shibboleth request property for content"),
1538 AP_INIT_FLAG("ShibDisable", (config_fn_t)ap_set_flag_slot,
1539 (void *) offsetof (shib_dir_config, bOff),
1540 OR_AUTHCFG, "Disable all Shib module activity here to save processing effort"),
1541 AP_INIT_TAKE1("ShibApplicationId", (config_fn_t)ap_set_string_slot,
1542 (void *) offsetof (shib_dir_config, szApplicationId),
1543 OR_AUTHCFG, "Set Shibboleth applicationId property for content"),
1544 AP_INIT_FLAG("ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1545 (void *) offsetof (shib_dir_config, bBasicHijack),
1546 OR_AUTHCFG, "Respond to AuthType Basic and convert to shibboleth"),
1547 AP_INIT_FLAG("ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1548 (void *) offsetof (shib_dir_config, bRequireSession),
1549 OR_AUTHCFG, "Initiates a new session if one does not exist"),
1550 AP_INIT_TAKE1("ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
1551 (void *) offsetof (shib_dir_config, szRequireWith),
1552 OR_AUTHCFG, "Initiates a new session if one does not exist using a specific SessionInitiator"),
1553 AP_INIT_FLAG("ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1554 (void *) offsetof (shib_dir_config, bExportAssertion),
1555 OR_AUTHCFG, "Export SAML attribute assertion(s) to Shib-Attributes header"),
1556 AP_INIT_TAKE1("ShibRedirectToSSL", (config_fn_t)ap_set_string_slot,
1557 (void *) offsetof (shib_dir_config, szRedirectToSSL),
1558 OR_AUTHCFG, "Redirect non-SSL requests to designated port"),
1559 AP_INIT_TAKE1("AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
1560 (void *) offsetof (shib_dir_config, szAuthGrpFile),
1561 OR_AUTHCFG, "Text file containing group names and member user IDs"),
1562 AP_INIT_FLAG("ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1563 (void *) offsetof (shib_dir_config, bRequireAll),
1564 OR_AUTHCFG, "All require directives must match"),
1565 AP_INIT_FLAG("AuthzShibAuthoritative", (config_fn_t)ap_set_flag_slot,
1566 (void *) offsetof (shib_dir_config, bAuthoritative),
1567 OR_AUTHCFG, "Allow failed mod_shib htaccess authorization to fall through to other modules"),
1568 AP_INIT_FLAG("ShibUseEnvironment", (config_fn_t)ap_set_flag_slot,
1569 (void *) offsetof (shib_dir_config, bUseEnvVars),
1570 OR_AUTHCFG, "Export attributes using environment variables (default)"),
1571 AP_INIT_FLAG("ShibUseHeaders", (config_fn_t)ap_set_flag_slot,
1572 (void *) offsetof (shib_dir_config, bUseHeaders),
1573 OR_AUTHCFG, "Export attributes using custom HTTP headers"),
1578 module AP_MODULE_DECLARE_DATA mod_shib = {
1579 STANDARD20_MODULE_STUFF,
1580 create_shib_dir_config, /* create dir config */
1581 merge_shib_dir_config, /* merge dir config --- default is to override */
1582 create_shib_server_config, /* create server config */
1583 merge_shib_server_config, /* merge server config */
1584 shib_cmds, /* command table */
1585 shib_register_hooks /* register hooks */
1589 #error "unsupported Apache version"