2 * Copyright 2001-2011 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/exceptions.h>
35 #include <shibsp/AbstractSPRequest.h>
36 #include <shibsp/AccessControl.h>
37 #include <shibsp/GSSRequest.h>
38 #include <shibsp/RequestMapper.h>
39 #include <shibsp/SPConfig.h>
40 #include <shibsp/ServiceProvider.h>
41 #include <shibsp/SessionCache.h>
42 #include <shibsp/attribute/Attribute.h>
44 #include <xercesc/util/XMLUniDefs.hpp>
45 #include <xercesc/util/regx/RegularExpression.hpp>
46 #include <xmltooling/XMLToolingConfig.h>
47 #include <xmltooling/util/NDC.h>
48 #include <xmltooling/util/ParserPool.h>
49 #include <xmltooling/util/Threads.h>
50 #include <xmltooling/util/XMLConstants.h>
51 #include <xmltooling/util/XMLHelper.h>
59 // Apache specific header files
61 #include <http_config.h>
62 #include <http_protocol.h>
63 #include <http_main.h>
65 #include <http_core.h>
67 #include <http_request.h>
69 #ifndef SHIB_APACHE_13
70 #include <apr_buckets.h>
71 #include <apr_strings.h>
72 #include <apr_pools.h>
82 #include <unistd.h> // for getpid()
85 using namespace shibsp;
86 using namespace xmltooling;
88 using xercesc::RegularExpression;
89 using xercesc::XMLException;
91 extern "C" module MODULE_VAR_EXPORT mod_shib;
94 char* g_szSHIBConfig = nullptr;
95 char* g_szSchemaDir = nullptr;
96 char* g_szPrefix = nullptr;
97 SPConfig* g_Config = nullptr;
98 string g_unsetHeaderValue,g_spoofKey;
99 bool g_checkSpoofing = true;
100 bool g_catchAll = false;
101 #ifndef SHIB_APACHE_13
102 char* g_szGSSContextKey = "mod_auth_gssapi:gss_ctx";
104 static const char* g_UserDataKey = "urn:mace:shibboleth:Apache:shib_check_user";
107 /* Apache 2.2.x headers must be accumulated and set in the output filter.
108 Apache 2.0.49+ supports the filter method.
109 Apache 1.3.x and lesser 2.0.x must write the headers directly. */
111 #if (defined(SHIB_APACHE_20) || defined(SHIB_APACHE_22)) && AP_MODULE_MAGIC_AT_LEAST(20020903,6)
112 #define SHIB_DEFERRED_HEADERS
115 /********************************************************************************/
116 // Basic Apache Configuration code.
119 // per-server module configuration structure
120 struct shib_server_config
125 // creates the per-server configuration
126 extern "C" void* create_shib_server_config(SH_AP_POOL* p, server_rec* s)
128 shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
129 sc->szScheme = nullptr;
133 // overrides server configuration in virtual servers
134 extern "C" void* merge_shib_server_config (SH_AP_POOL* p, void* base, void* sub)
136 shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
137 shib_server_config* parent=(shib_server_config*)base;
138 shib_server_config* child=(shib_server_config*)sub;
141 sc->szScheme=ap_pstrdup(p,child->szScheme);
142 else if (parent->szScheme)
143 sc->szScheme=ap_pstrdup(p,parent->szScheme);
145 sc->szScheme=nullptr;
150 // per-dir module configuration structure
151 struct shib_dir_config
153 SH_AP_TABLE* tSettings; // generic table of extensible settings
156 char* szAuthGrpFile; // Auth GroupFile name
157 int bRequireAll; // all "known" require directives must match, otherwise OR logic
158 int bAuthoritative; // allow htaccess plugin to DECLINE when authz fails
160 // Content Configuration
161 char* szApplicationId; // Shib applicationId value
162 char* szRequireWith; // require a session using a specific initiator?
163 char* szRedirectToSSL; // redirect non-SSL requests to SSL port
164 char* szAccessControl; // path to "external" AccessControl plugin file
165 int bOff; // flat-out disable all Shib processing
166 int bBasicHijack; // activate for AuthType Basic?
167 int bRequireSession; // require a session?
168 int bExportAssertion; // export SAML assertion to the environment?
169 int bUseEnvVars; // use environment?
170 int bUseHeaders; // use headers?
173 // creates per-directory config structure
174 extern "C" void* create_shib_dir_config (SH_AP_POOL* p, char* d)
176 shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
177 dc->tSettings = nullptr;
178 dc->szAuthGrpFile = nullptr;
179 dc->bRequireAll = -1;
180 dc->bAuthoritative = -1;
181 dc->szApplicationId = nullptr;
182 dc->szRequireWith = nullptr;
183 dc->szRedirectToSSL = nullptr;
184 dc->szAccessControl = nullptr;
186 dc->bBasicHijack = -1;
187 dc->bRequireSession = -1;
188 dc->bExportAssertion = -1;
189 dc->bUseEnvVars = -1;
190 dc->bUseHeaders = -1;
194 // overrides server configuration in directories
195 extern "C" void* merge_shib_dir_config (SH_AP_POOL* p, void* base, void* sub)
197 shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
198 shib_dir_config* parent=(shib_dir_config*)base;
199 shib_dir_config* child=(shib_dir_config*)sub;
201 // The child supersedes any matching table settings in the parent.
202 dc->tSettings = nullptr;
203 if (parent->tSettings)
204 dc->tSettings = ap_copy_table(p, parent->tSettings);
205 if (child->tSettings) {
207 ap_overlap_tables(dc->tSettings, child->tSettings, AP_OVERLAP_TABLES_SET);
209 dc->tSettings = ap_copy_table(p, child->tSettings);
212 if (child->szAuthGrpFile)
213 dc->szAuthGrpFile=ap_pstrdup(p,child->szAuthGrpFile);
214 else if (parent->szAuthGrpFile)
215 dc->szAuthGrpFile=ap_pstrdup(p,parent->szAuthGrpFile);
217 dc->szAuthGrpFile=nullptr;
219 if (child->szApplicationId)
220 dc->szApplicationId=ap_pstrdup(p,child->szApplicationId);
221 else if (parent->szApplicationId)
222 dc->szApplicationId=ap_pstrdup(p,parent->szApplicationId);
224 dc->szApplicationId=nullptr;
226 if (child->szRequireWith)
227 dc->szRequireWith=ap_pstrdup(p,child->szRequireWith);
228 else if (parent->szRequireWith)
229 dc->szRequireWith=ap_pstrdup(p,parent->szRequireWith);
231 dc->szRequireWith=nullptr;
233 if (child->szRedirectToSSL)
234 dc->szRedirectToSSL=ap_pstrdup(p,child->szRedirectToSSL);
235 else if (parent->szRedirectToSSL)
236 dc->szRedirectToSSL=ap_pstrdup(p,parent->szRedirectToSSL);
238 dc->szRedirectToSSL=nullptr;
240 if (child->szAccessControl)
241 dc->szAccessControl=ap_pstrdup(p,child->szAccessControl);
242 else if (parent->szAccessControl)
243 dc->szAccessControl=ap_pstrdup(p,parent->szAccessControl);
245 dc->szAccessControl=nullptr;
247 dc->bOff=((child->bOff==-1) ? parent->bOff : child->bOff);
248 dc->bBasicHijack=((child->bBasicHijack==-1) ? parent->bBasicHijack : child->bBasicHijack);
249 dc->bRequireSession=((child->bRequireSession==-1) ? parent->bRequireSession : child->bRequireSession);
250 dc->bExportAssertion=((child->bExportAssertion==-1) ? parent->bExportAssertion : child->bExportAssertion);
251 dc->bRequireAll=((child->bRequireAll==-1) ? parent->bRequireAll : child->bRequireAll);
252 dc->bAuthoritative=((child->bAuthoritative==-1) ? parent->bAuthoritative : child->bAuthoritative);
253 dc->bUseEnvVars=((child->bUseEnvVars==-1) ? parent->bUseEnvVars : child->bUseEnvVars);
254 dc->bUseHeaders=((child->bUseHeaders==-1) ? parent->bUseHeaders : child->bUseHeaders);
258 // per-request module structure
259 struct shib_request_config
261 SH_AP_TABLE *env; // environment vars
262 #ifdef SHIB_DEFERRED_HEADERS
263 SH_AP_TABLE *hdr_out; // headers to browser
267 // create a request record
268 static shib_request_config *init_request_config(request_rec *r)
270 shib_request_config* rc=(shib_request_config*)ap_pcalloc(r->pool,sizeof(shib_request_config));
271 ap_set_module_config (r->request_config, &mod_shib, rc);
272 memset(rc, 0, sizeof(shib_request_config));
273 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_init_rc");
277 // generic global slot handlers
278 extern "C" const char* ap_set_global_string_slot(cmd_parms* parms, void*, const char* arg)
280 *((char**)(parms->info))=ap_pstrdup(parms->pool,arg);
284 extern "C" const char* shib_set_server_string_slot(cmd_parms* parms, void*, const char* arg)
286 char* base=(char*)ap_get_module_config(parms->server->module_config,&mod_shib);
287 size_t offset=(size_t)parms->info;
288 *((char**)(base + offset))=ap_pstrdup(parms->pool,arg);
292 extern "C" const char* shib_ap_set_file_slot(cmd_parms* parms,
293 #ifdef SHIB_APACHE_13
294 char* arg1, char* arg2
296 void* arg1, const char* arg2
300 ap_set_file_slot(parms, arg1, arg2);
304 extern "C" const char* shib_table_set(cmd_parms* parms, shib_dir_config* dc, const char* arg1, const char* arg2)
307 dc->tSettings = ap_make_table(parms->pool, 4);
308 ap_table_set(dc->tSettings, arg1, arg2);
313 class ShibTargetApache : public AbstractSPRequest
314 #if defined(HAVE_GSSAPI) && !defined(SHIB_APACHE_13)
319 mutable string m_body;
320 mutable bool m_gotBody,m_firsttime;
321 mutable vector<string> m_certs;
322 set<string> m_allhttp;
326 shib_dir_config* m_dc;
327 shib_server_config* m_sc;
328 shib_request_config* m_rc;
330 ShibTargetApache(request_rec* req, bool handler, bool shib_check_user)
331 : AbstractSPRequest(SHIBSP_LOGCAT".Apache"), m_handler(handler), m_gotBody(false),m_firsttime(true) {
332 m_sc = (shib_server_config*)ap_get_module_config(req->server->module_config, &mod_shib);
333 m_dc = (shib_dir_config*)ap_get_module_config(req->per_dir_config, &mod_shib);
334 m_rc = (shib_request_config*)ap_get_module_config(req->request_config, &mod_shib);
337 setRequestURI(m_req->unparsed_uri);
339 if (shib_check_user && m_dc->bUseHeaders == 1) {
340 // Try and see if this request was already processed, to skip spoof checking.
341 if (!ap_is_initial_req(m_req)) {
344 else if (!g_spoofKey.empty()) {
345 const char* hdr = ap_table_get(m_req->headers_in, "Shib-Spoof-Check");
346 if (hdr && g_spoofKey == hdr)
351 log(SPDebug, "shib_check_user running more than once");
354 virtual ~ShibTargetApache() {}
356 const char* getScheme() const {
357 return m_sc->szScheme ? m_sc->szScheme : ap_http_method(m_req);
359 const char* getHostname() const {
360 return ap_get_server_name(m_req);
362 int getPort() const {
363 return ap_get_server_port(m_req);
365 const char* getMethod() const {
366 return m_req->method;
368 string getContentType() const {
369 const char* type = ap_table_get(m_req->headers_in, "Content-Type");
370 return type ? type : "";
372 long getContentLength() const {
373 return m_gotBody ? m_body.length() : m_req->remaining;
375 string getRemoteAddr() const {
376 string ret = AbstractSPRequest::getRemoteAddr();
377 return ret.empty() ? m_req->connection->remote_ip : ret;
379 void log(SPLogLevel level, const string& msg) const {
380 AbstractSPRequest::log(level,msg);
383 (level == SPDebug ? APLOG_DEBUG :
384 (level == SPInfo ? APLOG_INFO :
385 (level == SPWarn ? APLOG_WARNING :
386 (level == SPError ? APLOG_ERR : APLOG_CRIT))))|APLOG_NOERRNO,
392 const char* getQueryString() const { return m_req->args; }
393 const char* getRequestBody() const {
394 if (m_gotBody || m_req->method_number==M_GET)
395 return m_body.c_str();
396 #ifdef SHIB_APACHE_13
397 // Read the posted data
398 if (ap_setup_client_block(m_req, REQUEST_CHUNKED_DECHUNK) != OK) {
400 log(SPError, "Apache function (setup_client_block) failed while reading request body.");
401 return m_body.c_str();
403 if (!ap_should_client_block(m_req)) {
405 log(SPError, "Apache function (should_client_block) failed while reading request body.");
406 return m_body.c_str();
408 if (m_req->remaining > 1024*1024)
409 throw opensaml::SecurityPolicyException("Blocked request body larger than 1M size limit.");
412 char buff[HUGE_STRING_LEN];
413 ap_hard_timeout("[mod_shib] getRequestBody", m_req);
414 while ((len=ap_get_client_block(m_req, buff, sizeof(buff))) > 0) {
415 ap_reset_timeout(m_req);
416 m_body.append(buff, len);
418 ap_kill_timeout(m_req);
423 apr_bucket_brigade* bb = apr_brigade_create(m_req->pool, m_req->connection->bucket_alloc);
426 apr_status_t rv = ap_get_brigade(m_req->input_filters, bb, AP_MODE_READBYTES, APR_BLOCK_READ, HUGE_STRING_LEN);
427 if (rv != APR_SUCCESS) {
428 log(SPError, "Apache function (ap_get_brigade) failed while reading request body.");
432 for (bucket = APR_BRIGADE_FIRST(bb); bucket != APR_BRIGADE_SENTINEL(bb); bucket = APR_BUCKET_NEXT(bucket)) {
433 if (APR_BUCKET_IS_EOS(bucket)) {
438 /* We can't do much with this. */
439 if (APR_BUCKET_IS_FLUSH(bucket))
443 apr_bucket_read(bucket, &data, &len, APR_BLOCK_READ);
445 m_body.append(data, len);
447 apr_brigade_cleanup(bb);
449 apr_brigade_destroy(bb);
452 return m_body.c_str();
454 void clearHeader(const char* rawname, const char* cginame) {
455 if (m_dc->bUseHeaders == 1) {
456 // ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_clear_header: hdr\n");
457 if (g_checkSpoofing && m_firsttime) {
458 if (m_allhttp.empty()) {
459 // First time, so populate set with "CGI" versions of client-supplied headers.
460 #ifdef SHIB_APACHE_13
461 array_header *hdrs_arr = ap_table_elts(m_req->headers_in);
462 table_entry *hdrs = (table_entry *) hdrs_arr->elts;
464 const apr_array_header_t *hdrs_arr = apr_table_elts(m_req->headers_in);
465 const apr_table_entry_t *hdrs = (const apr_table_entry_t *) hdrs_arr->elts;
467 for (int i = 0; i < hdrs_arr->nelts; ++i) {
470 string cgiversion("HTTP_");
471 const char* pch = hdrs[i].key;
473 cgiversion += (isalnum(*pch) ? toupper(*pch) : '_');
476 m_allhttp.insert(cgiversion);
480 if (m_allhttp.count(cginame) > 0)
481 throw opensaml::SecurityPolicyException("Attempt to spoof header ($1) was detected.", params(1, rawname));
483 ap_table_unset(m_req->headers_in, rawname);
484 ap_table_set(m_req->headers_in, rawname, g_unsetHeaderValue.c_str());
487 void setHeader(const char* name, const char* value) {
488 if (m_dc->bUseEnvVars != 0) {
490 // this happens on subrequests
491 // ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_setheader: no_m_rc\n");
492 m_rc = init_request_config(m_req);
495 m_rc->env = ap_make_table(m_req->pool, 10);
496 // ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_set_env: %s=%s\n", name, value?value:"Null");
497 ap_table_set(m_rc->env, name, value ? value : "");
499 if (m_dc->bUseHeaders == 1)
500 ap_table_set(m_req->headers_in, name, value);
502 string getHeader(const char* name) const {
503 const char* hdr = ap_table_get(m_req->headers_in, name);
504 return string(hdr ? hdr : "");
506 string getSecureHeader(const char* name) const {
507 if (m_dc->bUseEnvVars != 0) {
509 if (m_rc && m_rc->env)
510 hdr = ap_table_get(m_rc->env, name);
513 return string(hdr ? hdr : "");
515 return getHeader(name);
517 void setRemoteUser(const char* user) {
518 SH_AP_USER(m_req) = user ? ap_pstrdup(m_req->pool, user) : nullptr;
519 if (m_dc->bUseHeaders == 1) {
521 ap_table_set(m_req->headers_in, "REMOTE_USER", user);
524 ap_table_unset(m_req->headers_in, "REMOTE_USER");
525 ap_table_set(m_req->headers_in, "REMOTE_USER", g_unsetHeaderValue.c_str());
529 string getRemoteUser() const {
530 return string(SH_AP_USER(m_req) ? SH_AP_USER(m_req) : "");
532 void setAuthType(const char* authtype) {
533 if (authtype && m_dc->bBasicHijack == 1)
535 SH_AP_AUTH_TYPE(m_req) = authtype ? ap_pstrdup(m_req->pool, authtype) : nullptr;
537 string getAuthType() const {
538 return string(SH_AP_AUTH_TYPE(m_req) ? SH_AP_AUTH_TYPE(m_req) : "");
540 void setContentType(const char* type) {
541 m_req->content_type = ap_psprintf(m_req->pool, "%s", type);
543 void setResponseHeader(const char* name, const char* value) {
544 HTTPResponse::setResponseHeader(name, value);
545 #ifdef SHIB_DEFERRED_HEADERS
547 // this happens on subrequests
548 m_rc = init_request_config(m_req);
551 m_rc->hdr_out = ap_make_table(m_req->pool, 5);
552 ap_table_add(m_rc->hdr_out, name, value);
556 ap_table_add(m_req->err_headers_out, name, value);
558 long sendResponse(istream& in, long status) {
559 if (status != XMLTOOLING_HTTP_STATUS_OK)
560 m_req->status = status;
561 ap_send_http_header(m_req);
565 ap_rwrite(buf,in.gcount(),m_req);
567 #if (defined(SHIB_APACHE_20) || defined(SHIB_APACHE_22))
568 if (status != XMLTOOLING_HTTP_STATUS_OK && status != XMLTOOLING_HTTP_STATUS_ERROR)
573 long sendRedirect(const char* url) {
574 HTTPResponse::sendRedirect(url);
575 ap_table_set(m_req->headers_out, "Location", url);
578 const vector<string>& getClientCertificates() const {
579 if (m_certs.empty()) {
580 const char* cert = ap_table_get(m_req->subprocess_env, "SSL_CLIENT_CERT");
582 m_certs.push_back(cert);
585 cert = ap_table_get(m_req->subprocess_env, ap_psprintf(m_req->pool, "SSL_CLIENT_CERT_CHAIN_%d", i++));
587 m_certs.push_back(cert);
592 long returnDecline(void) { return DECLINED; }
593 long returnOK(void) { return OK; }
594 #if defined(HAVE_GSSAPI) && !defined(SHIB_APACHE_13)
595 gss_ctx_id_t getGSSContext() const {
596 gss_ctx_id_t ctx = GSS_C_NO_CONTEXT;
597 apr_pool_userdata_get((void**)&ctx, g_szGSSContextKey, m_req->pool);
603 /********************************************************************************/
606 extern "C" int shib_check_user(request_rec* r)
608 // Short-circuit entirely?
609 if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
612 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_check_user(%d): ENTER", (int)getpid());
614 ostringstream threadid;
615 threadid << "[" << getpid() << "] shib_check_user" << '\0';
616 xmltooling::NDC ndc(threadid.str().c_str());
619 ShibTargetApache sta(r,false,true);
621 // Check user authentication and export information, then set the handler bypass
622 pair<bool,long> res = sta.getServiceProvider().doAuthentication(sta,true);
623 apr_pool_userdata_setn((const void*)42,g_UserDataKey,nullptr,r->pool);
624 // If directed, install a spoof key to recognize when we've already cleared headers.
625 if (!g_spoofKey.empty() && (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bUseHeaders==1))
626 ap_table_set(r->headers_in, "Shib-Spoof-Check", g_spoofKey.c_str());
627 if (res.first) return res.second;
629 // user auth was okay -- export the assertions now
630 res = sta.getServiceProvider().doExport(sta);
631 if (res.first) return res.second;
633 // export happened successfully.. this user is ok.
636 catch (exception& e) {
637 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user threw an exception: %s", e.what());
641 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user threw an unknown exception!");
648 extern "C" int shib_handler(request_rec* r)
650 // Short-circuit entirely?
651 if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
654 ostringstream threadid;
655 threadid << "[" << getpid() << "] shib_handler" << '\0';
656 xmltooling::NDC ndc(threadid.str().c_str());
658 #ifndef SHIB_APACHE_13
659 // With 2.x, this handler always runs, though last.
660 // We check if shib_check_user ran, because it will detect a handler request
661 // and dispatch it directly.
663 apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
664 if (data==(const void*)42) {
665 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler skipped since check_user ran");
670 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler(%d): ENTER: %s", (int)getpid(), r->handler);
673 ShibTargetApache sta(r,true,false);
675 pair<bool,long> res = sta.getServiceProvider().doHandler(sta);
676 if (res.first) return res.second;
678 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "doHandler() did not do anything.");
681 catch (exception& e) {
682 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler threw an exception: %s", e.what());
686 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler threw an unknown exception!");
694 * shib_auth_checker() -- a simple resource manager to
695 * process the .htaccess settings
697 extern "C" int shib_auth_checker(request_rec* r)
699 // Short-circuit entirely?
700 if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
703 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_auth_checker(%d): ENTER", (int)getpid());
705 ostringstream threadid;
706 threadid << "[" << getpid() << "] shib_auth_checker" << '\0';
707 xmltooling::NDC ndc(threadid.str().c_str());
710 ShibTargetApache sta(r,false,false);
712 pair<bool,long> res = sta.getServiceProvider().doAuthorization(sta);
713 if (res.first) return res.second;
715 // The SP method should always return true, so if we get this far, something unusual happened.
716 // Just let Apache (or some other module) decide what to do.
719 catch (exception& e) {
720 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an exception: %s", e.what());
724 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an unknown exception!");
731 // Access control plugin that enforces htaccess rules
732 class htAccessControl : virtual public AccessControl
736 ~htAccessControl() {}
737 Lockable* lock() {return this;}
739 aclresult_t authorized(const SPRequest& request, const Session* session) const;
741 bool checkAttribute(const SPRequest& request, const Attribute* attr, const char* toMatch, RegularExpression* re) const;
744 AccessControl* htAccessFactory(const xercesc::DOMElement* const & e)
746 return new htAccessControl();
749 class ApacheRequestMapper : public virtual RequestMapper, public virtual PropertySet
752 ApacheRequestMapper(const xercesc::DOMElement* e);
753 ~ApacheRequestMapper() { delete m_mapper; delete m_htaccess; delete m_staKey; delete m_propsKey; }
754 Lockable* lock() { return m_mapper->lock(); }
755 void unlock() { m_staKey->setData(nullptr); m_propsKey->setData(nullptr); m_mapper->unlock(); }
756 Settings getSettings(const HTTPRequest& request) const;
758 const PropertySet* getParent() const { return nullptr; }
759 void setParent(const PropertySet*) {}
760 pair<bool,bool> getBool(const char* name, const char* ns=nullptr) const;
761 pair<bool,const char*> getString(const char* name, const char* ns=nullptr) const;
762 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=nullptr) const;
763 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=nullptr) const;
764 pair<bool,int> getInt(const char* name, const char* ns=nullptr) const;
765 void getAll(map<string,const char*>& properties) const;
766 const PropertySet* getPropertySet(const char* name, const char* ns=shibspconstants::ASCII_SHIB2SPCONFIG_NS) const;
767 const xercesc::DOMElement* getElement() const;
770 RequestMapper* m_mapper;
772 ThreadKey* m_propsKey;
773 AccessControl* m_htaccess;
776 RequestMapper* ApacheRequestMapFactory(const xercesc::DOMElement* const & e)
778 return new ApacheRequestMapper(e);
781 ApacheRequestMapper::ApacheRequestMapper(const xercesc::DOMElement* e) : m_mapper(nullptr), m_staKey(nullptr), m_propsKey(nullptr), m_htaccess(nullptr)
783 m_mapper=SPConfig::getConfig().RequestMapperManager.newPlugin(XML_REQUEST_MAPPER,e);
784 m_htaccess=new htAccessControl();
785 m_staKey=ThreadKey::create(nullptr);
786 m_propsKey=ThreadKey::create(nullptr);
789 RequestMapper::Settings ApacheRequestMapper::getSettings(const HTTPRequest& request) const
791 Settings s=m_mapper->getSettings(request);
792 m_staKey->setData((void*)dynamic_cast<const ShibTargetApache*>(&request));
793 m_propsKey->setData((void*)s.first);
794 return pair<const PropertySet*,AccessControl*>(this,s.second ? s.second : m_htaccess);
797 pair<bool,bool> ApacheRequestMapper::getBool(const char* name, const char* ns) const
799 const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
800 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
802 // Override Apache-settable boolean properties.
803 if (name && !strcmp(name,"requireSession") && sta->m_dc->bRequireSession != -1)
804 return make_pair(true, sta->m_dc->bRequireSession==1);
805 else if (name && !strcmp(name,"exportAssertion") && sta->m_dc->bExportAssertion != -1)
806 return make_pair(true, sta->m_dc->bExportAssertion==1);
807 else if (sta->m_dc->tSettings) {
808 const char* prop = ap_table_get(sta->m_dc->tSettings, name);
810 return make_pair(true, !strcmp(prop, "true") || !strcmp(prop, "1") || !strcmp(prop, "On"));
813 return s ? s->getBool(name,ns) : make_pair(false,false);
816 pair<bool,const char*> ApacheRequestMapper::getString(const char* name, const char* ns) const
818 const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
819 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
821 // Override Apache-settable string properties.
822 if (name && !strcmp(name,"authType")) {
823 const char *auth_type=ap_auth_type(sta->m_req);
825 // Check for Basic Hijack
826 if (!strcasecmp(auth_type, "basic") && sta->m_dc->bBasicHijack == 1)
827 auth_type = "shibboleth";
828 return make_pair(true,auth_type);
831 else if (name && !strcmp(name,"applicationId") && sta->m_dc->szApplicationId)
832 return pair<bool,const char*>(true,sta->m_dc->szApplicationId);
833 else if (name && !strcmp(name,"requireSessionWith") && sta->m_dc->szRequireWith)
834 return pair<bool,const char*>(true,sta->m_dc->szRequireWith);
835 else if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
836 return pair<bool,const char*>(true,sta->m_dc->szRedirectToSSL);
837 else if (sta->m_dc->tSettings) {
838 const char* prop = ap_table_get(sta->m_dc->tSettings, name);
840 return make_pair(true, prop);
843 return s ? s->getString(name,ns) : pair<bool,const char*>(false,nullptr);
846 pair<bool,const XMLCh*> ApacheRequestMapper::getXMLString(const char* name, const char* ns) const
848 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
849 return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,nullptr);
852 pair<bool,unsigned int> ApacheRequestMapper::getUnsignedInt(const char* name, const char* ns) const
854 const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
855 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
857 // Override Apache-settable int properties.
858 if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
859 return pair<bool,unsigned int>(true, strtol(sta->m_dc->szRedirectToSSL, nullptr, 10));
860 else if (sta->m_dc->tSettings) {
861 const char* prop = ap_table_get(sta->m_dc->tSettings, name);
863 return pair<bool,unsigned int>(true, atoi(prop));
866 return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
869 pair<bool,int> ApacheRequestMapper::getInt(const char* name, const char* ns) const
871 const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
872 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
874 // Override Apache-settable int properties.
875 if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
876 return pair<bool,int>(true,atoi(sta->m_dc->szRedirectToSSL));
877 else if (sta->m_dc->tSettings) {
878 const char* prop = ap_table_get(sta->m_dc->tSettings, name);
880 return make_pair(true, atoi(prop));
883 return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
886 static int _rm_get_all_table_walk(void *v, const char *key, const char *value)
888 reinterpret_cast<map<string,const char*>*>(v)->insert(pair<string,const char*>(key, value));
892 void ApacheRequestMapper::getAll(map<string,const char*>& properties) const
894 const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
895 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
898 s->getAll(properties);
902 const char* auth_type=ap_auth_type(sta->m_req);
904 // Check for Basic Hijack
905 if (!strcasecmp(auth_type, "basic") && sta->m_dc->bBasicHijack == 1)
906 auth_type = "shibboleth";
907 properties["authType"] = auth_type;
910 if (sta->m_dc->szApplicationId)
911 properties["applicationId"] = sta->m_dc->szApplicationId;
912 if (sta->m_dc->szRequireWith)
913 properties["requireSessionWith"] = sta->m_dc->szRequireWith;
914 if (sta->m_dc->szRedirectToSSL)
915 properties["redirectToSSL"] = sta->m_dc->szRedirectToSSL;
916 if (sta->m_dc->bRequireSession != 0)
917 properties["requireSession"] = (sta->m_dc->bRequireSession==1) ? "true" : "false";
918 if (sta->m_dc->bExportAssertion != 0)
919 properties["exportAssertion"] = (sta->m_dc->bExportAssertion==1) ? "true" : "false";
921 if (sta->m_dc->tSettings)
922 ap_table_do(_rm_get_all_table_walk, &properties, sta->m_dc->tSettings, nullptr);
925 const PropertySet* ApacheRequestMapper::getPropertySet(const char* name, const char* ns) const
927 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
928 return s ? s->getPropertySet(name,ns) : nullptr;
931 const xercesc::DOMElement* ApacheRequestMapper::getElement() const
933 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
934 return s ? s->getElement() : nullptr;
937 static SH_AP_TABLE* groups_for_user(request_rec* r, const char* user, char* grpfile)
940 SH_AP_TABLE* grps=ap_make_table(r->pool,15);
941 char l[MAX_STRING_LEN];
942 const char *group_name, *ll, *w;
944 #ifdef SHIB_APACHE_13
945 if (!(f=ap_pcfg_openfile(r->pool,grpfile))) {
947 if (ap_pcfg_openfile(&f,r->pool,grpfile) != APR_SUCCESS) {
949 ap_log_rerror(APLOG_MARK,APLOG_DEBUG,SH_AP_R(r),"groups_for_user() could not open group file: %s\n",grpfile);
954 #ifdef SHIB_APACHE_13
955 sp=ap_make_sub_pool(r->pool);
957 if (apr_pool_create(&sp,r->pool) != APR_SUCCESS) {
958 ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,
959 "groups_for_user() could not create a subpool");
964 while (!(ap_cfg_getline(l,MAX_STRING_LEN,f))) {
965 if ((*l=='#') || (!*l))
970 group_name=ap_getword(sp,&ll,':');
973 w=ap_getword_conf(sp,&ll);
974 if (!strcmp(w,user)) {
975 ap_table_setn(grps,ap_pstrdup(r->pool,group_name),"in");
985 bool htAccessControl::checkAttribute(const SPRequest& request, const Attribute* attr, const char* toMatch, RegularExpression* re) const
987 bool caseSensitive = attr->isCaseSensitive();
988 const vector<string>& vals = attr->getSerializedValues();
989 for (vector<string>::const_iterator v=vals.begin(); v!=vals.end(); ++v) {
991 auto_arrayptr<XMLCh> trans(fromUTF8(v->c_str()));
992 if (re->matches(trans.get())) {
993 if (request.isPriorityEnabled(SPRequest::SPDebug))
994 request.log(SPRequest::SPDebug, string("htaccess: expecting regexp ") + toMatch + ", got " + *v + ": acccepted");
998 else if ((caseSensitive && *v == toMatch) || (!caseSensitive && !strcasecmp(v->c_str(), toMatch))) {
999 if (request.isPriorityEnabled(SPRequest::SPDebug))
1000 request.log(SPRequest::SPDebug, string("htaccess: expecting ") + toMatch + ", got " + *v + ": accepted");
1003 else if (request.isPriorityEnabled(SPRequest::SPDebug)) {
1004 request.log(SPRequest::SPDebug, string("htaccess: expecting ") + toMatch + ", got " + *v + ": rejected");
1010 AccessControl::aclresult_t htAccessControl::authorized(const SPRequest& request, const Session* session) const
1012 // Make sure the object is our type.
1013 const ShibTargetApache* sta=dynamic_cast<const ShibTargetApache*>(&request);
1015 throw ConfigurationException("Request wrapper object was not of correct type.");
1017 int m=sta->m_req->method_number;
1018 bool method_restricted=false;
1021 const array_header* reqs_arr=ap_requires(sta->m_req);
1023 return shib_acl_indeterminate; // should never happen
1025 // Check for an "embedded" AccessControl plugin.
1026 if (sta->m_dc->szAccessControl) {
1027 aclresult_t result = shib_acl_false;
1029 ifstream aclfile(sta->m_dc->szAccessControl);
1030 xercesc::DOMDocument* acldoc = XMLToolingConfig::getConfig().getParser().parse(aclfile);
1031 XercesJanitor<xercesc::DOMDocument> docjanitor(acldoc);
1032 static XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
1033 string t(XMLHelper::getAttrString(acldoc ? acldoc->getDocumentElement() : nullptr, nullptr, _type));
1035 throw ConfigurationException("Missing type attribute in AccessControl plugin configuration.");
1036 auto_ptr<AccessControl> aclplugin(SPConfig::getConfig().AccessControlManager.newPlugin(t.c_str(), acldoc->getDocumentElement()));
1037 Locker acllock(aclplugin.get());
1038 result = aclplugin->authorized(request, session);
1040 catch (exception& ex) {
1041 request.log(SPRequest::SPError, ex.what());
1044 if (result == shib_acl_true && sta->m_dc->bRequireAll != 1) {
1045 // If we're not insisting that all rules be met, then we're done.
1046 request.log(SPRequest::SPDebug, "htaccess: embedded AccessControl plugin was successful, granting access");
1047 return shib_acl_true;
1049 else if (result != shib_acl_true && sta->m_dc->bRequireAll == 1) {
1050 // If we're insisting that all rules be met, which is not something Apache really handles well,
1051 // then we either return false or indeterminate based on the authoritative option, which defaults on.
1052 if (sta->m_dc->bAuthoritative != 0) {
1053 request.log(SPRequest::SPDebug, "htaccess: embedded AccessControl plugin was unsuccessful, denying access");
1054 return shib_acl_false;
1057 request.log(SPRequest::SPDebug, "htaccess: embedded AccessControl plugin was unsuccessful but not authoritative, leaving it up to Apache");
1058 return shib_acl_indeterminate;
1063 require_line* reqs=(require_line*)reqs_arr->elts;
1065 for (int x=0; x<reqs_arr->nelts; x++) {
1066 // This rule should be completely ignored, the method doesn't fit.
1067 // The rule just doesn't exist for our purposes.
1068 if (!(reqs[x].method_mask & (1 << m)))
1071 method_restricted=true; // this lets us know at the end that at least one rule was potentially enforcable.
1073 // Tracks status of this rule's evaluation.
1074 bool status = false;
1076 string remote_user = request.getRemoteUser();
1078 t = reqs[x].requirement;
1079 w = ap_getword_white(sta->m_req->pool, &t);
1081 if (!strcasecmp(w,"shibboleth")) {
1082 // This is a dummy rule needed because Apache conflates authn and authz.
1083 // Without some require rule, AuthType is ignored and no check_user hooks run.
1085 // We evaluate to false if ShibAccessControl is used and ShibRequireAll is off.
1086 // This allows actual rules to dictate the result, since ShibAccessControl returned
1087 // non-true, and if nothing else is used, access will be denied.
1088 if (!sta->m_dc->szAccessControl || sta->m_dc->bRequireAll == 1) {
1089 // We evaluate to true, because ShibRequireAll is enabled (so a true is just a no-op)
1090 // or because there was no other AccessControl rule in place, so this may be the only
1095 else if (!strcmp(w,"valid-user") && session) {
1096 request.log(SPRequest::SPDebug, "htaccess: accepting valid-user based on active session");
1099 else if (!strcmp(w,"user") && !remote_user.empty()) {
1100 bool regexp = false;
1102 w = ap_getword_conf(sta->m_req->pool,&t);
1107 else if (*w == '!') {
1108 // A negated rule presumes success unless a match is found.
1115 // Figure out if there's a match.
1119 // To do regex matching, we have to convert from UTF-8.
1120 auto_arrayptr<XMLCh> trans(fromUTF8(w));
1121 RegularExpression re(trans.get());
1122 auto_arrayptr<XMLCh> trans2(fromUTF8(remote_user.c_str()));
1123 match = re.matches(trans2.get());
1125 catch (XMLException& ex) {
1126 auto_ptr_char tmp(ex.getMessage());
1127 request.log(SPRequest::SPError,
1128 string("htaccess plugin caught exception while parsing regular expression (") + w + "): " + tmp.get());
1131 else if (remote_user == w) {
1136 // If we matched, then we're done with this rule either way and we flip status to reflect the outcome.
1138 if (request.isPriorityEnabled(SPRequest::SPDebug))
1139 request.log(SPRequest::SPDebug,
1140 string("htaccess: require user ") + (!status ? "rejecting (" : "accepting (") + remote_user + ")");
1145 else if (!strcmp(w,"group") && !remote_user.empty()) {
1146 SH_AP_TABLE* grpstatus = nullptr;
1147 if (sta->m_dc->szAuthGrpFile) {
1148 if (request.isPriorityEnabled(SPRequest::SPDebug))
1149 request.log(SPRequest::SPDebug,string("htaccess plugin using groups file: ") + sta->m_dc->szAuthGrpFile);
1150 grpstatus = groups_for_user(sta->m_req,remote_user.c_str(),sta->m_dc->szAuthGrpFile);
1154 w = ap_getword_conf(sta->m_req->pool,&t);
1156 // A negated rule presumes success unless a match is found.
1161 if (grpstatus && ap_table_get(grpstatus,w)) {
1162 // If we matched, then we're done with this rule either way and we flip status to reflect the outcome.
1164 request.log(SPRequest::SPDebug, string("htaccess: require group ") + (!status ? "rejecting (" : "accepting (") + w + ")");
1169 else if (!strcmp(w,"authnContextClassRef") || !strcmp(w,"authnContextDeclRef")) {
1170 const char* ref = !strcmp(w,"authnContextClassRef") ? session->getAuthnContextClassRef() : session->getAuthnContextDeclRef();
1172 bool regexp = false;
1174 w = ap_getword_conf(sta->m_req->pool,&t);
1179 else if (*w == '!') {
1180 // A negated rule presumes success unless a match is found.
1187 // Figure out if there's a match.
1191 // To do regex matching, we have to convert from UTF-8.
1192 RegularExpression re(w);
1193 match = re.matches(ref);
1195 catch (XMLException& ex) {
1196 auto_ptr_char tmp(ex.getMessage());
1197 request.log(SPRequest::SPError,
1198 string("htaccess plugin caught exception while parsing regular expression (") + w + "): " + tmp.get());
1201 else if (!strcmp(w,ref)) {
1206 // If we matched, then we're done with this rule either way and we flip status to reflect the outcome.
1208 if (request.isPriorityEnabled(SPRequest::SPDebug))
1209 request.log(SPRequest::SPDebug,
1210 string("htaccess: require authnContext ") + (!status ? "rejecting (" : "accepting (") + ref + ")");
1215 else if (request.isPriorityEnabled(SPRequest::SPDebug)) {
1216 request.log(SPRequest::SPDebug, "htaccess: require authnContext rejecting session with no context associated");
1219 else if (!session) {
1220 request.log(SPRequest::SPError, string("htaccess: require ") + w + " not given a valid session, are you using lazy sessions?");
1223 // Find the attribute(s) matching the require rule.
1224 pair<multimap<string,const Attribute*>::const_iterator,multimap<string,const Attribute*>::const_iterator> attrs =
1225 session->getIndexedAttributes().equal_range(w);
1228 while (!status && attrs.first!=attrs.second && *t) {
1229 w=ap_getword_conf(sta->m_req->pool,&t);
1236 auto_ptr<RegularExpression> re;
1238 delete re.release();
1239 auto_arrayptr<XMLCh> trans(fromUTF8(w));
1240 auto_ptr<xercesc::RegularExpression> temp(new xercesc::RegularExpression(trans.get()));
1244 pair<multimap<string,const Attribute*>::const_iterator,multimap<string,const Attribute*>::const_iterator> attrs2(attrs);
1245 for (; !status && attrs2.first!=attrs2.second; ++attrs2.first) {
1246 if (checkAttribute(request, attrs2.first->second, w, regexp ? re.get() : nullptr)) {
1251 catch (XMLException& ex) {
1252 auto_ptr_char tmp(ex.getMessage());
1253 request.log(SPRequest::SPError,
1254 string("htaccess plugin caught exception while parsing regular expression (") + w + "): " + tmp.get()
1260 // If status is false, we found a rule we couldn't satisfy.
1261 // Could be an unknown rule to us, or it just didn't match.
1263 if (status && sta->m_dc->bRequireAll != 1) {
1264 // If we're not insisting that all rules be met, then we're done.
1265 request.log(SPRequest::SPDebug, "htaccess: a rule was successful, granting access");
1266 return shib_acl_true;
1268 else if (!status && sta->m_dc->bRequireAll == 1) {
1269 // If we're insisting that all rules be met, which is not something Apache really handles well,
1270 // then we either return false or indeterminate based on the authoritative option, which defaults on.
1271 if (sta->m_dc->bAuthoritative != 0) {
1272 request.log(SPRequest::SPDebug, "htaccess: a rule was unsuccessful, denying access");
1273 return shib_acl_false;
1276 request.log(SPRequest::SPDebug, "htaccess: a rule was unsuccessful but not authoritative, leaving it up to Apache");
1277 return shib_acl_indeterminate;
1280 // Otherwise, we keep going. If we're requring all, then we have to check every rule.
1281 // If not we just didn't find a successful rule yet, so we keep going anyway.
1284 // If we get here, we either "failed" or we're in require all mode (but not both).
1285 // If no rules possibly apply or we insisted that all rules check out, then we're good.
1286 if (!method_restricted) {
1287 request.log(SPRequest::SPDebug, "htaccess: no rules applied to this request method, granting access");
1288 return shib_acl_true;
1290 else if (sta->m_dc->bRequireAll == 1) {
1291 request.log(SPRequest::SPDebug, "htaccess: all rules successful, granting access");
1292 return shib_acl_true;
1294 else if (sta->m_dc->bAuthoritative != 0) {
1295 request.log(SPRequest::SPDebug, "htaccess: no rules were successful, denying access");
1296 return shib_acl_false;
1299 request.log(SPRequest::SPDebug, "htaccess: no rules were successful but not authoritative, leaving it up to Apache");
1300 return shib_acl_indeterminate;
1304 // Initial look at a request - create the per-request structure
1305 static int shib_post_read(request_rec *r)
1307 init_request_config(r);
1308 //ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_post_read");
1312 // fixups: set environment vars
1314 extern "C" int shib_fixups(request_rec* r)
1316 shib_request_config *rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
1317 shib_dir_config *dc = (shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib);
1318 if (dc->bOff==1 || dc->bUseEnvVars==0)
1321 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_fixup(%d): ENTER", (int)getpid());
1323 if (rc==nullptr || rc->env==nullptr || ap_is_empty_table(rc->env))
1326 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_fixup adding %d vars", ap_table_elts(rc->env)->nelts);
1327 r->subprocess_env = ap_overlay_tables(r->pool, r->subprocess_env, rc->env);
1332 #ifdef SHIB_APACHE_13
1335 * Cleanup the (per-process) pool info.
1337 extern "C" void shib_child_exit(server_rec* s, SH_AP_POOL* p)
1340 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit(%d) dealing with g_Config..", (int)getpid());
1343 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit() done");
1349 * Apache 2.x doesn't allow for per-child cleanup, causes CGI forks to hang.
1351 extern "C" apr_status_t shib_exit(void* data)
1357 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,0,nullptr,"shib_exit() done");
1363 * shire_child_init()
1364 * Things to do when the child process is initialized.
1365 * (or after the configs are read in apache-2)
1367 #ifdef SHIB_APACHE_13
1368 extern "C" void shib_child_init(server_rec* s, SH_AP_POOL* p)
1370 extern "C" void shib_child_init(apr_pool_t* p, server_rec* s)
1373 // Initialize runtime components.
1375 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init(%d) starting", (int)getpid());
1378 ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() already initialized!");
1382 g_Config=&SPConfig::getConfig();
1383 g_Config->setFeatures(
1384 SPConfig::Listener |
1386 SPConfig::RequestMapping |
1387 SPConfig::InProcess |
1391 if (!g_Config->init(g_szSchemaDir, g_szPrefix)) {
1392 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize libraries");
1395 g_Config->AccessControlManager.registerFactory(HT_ACCESS_CONTROL,&htAccessFactory);
1396 g_Config->RequestMapperManager.registerFactory(NATIVE_REQUEST_MAPPER,&ApacheRequestMapFactory);
1399 if (!g_Config->instantiate(g_szSHIBConfig, true))
1400 throw runtime_error("unknown error");
1402 catch (exception& ex) {
1403 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"%s",ex.what());
1404 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to load configuration");
1408 ServiceProvider* sp=g_Config->getServiceProvider();
1409 xmltooling::Locker locker(sp);
1410 const PropertySet* props=sp->getPropertySet("InProcess");
1412 pair<bool,const char*> unsetValue=props->getString("unsetHeaderValue");
1413 if (unsetValue.first)
1414 g_unsetHeaderValue = unsetValue.second;
1415 pair<bool,bool> flag=props->getBool("checkSpoofing");
1416 g_checkSpoofing = !flag.first || flag.second;
1417 if (g_checkSpoofing) {
1418 unsetValue=props->getString("spoofKey");
1419 if (unsetValue.first)
1420 g_spoofKey = unsetValue.second;
1422 flag=props->getBool("catchAll");
1423 g_catchAll = flag.first && flag.second;
1426 // Set the cleanup handler
1427 apr_pool_cleanup_register(p, nullptr, &shib_exit, apr_pool_cleanup_null);
1429 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() done");
1433 #ifdef SHIB_DEFERRED_HEADERS
1434 static void set_output_filter(request_rec *r)
1436 ap_add_output_filter("SHIB_HEADERS_OUT", nullptr, r, r->connection);
1439 static void set_error_filter(request_rec *r)
1441 ap_add_output_filter("SHIB_HEADERS_ERR", nullptr, r, r->connection);
1444 static int _table_add(void *v, const char *key, const char *value)
1446 apr_table_addn((apr_table_t*)v, key, value);
1450 static apr_status_t do_output_filter(ap_filter_t *f, apr_bucket_brigade *in)
1452 request_rec *r = f->r;
1453 shib_request_config *rc = (shib_request_config*) ap_get_module_config(r->request_config, &mod_shib);
1455 if (rc && rc->hdr_out) {
1456 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);
1457 // can't use overlap call because it will collapse Set-Cookie headers
1458 //apr_table_overlap(r->headers_out, rc->hdr_out, APR_OVERLAP_TABLES_MERGE);
1459 apr_table_do(_table_add,r->headers_out, rc->hdr_out,nullptr);
1462 /* remove ourselves from the filter chain */
1463 ap_remove_output_filter(f);
1465 /* send the data up the stack */
1466 return ap_pass_brigade(f->next,in);
1469 static apr_status_t do_error_filter(ap_filter_t *f, apr_bucket_brigade *in)
1471 request_rec *r = f->r;
1472 shib_request_config *rc = (shib_request_config*) ap_get_module_config(r->request_config, &mod_shib);
1474 if (rc && rc->hdr_out) {
1475 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);
1476 // can't use overlap call because it will collapse Set-Cookie headers
1477 //apr_table_overlap(r->err_headers_out, rc->hdr_out, APR_OVERLAP_TABLES_MERGE);
1478 apr_table_do(_table_add,r->err_headers_out, rc->hdr_out,nullptr);
1481 /* remove ourselves from the filter chain */
1482 ap_remove_output_filter(f);
1484 /* send the data up the stack */
1485 return ap_pass_brigade(f->next,in);
1487 #endif // SHIB_DEFERRED_HEADERS
1489 typedef const char* (*config_fn_t)(void);
1491 #ifdef SHIB_APACHE_13
1493 // SHIB Module commands
1495 static command_rec shire_cmds[] = {
1496 {"ShibPrefix", (config_fn_t)ap_set_global_string_slot, &g_szPrefix,
1497 RSRC_CONF, TAKE1, "Shibboleth installation directory"},
1498 {"ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1499 RSRC_CONF, TAKE1, "Path to shibboleth2.xml config file"},
1500 {"ShibCatalogs", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1501 RSRC_CONF, TAKE1, "Paths of XML schema catalogs"},
1503 {"ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
1504 (void *) XtOffsetOf (shib_server_config, szScheme),
1505 RSRC_CONF, TAKE1, "URL scheme to force into generated URLs for a vhost"},
1507 {"ShibRequestSetting", (config_fn_t)shib_table_set, nullptr,
1508 OR_AUTHCFG, TAKE2, "Set arbitrary Shibboleth request property for content"},
1510 {"ShibAccessControl", (config_fn_t)ap_set_string_slot,
1511 (void *) XtOffsetOf (shib_dir_config, szAccessControl),
1512 OR_AUTHCFG, TAKE1, "Set arbitrary Shibboleth access control plugin for content"},
1514 {"ShibDisable", (config_fn_t)ap_set_flag_slot,
1515 (void *) XtOffsetOf (shib_dir_config, bOff),
1516 OR_AUTHCFG, FLAG, "Disable all Shib module activity here to save processing effort"},
1517 {"ShibApplicationId", (config_fn_t)ap_set_string_slot,
1518 (void *) XtOffsetOf (shib_dir_config, szApplicationId),
1519 OR_AUTHCFG, TAKE1, "Set Shibboleth applicationId property for content"},
1520 {"ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1521 (void *) XtOffsetOf (shib_dir_config, bBasicHijack),
1522 OR_AUTHCFG, FLAG, "(DEPRECATED) Respond to AuthType Basic and convert to shibboleth"},
1523 {"ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1524 (void *) XtOffsetOf (shib_dir_config, bRequireSession),
1525 OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist"},
1526 {"ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
1527 (void *) XtOffsetOf (shib_dir_config, szRequireWith),
1528 OR_AUTHCFG, TAKE1, "Initiates a new session if one does not exist using a specific SessionInitiator"},
1529 {"ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1530 (void *) XtOffsetOf (shib_dir_config, bExportAssertion),
1531 OR_AUTHCFG, FLAG, "Export SAML attribute assertion(s) to Shib-Attributes header"},
1532 {"ShibRedirectToSSL", (config_fn_t)ap_set_string_slot,
1533 (void *) XtOffsetOf (shib_dir_config, szRedirectToSSL),
1534 OR_AUTHCFG, TAKE1, "Redirect non-SSL requests to designated port" },
1535 {"AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
1536 (void *) XtOffsetOf (shib_dir_config, szAuthGrpFile),
1537 OR_AUTHCFG, TAKE1, "text file containing group names and member user IDs"},
1538 {"ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1539 (void *) XtOffsetOf (shib_dir_config, bRequireAll),
1540 OR_AUTHCFG, FLAG, "All require directives must match"},
1541 {"AuthzShibAuthoritative", (config_fn_t)ap_set_flag_slot,
1542 (void *) XtOffsetOf (shib_dir_config, bAuthoritative),
1543 OR_AUTHCFG, FLAG, "Allow failed mod_shib htaccess authorization to fall through to other modules"},
1544 {"ShibUseEnvironment", (config_fn_t)ap_set_flag_slot,
1545 (void *) XtOffsetOf (shib_dir_config, bUseEnvVars),
1546 OR_AUTHCFG, FLAG, "Export attributes using environment variables (default)"},
1547 {"ShibUseHeaders", (config_fn_t)ap_set_flag_slot,
1548 (void *) XtOffsetOf (shib_dir_config, bUseHeaders),
1549 OR_AUTHCFG, FLAG, "Export attributes using custom HTTP headers"},
1555 handler_rec shib_handlers[] = {
1556 { "shib-handler", shib_handler },
1560 module MODULE_VAR_EXPORT mod_shib = {
1561 STANDARD_MODULE_STUFF,
1562 nullptr, /* initializer */
1563 create_shib_dir_config, /* dir config creater */
1564 merge_shib_dir_config, /* dir merger --- default is to override */
1565 create_shib_server_config, /* server config */
1566 merge_shib_server_config, /* merge server config */
1567 shire_cmds, /* command table */
1568 shib_handlers, /* handlers */
1569 nullptr, /* filename translation */
1570 shib_check_user, /* check_user_id */
1571 shib_auth_checker, /* check auth */
1572 nullptr, /* check access */
1573 nullptr, /* type_checker */
1574 shib_fixups, /* fixups */
1575 nullptr, /* logger */
1576 nullptr, /* header parser */
1577 shib_child_init, /* child_init */
1578 shib_child_exit, /* child_exit */
1579 shib_post_read /* post read-request */
1582 #elif defined(SHIB_APACHE_20) || defined(SHIB_APACHE_22)
1584 //static const char * const authnPre[] = { "mod_gss.c", nullptr };
1586 extern "C" void shib_register_hooks (apr_pool_t *p)
1588 #ifdef SHIB_DEFERRED_HEADERS
1589 ap_register_output_filter("SHIB_HEADERS_OUT", do_output_filter, nullptr, AP_FTYPE_CONTENT_SET);
1590 ap_hook_insert_filter(set_output_filter, nullptr, nullptr, APR_HOOK_LAST);
1591 ap_register_output_filter("SHIB_HEADERS_ERR", do_error_filter, nullptr, AP_FTYPE_CONTENT_SET);
1592 ap_hook_insert_error_filter(set_error_filter, nullptr, nullptr, APR_HOOK_LAST);
1593 ap_hook_post_read_request(shib_post_read, nullptr, nullptr, APR_HOOK_MIDDLE);
1595 ap_hook_child_init(shib_child_init, nullptr, nullptr, APR_HOOK_MIDDLE);
1596 const char* prereq = getenv("SHIBSP_APACHE_PREREQ");
1597 if (prereq && *prereq) {
1598 const char* const authnPre[] = { prereq, nullptr };
1599 ap_hook_check_user_id(shib_check_user, authnPre, nullptr, APR_HOOK_MIDDLE);
1602 ap_hook_check_user_id(shib_check_user, nullptr, nullptr, APR_HOOK_MIDDLE);
1604 ap_hook_auth_checker(shib_auth_checker, nullptr, nullptr, APR_HOOK_FIRST);
1605 ap_hook_handler(shib_handler, nullptr, nullptr, APR_HOOK_LAST);
1606 ap_hook_fixups(shib_fixups, nullptr, nullptr, APR_HOOK_MIDDLE);
1609 // SHIB Module commands
1612 static command_rec shib_cmds[] = {
1613 AP_INIT_TAKE1("ShibPrefix", (config_fn_t)ap_set_global_string_slot, &g_szPrefix,
1614 RSRC_CONF, "Shibboleth installation directory"),
1615 AP_INIT_TAKE1("ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1616 RSRC_CONF, "Path to shibboleth2.xml config file"),
1617 AP_INIT_TAKE1("ShibCatalogs", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1618 RSRC_CONF, "Paths of XML schema catalogs"),
1619 AP_INIT_TAKE1("ShibGSSKey", (config_fn_t)ap_set_global_string_slot, &g_szGSSContextKey,
1620 RSRC_CONF, "Name of user data key containing GSS context established by GSS module"),
1622 AP_INIT_TAKE1("ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
1623 (void *) offsetof (shib_server_config, szScheme),
1624 RSRC_CONF, "URL scheme to force into generated URLs for a vhost"),
1626 AP_INIT_TAKE2("ShibRequestSetting", (config_fn_t)shib_table_set, nullptr,
1627 OR_AUTHCFG, "Set arbitrary Shibboleth request property for content"),
1629 AP_INIT_TAKE1("ShibAccessControl", (config_fn_t)ap_set_string_slot,
1630 (void *) offsetof (shib_dir_config, szAccessControl),
1631 OR_AUTHCFG, "Set arbitrary Shibboleth access control plugin for content"),
1633 AP_INIT_FLAG("ShibDisable", (config_fn_t)ap_set_flag_slot,
1634 (void *) offsetof (shib_dir_config, bOff),
1635 OR_AUTHCFG, "Disable all Shib module activity here to save processing effort"),
1636 AP_INIT_TAKE1("ShibApplicationId", (config_fn_t)ap_set_string_slot,
1637 (void *) offsetof (shib_dir_config, szApplicationId),
1638 OR_AUTHCFG, "Set Shibboleth applicationId property for content"),
1639 AP_INIT_FLAG("ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1640 (void *) offsetof (shib_dir_config, bBasicHijack),
1641 OR_AUTHCFG, "(DEPRECATED) Respond to AuthType Basic and convert to shibboleth"),
1642 AP_INIT_FLAG("ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1643 (void *) offsetof (shib_dir_config, bRequireSession),
1644 OR_AUTHCFG, "Initiates a new session if one does not exist"),
1645 AP_INIT_TAKE1("ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
1646 (void *) offsetof (shib_dir_config, szRequireWith),
1647 OR_AUTHCFG, "Initiates a new session if one does not exist using a specific SessionInitiator"),
1648 AP_INIT_FLAG("ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1649 (void *) offsetof (shib_dir_config, bExportAssertion),
1650 OR_AUTHCFG, "Export SAML attribute assertion(s) to Shib-Attributes header"),
1651 AP_INIT_TAKE1("ShibRedirectToSSL", (config_fn_t)ap_set_string_slot,
1652 (void *) offsetof (shib_dir_config, szRedirectToSSL),
1653 OR_AUTHCFG, "Redirect non-SSL requests to designated port"),
1654 AP_INIT_TAKE1("AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
1655 (void *) offsetof (shib_dir_config, szAuthGrpFile),
1656 OR_AUTHCFG, "Text file containing group names and member user IDs"),
1657 AP_INIT_FLAG("ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1658 (void *) offsetof (shib_dir_config, bRequireAll),
1659 OR_AUTHCFG, "All require directives must match"),
1660 AP_INIT_FLAG("AuthzShibAuthoritative", (config_fn_t)ap_set_flag_slot,
1661 (void *) offsetof (shib_dir_config, bAuthoritative),
1662 OR_AUTHCFG, "Allow failed mod_shib htaccess authorization to fall through to other modules"),
1663 AP_INIT_FLAG("ShibUseEnvironment", (config_fn_t)ap_set_flag_slot,
1664 (void *) offsetof (shib_dir_config, bUseEnvVars),
1665 OR_AUTHCFG, "Export attributes using environment variables (default)"),
1666 AP_INIT_FLAG("ShibUseHeaders", (config_fn_t)ap_set_flag_slot,
1667 (void *) offsetof (shib_dir_config, bUseHeaders),
1668 OR_AUTHCFG, "Export attributes using custom HTTP headers"),
1673 module AP_MODULE_DECLARE_DATA mod_shib = {
1674 STANDARD20_MODULE_STUFF,
1675 create_shib_dir_config, /* create dir config */
1676 merge_shib_dir_config, /* merge dir config --- default is to override */
1677 create_shib_server_config, /* create server config */
1678 merge_shib_server_config, /* merge server config */
1679 shib_cmds, /* command table */
1680 shib_register_hooks /* register hooks */
1684 #error "unsupported Apache version"