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>
83 #include <unistd.h> // for getpid()
86 using namespace shibsp;
87 using namespace xmltooling;
89 using xercesc::RegularExpression;
90 using xercesc::XMLException;
92 extern "C" module MODULE_VAR_EXPORT mod_shib;
95 char* g_szSHIBConfig = nullptr;
96 char* g_szSchemaDir = nullptr;
97 char* g_szPrefix = nullptr;
98 SPConfig* g_Config = nullptr;
99 string g_unsetHeaderValue,g_spoofKey;
100 bool g_checkSpoofing = true;
101 bool g_catchAll = false;
102 #ifndef SHIB_APACHE_13
103 char* g_szGSSContextKey = "mod_auth_gssapi:gss_ctx";
105 static const char* g_UserDataKey = "urn:mace:shibboleth:Apache:shib_check_user";
108 /* Apache 2.2.x headers must be accumulated and set in the output filter.
109 Apache 2.0.49+ supports the filter method.
110 Apache 1.3.x and lesser 2.0.x must write the headers directly. */
112 #if (defined(SHIB_APACHE_20) || defined(SHIB_APACHE_22)) && AP_MODULE_MAGIC_AT_LEAST(20020903,6)
113 #define SHIB_DEFERRED_HEADERS
116 /********************************************************************************/
117 // Basic Apache Configuration code.
120 // per-server module configuration structure
121 struct shib_server_config
126 // creates the per-server configuration
127 extern "C" void* create_shib_server_config(SH_AP_POOL* p, server_rec* s)
129 shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
130 sc->szScheme = nullptr;
134 // overrides server configuration in virtual servers
135 extern "C" void* merge_shib_server_config (SH_AP_POOL* p, void* base, void* sub)
137 shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
138 shib_server_config* parent=(shib_server_config*)base;
139 shib_server_config* child=(shib_server_config*)sub;
142 sc->szScheme=ap_pstrdup(p,child->szScheme);
143 else if (parent->szScheme)
144 sc->szScheme=ap_pstrdup(p,parent->szScheme);
146 sc->szScheme=nullptr;
151 // per-dir module configuration structure
152 struct shib_dir_config
154 SH_AP_TABLE* tSettings; // generic table of extensible settings
157 char* szAuthGrpFile; // Auth GroupFile name
158 int bRequireAll; // all "known" require directives must match, otherwise OR logic
159 int bAuthoritative; // allow htaccess plugin to DECLINE when authz fails
161 // Content Configuration
162 char* szApplicationId; // Shib applicationId value
163 char* szRequireWith; // require a session using a specific initiator?
164 char* szRedirectToSSL; // redirect non-SSL requests to SSL port
165 char* szAccessControl; // path to "external" AccessControl plugin file
166 int bOff; // flat-out disable all Shib processing
167 int bBasicHijack; // activate for AuthType Basic?
168 int bRequireSession; // require a session?
169 int bExportAssertion; // export SAML assertion to the environment?
170 int bUseEnvVars; // use environment?
171 int bUseHeaders; // use headers?
174 // creates per-directory config structure
175 extern "C" void* create_shib_dir_config (SH_AP_POOL* p, char* d)
177 shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
178 dc->tSettings = nullptr;
179 dc->szAuthGrpFile = nullptr;
180 dc->bRequireAll = -1;
181 dc->bAuthoritative = -1;
182 dc->szApplicationId = nullptr;
183 dc->szRequireWith = nullptr;
184 dc->szRedirectToSSL = nullptr;
185 dc->szAccessControl = nullptr;
187 dc->bBasicHijack = -1;
188 dc->bRequireSession = -1;
189 dc->bExportAssertion = -1;
190 dc->bUseEnvVars = -1;
191 dc->bUseHeaders = -1;
195 // overrides server configuration in directories
196 extern "C" void* merge_shib_dir_config (SH_AP_POOL* p, void* base, void* sub)
198 shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
199 shib_dir_config* parent=(shib_dir_config*)base;
200 shib_dir_config* child=(shib_dir_config*)sub;
202 // The child supersedes any matching table settings in the parent.
203 dc->tSettings = nullptr;
204 if (parent->tSettings)
205 dc->tSettings = ap_copy_table(p, parent->tSettings);
206 if (child->tSettings) {
208 ap_overlap_tables(dc->tSettings, child->tSettings, AP_OVERLAP_TABLES_SET);
210 dc->tSettings = ap_copy_table(p, child->tSettings);
213 if (child->szAuthGrpFile)
214 dc->szAuthGrpFile=ap_pstrdup(p,child->szAuthGrpFile);
215 else if (parent->szAuthGrpFile)
216 dc->szAuthGrpFile=ap_pstrdup(p,parent->szAuthGrpFile);
218 dc->szAuthGrpFile=nullptr;
220 if (child->szApplicationId)
221 dc->szApplicationId=ap_pstrdup(p,child->szApplicationId);
222 else if (parent->szApplicationId)
223 dc->szApplicationId=ap_pstrdup(p,parent->szApplicationId);
225 dc->szApplicationId=nullptr;
227 if (child->szRequireWith)
228 dc->szRequireWith=ap_pstrdup(p,child->szRequireWith);
229 else if (parent->szRequireWith)
230 dc->szRequireWith=ap_pstrdup(p,parent->szRequireWith);
232 dc->szRequireWith=nullptr;
234 if (child->szRedirectToSSL)
235 dc->szRedirectToSSL=ap_pstrdup(p,child->szRedirectToSSL);
236 else if (parent->szRedirectToSSL)
237 dc->szRedirectToSSL=ap_pstrdup(p,parent->szRedirectToSSL);
239 dc->szRedirectToSSL=nullptr;
241 if (child->szAccessControl)
242 dc->szAccessControl=ap_pstrdup(p,child->szAccessControl);
243 else if (parent->szAccessControl)
244 dc->szAccessControl=ap_pstrdup(p,parent->szAccessControl);
246 dc->szAccessControl=nullptr;
248 dc->bOff=((child->bOff==-1) ? parent->bOff : child->bOff);
249 dc->bBasicHijack=((child->bBasicHijack==-1) ? parent->bBasicHijack : child->bBasicHijack);
250 dc->bRequireSession=((child->bRequireSession==-1) ? parent->bRequireSession : child->bRequireSession);
251 dc->bExportAssertion=((child->bExportAssertion==-1) ? parent->bExportAssertion : child->bExportAssertion);
252 dc->bRequireAll=((child->bRequireAll==-1) ? parent->bRequireAll : child->bRequireAll);
253 dc->bAuthoritative=((child->bAuthoritative==-1) ? parent->bAuthoritative : child->bAuthoritative);
254 dc->bUseEnvVars=((child->bUseEnvVars==-1) ? parent->bUseEnvVars : child->bUseEnvVars);
255 dc->bUseHeaders=((child->bUseHeaders==-1) ? parent->bUseHeaders : child->bUseHeaders);
259 // per-request module structure
260 struct shib_request_config
262 SH_AP_TABLE *env; // environment vars
263 #ifdef SHIB_DEFERRED_HEADERS
264 SH_AP_TABLE *hdr_out; // headers to browser
268 // create a request record
269 static shib_request_config *init_request_config(request_rec *r)
271 shib_request_config* rc=(shib_request_config*)ap_pcalloc(r->pool,sizeof(shib_request_config));
272 ap_set_module_config (r->request_config, &mod_shib, rc);
273 memset(rc, 0, sizeof(shib_request_config));
274 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_init_rc");
278 // generic global slot handlers
279 extern "C" const char* ap_set_global_string_slot(cmd_parms* parms, void*, const char* arg)
281 *((char**)(parms->info))=ap_pstrdup(parms->pool,arg);
285 extern "C" const char* shib_set_server_string_slot(cmd_parms* parms, void*, const char* arg)
287 char* base=(char*)ap_get_module_config(parms->server->module_config,&mod_shib);
288 size_t offset=(size_t)parms->info;
289 *((char**)(base + offset))=ap_pstrdup(parms->pool,arg);
293 extern "C" const char* shib_ap_set_file_slot(cmd_parms* parms,
294 #ifdef SHIB_APACHE_13
295 char* arg1, char* arg2
297 void* arg1, const char* arg2
301 ap_set_file_slot(parms, arg1, arg2);
305 extern "C" const char* shib_table_set(cmd_parms* parms, shib_dir_config* dc, const char* arg1, const char* arg2)
308 dc->tSettings = ap_make_table(parms->pool, 4);
309 ap_table_set(dc->tSettings, arg1, arg2);
314 class ShibTargetApache : public AbstractSPRequest
315 #if defined(SHIBSP_HAVE_GSSAPI) && !defined(SHIB_APACHE_13)
320 mutable string m_body;
321 mutable bool m_gotBody,m_firsttime;
322 mutable vector<string> m_certs;
323 set<string> m_allhttp;
327 shib_dir_config* m_dc;
328 shib_server_config* m_sc;
329 shib_request_config* m_rc;
331 ShibTargetApache(request_rec* req, bool handler, bool shib_check_user)
332 : AbstractSPRequest(SHIBSP_LOGCAT".Apache"), m_handler(handler), m_gotBody(false),m_firsttime(true) {
333 m_sc = (shib_server_config*)ap_get_module_config(req->server->module_config, &mod_shib);
334 m_dc = (shib_dir_config*)ap_get_module_config(req->per_dir_config, &mod_shib);
335 m_rc = (shib_request_config*)ap_get_module_config(req->request_config, &mod_shib);
338 setRequestURI(m_req->unparsed_uri);
340 if (shib_check_user && m_dc->bUseHeaders == 1) {
341 // Try and see if this request was already processed, to skip spoof checking.
342 if (!ap_is_initial_req(m_req)) {
345 else if (!g_spoofKey.empty()) {
346 const char* hdr = ap_table_get(m_req->headers_in, "Shib-Spoof-Check");
347 if (hdr && g_spoofKey == hdr)
352 log(SPDebug, "shib_check_user running more than once");
355 virtual ~ShibTargetApache() {}
357 const char* getScheme() const {
358 return m_sc->szScheme ? m_sc->szScheme : ap_http_method(m_req);
360 bool isSecure() const {
361 return HTTPRequest::isSecure();
363 const char* getHostname() const {
364 return ap_get_server_name(m_req);
366 int getPort() const {
367 return ap_get_server_port(m_req);
369 const char* getMethod() const {
370 return m_req->method;
372 string getContentType() const {
373 const char* type = ap_table_get(m_req->headers_in, "Content-Type");
374 return type ? type : "";
376 long getContentLength() const {
377 return m_gotBody ? m_body.length() : m_req->remaining;
379 string getRemoteAddr() const {
380 string ret = AbstractSPRequest::getRemoteAddr();
381 return ret.empty() ? m_req->connection->remote_ip : ret;
383 void log(SPLogLevel level, const string& msg) const {
384 AbstractSPRequest::log(level,msg);
387 (level == SPDebug ? APLOG_DEBUG :
388 (level == SPInfo ? APLOG_INFO :
389 (level == SPWarn ? APLOG_WARNING :
390 (level == SPError ? APLOG_ERR : APLOG_CRIT))))|APLOG_NOERRNO,
396 const char* getQueryString() const { return m_req->args; }
397 const char* getRequestBody() const {
398 if (m_gotBody || m_req->method_number==M_GET)
399 return m_body.c_str();
400 #ifdef SHIB_APACHE_13
401 // Read the posted data
402 if (ap_setup_client_block(m_req, REQUEST_CHUNKED_DECHUNK) != OK) {
404 log(SPError, "Apache function (setup_client_block) failed while reading request body.");
405 return m_body.c_str();
407 if (!ap_should_client_block(m_req)) {
409 log(SPError, "Apache function (should_client_block) failed while reading request body.");
410 return m_body.c_str();
412 if (m_req->remaining > 1024*1024)
413 throw opensaml::SecurityPolicyException("Blocked request body larger than 1M size limit.");
416 char buff[HUGE_STRING_LEN];
417 ap_hard_timeout("[mod_shib] getRequestBody", m_req);
418 while ((len=ap_get_client_block(m_req, buff, sizeof(buff))) > 0) {
419 ap_reset_timeout(m_req);
420 m_body.append(buff, len);
422 ap_kill_timeout(m_req);
427 apr_bucket_brigade* bb = apr_brigade_create(m_req->pool, m_req->connection->bucket_alloc);
430 apr_status_t rv = ap_get_brigade(m_req->input_filters, bb, AP_MODE_READBYTES, APR_BLOCK_READ, HUGE_STRING_LEN);
431 if (rv != APR_SUCCESS) {
432 log(SPError, "Apache function (ap_get_brigade) failed while reading request body.");
436 for (bucket = APR_BRIGADE_FIRST(bb); bucket != APR_BRIGADE_SENTINEL(bb); bucket = APR_BUCKET_NEXT(bucket)) {
437 if (APR_BUCKET_IS_EOS(bucket)) {
442 /* We can't do much with this. */
443 if (APR_BUCKET_IS_FLUSH(bucket))
447 apr_bucket_read(bucket, &data, &len, APR_BLOCK_READ);
449 m_body.append(data, len);
451 apr_brigade_cleanup(bb);
453 apr_brigade_destroy(bb);
456 return m_body.c_str();
458 const char* getParameter(const char* name) const {
459 return AbstractSPRequest::getParameter(name);
461 vector<const char*>::size_type getParameters(const char* name, vector<const char*>& values) const {
462 return AbstractSPRequest::getParameters(name, values);
464 void clearHeader(const char* rawname, const char* cginame) {
465 if (m_dc->bUseHeaders == 1) {
466 // ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_clear_header: hdr\n");
467 if (g_checkSpoofing && m_firsttime) {
468 if (m_allhttp.empty()) {
469 // First time, so populate set with "CGI" versions of client-supplied headers.
470 #ifdef SHIB_APACHE_13
471 array_header *hdrs_arr = ap_table_elts(m_req->headers_in);
472 table_entry *hdrs = (table_entry *) hdrs_arr->elts;
474 const apr_array_header_t *hdrs_arr = apr_table_elts(m_req->headers_in);
475 const apr_table_entry_t *hdrs = (const apr_table_entry_t *) hdrs_arr->elts;
477 for (int i = 0; i < hdrs_arr->nelts; ++i) {
480 string cgiversion("HTTP_");
481 const char* pch = hdrs[i].key;
483 cgiversion += (isalnum(*pch) ? toupper(*pch) : '_');
486 m_allhttp.insert(cgiversion);
490 if (m_allhttp.count(cginame) > 0)
491 throw opensaml::SecurityPolicyException("Attempt to spoof header ($1) was detected.", params(1, rawname));
493 ap_table_unset(m_req->headers_in, rawname);
494 ap_table_set(m_req->headers_in, rawname, g_unsetHeaderValue.c_str());
497 void setHeader(const char* name, const char* value) {
498 if (m_dc->bUseEnvVars != 0) {
500 // this happens on subrequests
501 // ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_setheader: no_m_rc\n");
502 m_rc = init_request_config(m_req);
505 m_rc->env = ap_make_table(m_req->pool, 10);
506 // ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_set_env: %s=%s\n", name, value?value:"Null");
507 ap_table_set(m_rc->env, name, value ? value : "");
509 if (m_dc->bUseHeaders == 1)
510 ap_table_set(m_req->headers_in, name, value);
512 string getHeader(const char* name) const {
513 const char* hdr = ap_table_get(m_req->headers_in, name);
514 return string(hdr ? hdr : "");
516 string getSecureHeader(const char* name) const {
517 if (m_dc->bUseEnvVars != 0) {
519 if (m_rc && m_rc->env)
520 hdr = ap_table_get(m_rc->env, name);
523 return string(hdr ? hdr : "");
525 return getHeader(name);
527 void setRemoteUser(const char* user) {
528 SH_AP_USER(m_req) = user ? ap_pstrdup(m_req->pool, user) : nullptr;
529 if (m_dc->bUseHeaders == 1) {
531 ap_table_set(m_req->headers_in, "REMOTE_USER", user);
534 ap_table_unset(m_req->headers_in, "REMOTE_USER");
535 ap_table_set(m_req->headers_in, "REMOTE_USER", g_unsetHeaderValue.c_str());
539 string getRemoteUser() const {
540 return string(SH_AP_USER(m_req) ? SH_AP_USER(m_req) : "");
542 void setAuthType(const char* authtype) {
543 if (authtype && m_dc->bBasicHijack == 1)
545 SH_AP_AUTH_TYPE(m_req) = authtype ? ap_pstrdup(m_req->pool, authtype) : nullptr;
547 string getAuthType() const {
548 return string(SH_AP_AUTH_TYPE(m_req) ? SH_AP_AUTH_TYPE(m_req) : "");
550 void setContentType(const char* type) {
551 m_req->content_type = ap_psprintf(m_req->pool, "%s", type);
553 void setResponseHeader(const char* name, const char* value) {
554 HTTPResponse::setResponseHeader(name, value);
555 #ifdef SHIB_DEFERRED_HEADERS
557 // this happens on subrequests
558 m_rc = init_request_config(m_req);
561 m_rc->hdr_out = ap_make_table(m_req->pool, 5);
562 ap_table_add(m_rc->hdr_out, name, value);
566 ap_table_add(m_req->err_headers_out, name, value);
568 long sendResponse(istream& in, long status) {
569 if (status != XMLTOOLING_HTTP_STATUS_OK)
570 m_req->status = status;
571 ap_send_http_header(m_req);
575 ap_rwrite(buf,in.gcount(),m_req);
577 #if (defined(SHIB_APACHE_20) || defined(SHIB_APACHE_22))
578 if (status != XMLTOOLING_HTTP_STATUS_OK && status != XMLTOOLING_HTTP_STATUS_ERROR)
583 long sendRedirect(const char* url) {
584 HTTPResponse::sendRedirect(url);
585 ap_table_set(m_req->headers_out, "Location", url);
588 const vector<string>& getClientCertificates() const {
589 if (m_certs.empty()) {
590 const char* cert = ap_table_get(m_req->subprocess_env, "SSL_CLIENT_CERT");
592 m_certs.push_back(cert);
595 cert = ap_table_get(m_req->subprocess_env, ap_psprintf(m_req->pool, "SSL_CLIENT_CERT_CHAIN_%d", i++));
597 m_certs.push_back(cert);
602 long returnDecline(void) { return DECLINED; }
603 long returnOK(void) { return OK; }
604 #if defined(SHIBSP_HAVE_GSSAPI) && !defined(SHIB_APACHE_13)
605 gss_ctx_id_t getGSSContext() const {
606 gss_ctx_id_t ctx = GSS_C_NO_CONTEXT;
607 apr_pool_userdata_get((void**)&ctx, g_szGSSContextKey, m_req->pool);
613 /********************************************************************************/
616 extern "C" int shib_check_user(request_rec* r)
618 // Short-circuit entirely?
619 if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
622 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_check_user(%d): ENTER", (int)getpid());
624 ostringstream threadid;
625 threadid << "[" << getpid() << "] shib_check_user" << '\0';
626 xmltooling::NDC ndc(threadid.str().c_str());
629 ShibTargetApache sta(r,false,true);
631 // Check user authentication and export information, then set the handler bypass
632 pair<bool,long> res = sta.getServiceProvider().doAuthentication(sta,true);
633 apr_pool_userdata_setn((const void*)42,g_UserDataKey,nullptr,r->pool);
634 // If directed, install a spoof key to recognize when we've already cleared headers.
635 if (!g_spoofKey.empty() && (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bUseHeaders==1))
636 ap_table_set(r->headers_in, "Shib-Spoof-Check", g_spoofKey.c_str());
637 if (res.first) return res.second;
639 // user auth was okay -- export the assertions now
640 res = sta.getServiceProvider().doExport(sta);
641 if (res.first) return res.second;
643 // export happened successfully.. this user is ok.
646 catch (exception& e) {
647 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user threw an exception: %s", e.what());
651 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user threw an unknown exception!");
658 extern "C" int shib_handler(request_rec* r)
660 // Short-circuit entirely?
661 if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
664 ostringstream threadid;
665 threadid << "[" << getpid() << "] shib_handler" << '\0';
666 xmltooling::NDC ndc(threadid.str().c_str());
668 #ifndef SHIB_APACHE_13
669 // With 2.x, this handler always runs, though last.
670 // We check if shib_check_user ran, because it will detect a handler request
671 // and dispatch it directly.
673 apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
674 if (data==(const void*)42) {
675 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler skipped since check_user ran");
680 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler(%d): ENTER: %s", (int)getpid(), r->handler);
683 ShibTargetApache sta(r,true,false);
685 pair<bool,long> res = sta.getServiceProvider().doHandler(sta);
686 if (res.first) return res.second;
688 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "doHandler() did not do anything.");
691 catch (exception& e) {
692 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler threw an exception: %s", e.what());
696 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler threw an unknown exception!");
704 * shib_auth_checker() -- a simple resource manager to
705 * process the .htaccess settings
707 extern "C" int shib_auth_checker(request_rec* r)
709 // Short-circuit entirely?
710 if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
713 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_auth_checker(%d): ENTER", (int)getpid());
715 ostringstream threadid;
716 threadid << "[" << getpid() << "] shib_auth_checker" << '\0';
717 xmltooling::NDC ndc(threadid.str().c_str());
720 ShibTargetApache sta(r,false,false);
722 pair<bool,long> res = sta.getServiceProvider().doAuthorization(sta);
723 if (res.first) return res.second;
725 // The SP method should always return true, so if we get this far, something unusual happened.
726 // Just let Apache (or some other module) decide what to do.
729 catch (exception& e) {
730 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an exception: %s", e.what());
734 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an unknown exception!");
741 // Access control plugin that enforces htaccess rules
742 class htAccessControl : virtual public AccessControl
746 ~htAccessControl() {}
747 Lockable* lock() {return this;}
749 aclresult_t authorized(const SPRequest& request, const Session* session) const;
751 bool checkAttribute(const SPRequest& request, const Attribute* attr, const char* toMatch, RegularExpression* re) const;
754 AccessControl* htAccessFactory(const xercesc::DOMElement* const & e)
756 return new htAccessControl();
759 class ApacheRequestMapper : public virtual RequestMapper, public virtual PropertySet
762 ApacheRequestMapper(const xercesc::DOMElement* e);
763 ~ApacheRequestMapper() { delete m_mapper; delete m_htaccess; delete m_staKey; delete m_propsKey; }
764 Lockable* lock() { return m_mapper->lock(); }
765 void unlock() { m_staKey->setData(nullptr); m_propsKey->setData(nullptr); m_mapper->unlock(); }
766 Settings getSettings(const HTTPRequest& request) const;
768 const PropertySet* getParent() const { return nullptr; }
769 void setParent(const PropertySet*) {}
770 pair<bool,bool> getBool(const char* name, const char* ns=nullptr) const;
771 pair<bool,const char*> getString(const char* name, const char* ns=nullptr) const;
772 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=nullptr) const;
773 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=nullptr) const;
774 pair<bool,int> getInt(const char* name, const char* ns=nullptr) const;
775 void getAll(map<string,const char*>& properties) const;
776 const PropertySet* getPropertySet(const char* name, const char* ns=shibspconstants::ASCII_SHIB2SPCONFIG_NS) const;
777 const xercesc::DOMElement* getElement() const;
780 RequestMapper* m_mapper;
782 ThreadKey* m_propsKey;
783 AccessControl* m_htaccess;
786 RequestMapper* ApacheRequestMapFactory(const xercesc::DOMElement* const & e)
788 return new ApacheRequestMapper(e);
791 ApacheRequestMapper::ApacheRequestMapper(const xercesc::DOMElement* e) : m_mapper(nullptr), m_staKey(nullptr), m_propsKey(nullptr), m_htaccess(nullptr)
793 m_mapper=SPConfig::getConfig().RequestMapperManager.newPlugin(XML_REQUEST_MAPPER,e);
794 m_htaccess=new htAccessControl();
795 m_staKey=ThreadKey::create(nullptr);
796 m_propsKey=ThreadKey::create(nullptr);
799 RequestMapper::Settings ApacheRequestMapper::getSettings(const HTTPRequest& request) const
801 Settings s=m_mapper->getSettings(request);
802 m_staKey->setData((void*)dynamic_cast<const ShibTargetApache*>(&request));
803 m_propsKey->setData((void*)s.first);
804 return pair<const PropertySet*,AccessControl*>(this,s.second ? s.second : m_htaccess);
807 pair<bool,bool> ApacheRequestMapper::getBool(const char* name, const char* ns) const
809 const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
810 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
812 // Override Apache-settable boolean properties.
813 if (name && !strcmp(name,"requireSession") && sta->m_dc->bRequireSession != -1)
814 return make_pair(true, sta->m_dc->bRequireSession==1);
815 else if (name && !strcmp(name,"exportAssertion") && sta->m_dc->bExportAssertion != -1)
816 return make_pair(true, sta->m_dc->bExportAssertion==1);
817 else if (sta->m_dc->tSettings) {
818 const char* prop = ap_table_get(sta->m_dc->tSettings, name);
820 return make_pair(true, !strcmp(prop, "true") || !strcmp(prop, "1") || !strcmp(prop, "On"));
823 return s ? s->getBool(name,ns) : make_pair(false,false);
826 pair<bool,const char*> ApacheRequestMapper::getString(const char* name, const char* ns) const
828 const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
829 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
831 // Override Apache-settable string properties.
832 if (name && !strcmp(name,"authType")) {
833 const char *auth_type=ap_auth_type(sta->m_req);
835 // Check for Basic Hijack
836 if (!strcasecmp(auth_type, "basic") && sta->m_dc->bBasicHijack == 1)
837 auth_type = "shibboleth";
838 return make_pair(true,auth_type);
841 else if (name && !strcmp(name,"applicationId") && sta->m_dc->szApplicationId)
842 return pair<bool,const char*>(true,sta->m_dc->szApplicationId);
843 else if (name && !strcmp(name,"requireSessionWith") && sta->m_dc->szRequireWith)
844 return pair<bool,const char*>(true,sta->m_dc->szRequireWith);
845 else if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
846 return pair<bool,const char*>(true,sta->m_dc->szRedirectToSSL);
847 else if (sta->m_dc->tSettings) {
848 const char* prop = ap_table_get(sta->m_dc->tSettings, name);
850 return make_pair(true, prop);
853 return s ? s->getString(name,ns) : pair<bool,const char*>(false,nullptr);
856 pair<bool,const XMLCh*> ApacheRequestMapper::getXMLString(const char* name, const char* ns) const
858 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
859 return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,nullptr);
862 pair<bool,unsigned int> ApacheRequestMapper::getUnsignedInt(const char* name, const char* ns) const
864 const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
865 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
867 // Override Apache-settable int properties.
868 if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
869 return pair<bool,unsigned int>(true, strtol(sta->m_dc->szRedirectToSSL, nullptr, 10));
870 else if (sta->m_dc->tSettings) {
871 const char* prop = ap_table_get(sta->m_dc->tSettings, name);
873 return pair<bool,unsigned int>(true, atoi(prop));
876 return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
879 pair<bool,int> ApacheRequestMapper::getInt(const char* name, const char* ns) const
881 const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
882 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
884 // Override Apache-settable int properties.
885 if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
886 return pair<bool,int>(true,atoi(sta->m_dc->szRedirectToSSL));
887 else if (sta->m_dc->tSettings) {
888 const char* prop = ap_table_get(sta->m_dc->tSettings, name);
890 return make_pair(true, atoi(prop));
893 return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
896 static int _rm_get_all_table_walk(void *v, const char *key, const char *value)
898 reinterpret_cast<map<string,const char*>*>(v)->insert(pair<string,const char*>(key, value));
902 void ApacheRequestMapper::getAll(map<string,const char*>& properties) const
904 const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
905 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
908 s->getAll(properties);
912 const char* auth_type=ap_auth_type(sta->m_req);
914 // Check for Basic Hijack
915 if (!strcasecmp(auth_type, "basic") && sta->m_dc->bBasicHijack == 1)
916 auth_type = "shibboleth";
917 properties["authType"] = auth_type;
920 if (sta->m_dc->szApplicationId)
921 properties["applicationId"] = sta->m_dc->szApplicationId;
922 if (sta->m_dc->szRequireWith)
923 properties["requireSessionWith"] = sta->m_dc->szRequireWith;
924 if (sta->m_dc->szRedirectToSSL)
925 properties["redirectToSSL"] = sta->m_dc->szRedirectToSSL;
926 if (sta->m_dc->bRequireSession != 0)
927 properties["requireSession"] = (sta->m_dc->bRequireSession==1) ? "true" : "false";
928 if (sta->m_dc->bExportAssertion != 0)
929 properties["exportAssertion"] = (sta->m_dc->bExportAssertion==1) ? "true" : "false";
931 if (sta->m_dc->tSettings)
932 ap_table_do(_rm_get_all_table_walk, &properties, sta->m_dc->tSettings, NULL);
935 const PropertySet* ApacheRequestMapper::getPropertySet(const char* name, const char* ns) const
937 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
938 return s ? s->getPropertySet(name,ns) : nullptr;
941 const xercesc::DOMElement* ApacheRequestMapper::getElement() const
943 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
944 return s ? s->getElement() : nullptr;
947 static SH_AP_TABLE* groups_for_user(request_rec* r, const char* user, char* grpfile)
950 SH_AP_TABLE* grps=ap_make_table(r->pool,15);
951 char l[MAX_STRING_LEN];
952 const char *group_name, *ll, *w;
954 #ifdef SHIB_APACHE_13
955 if (!(f=ap_pcfg_openfile(r->pool,grpfile))) {
957 if (ap_pcfg_openfile(&f,r->pool,grpfile) != APR_SUCCESS) {
959 ap_log_rerror(APLOG_MARK,APLOG_DEBUG,SH_AP_R(r),"groups_for_user() could not open group file: %s\n",grpfile);
964 #ifdef SHIB_APACHE_13
965 sp=ap_make_sub_pool(r->pool);
967 if (apr_pool_create(&sp,r->pool) != APR_SUCCESS) {
968 ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,
969 "groups_for_user() could not create a subpool");
974 while (!(ap_cfg_getline(l,MAX_STRING_LEN,f))) {
975 if ((*l=='#') || (!*l))
980 group_name=ap_getword(sp,&ll,':');
983 w=ap_getword_conf(sp,&ll);
984 if (!strcmp(w,user)) {
985 ap_table_setn(grps,ap_pstrdup(r->pool,group_name),"in");
995 bool htAccessControl::checkAttribute(const SPRequest& request, const Attribute* attr, const char* toMatch, RegularExpression* re) const
997 bool caseSensitive = attr->isCaseSensitive();
998 const vector<string>& vals = attr->getSerializedValues();
999 for (vector<string>::const_iterator v=vals.begin(); v!=vals.end(); ++v) {
1001 auto_arrayptr<XMLCh> trans(fromUTF8(v->c_str()));
1002 if (re->matches(trans.get())) {
1003 if (request.isPriorityEnabled(SPRequest::SPDebug))
1004 request.log(SPRequest::SPDebug, string("htaccess: expecting regexp ") + toMatch + ", got " + *v + ": acccepted");
1008 else if ((caseSensitive && *v == toMatch) || (!caseSensitive && !strcasecmp(v->c_str(), toMatch))) {
1009 if (request.isPriorityEnabled(SPRequest::SPDebug))
1010 request.log(SPRequest::SPDebug, string("htaccess: expecting ") + toMatch + ", got " + *v + ": accepted");
1013 else if (request.isPriorityEnabled(SPRequest::SPDebug)) {
1014 request.log(SPRequest::SPDebug, string("htaccess: expecting ") + toMatch + ", got " + *v + ": rejected");
1020 AccessControl::aclresult_t htAccessControl::authorized(const SPRequest& request, const Session* session) const
1022 // Make sure the object is our type.
1023 const ShibTargetApache* sta=dynamic_cast<const ShibTargetApache*>(&request);
1025 throw ConfigurationException("Request wrapper object was not of correct type.");
1027 int m=sta->m_req->method_number;
1028 bool method_restricted=false;
1031 const array_header* reqs_arr=ap_requires(sta->m_req);
1033 return shib_acl_indeterminate; // should never happen
1035 // Check for an "embedded" AccessControl plugin.
1036 if (sta->m_dc->szAccessControl) {
1037 aclresult_t result = shib_acl_false;
1039 ifstream aclfile(sta->m_dc->szAccessControl);
1040 xercesc::DOMDocument* acldoc = XMLToolingConfig::getConfig().getParser().parse(aclfile);
1041 XercesJanitor<xercesc::DOMDocument> docjanitor(acldoc);
1042 static XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
1043 string t(XMLHelper::getAttrString(acldoc ? acldoc->getDocumentElement() : nullptr, nullptr, _type));
1045 throw ConfigurationException("Missing type attribute in AccessControl plugin configuration.");
1046 auto_ptr<AccessControl> aclplugin(SPConfig::getConfig().AccessControlManager.newPlugin(t.c_str(), acldoc->getDocumentElement()));
1047 Locker acllock(aclplugin.get());
1048 result = aclplugin->authorized(request, session);
1050 catch (exception& ex) {
1051 request.log(SPRequest::SPError, ex.what());
1054 if (result == shib_acl_true && sta->m_dc->bRequireAll != 1) {
1055 // If we're not insisting that all rules be met, then we're done.
1056 request.log(SPRequest::SPDebug, "htaccess: embedded AccessControl plugin was successful, granting access");
1057 return shib_acl_true;
1059 else if (result != shib_acl_true && sta->m_dc->bRequireAll == 1) {
1060 // If we're insisting that all rules be met, which is not something Apache really handles well,
1061 // then we either return false or indeterminate based on the authoritative option, which defaults on.
1062 if (sta->m_dc->bAuthoritative != 0) {
1063 request.log(SPRequest::SPDebug, "htaccess: embedded AccessControl plugin was unsuccessful, denying access");
1064 return shib_acl_false;
1067 request.log(SPRequest::SPDebug, "htaccess: embedded AccessControl plugin was unsuccessful but not authoritative, leaving it up to Apache");
1068 return shib_acl_indeterminate;
1073 require_line* reqs=(require_line*)reqs_arr->elts;
1075 for (int x=0; x<reqs_arr->nelts; x++) {
1076 // This rule should be completely ignored, the method doesn't fit.
1077 // The rule just doesn't exist for our purposes.
1078 if (!(reqs[x].method_mask & (1 << m)))
1081 method_restricted=true; // this lets us know at the end that at least one rule was potentially enforcable.
1083 // Tracks status of this rule's evaluation.
1084 bool status = false;
1086 string remote_user = request.getRemoteUser();
1088 t = reqs[x].requirement;
1089 w = ap_getword_white(sta->m_req->pool, &t);
1091 if (!strcasecmp(w,"shibboleth")) {
1092 // This is a dummy rule needed because Apache conflates authn and authz.
1093 // Without some require rule, AuthType is ignored and no check_user hooks run.
1095 // We evaluate to false if ShibAccessControl is used and ShibRequireAll is off.
1096 // This allows actual rules to dictate the result, since ShibAccessControl returned
1097 // non-true, and if nothing else is used, access will be denied.
1098 if (!sta->m_dc->szAccessControl || sta->m_dc->bRequireAll == 1) {
1099 // We evaluate to true, because ShibRequireAll is enabled (so a true is just a no-op)
1100 // or because there was no other AccessControl rule in place, so this may be the only
1105 else if (!strcmp(w,"valid-user") && session) {
1106 request.log(SPRequest::SPDebug, "htaccess: accepting valid-user based on active session");
1109 else if (!strcmp(w,"user") && !remote_user.empty()) {
1110 bool regexp = false;
1112 w = ap_getword_conf(sta->m_req->pool,&t);
1117 else if (*w == '!') {
1118 // A negated rule presumes success unless a match is found.
1125 // Figure out if there's a match.
1129 // To do regex matching, we have to convert from UTF-8.
1130 auto_arrayptr<XMLCh> trans(fromUTF8(w));
1131 RegularExpression re(trans.get());
1132 auto_arrayptr<XMLCh> trans2(fromUTF8(remote_user.c_str()));
1133 match = re.matches(trans2.get());
1135 catch (XMLException& ex) {
1136 auto_ptr_char tmp(ex.getMessage());
1137 request.log(SPRequest::SPError,
1138 string("htaccess plugin caught exception while parsing regular expression (") + w + "): " + tmp.get());
1141 else if (remote_user == w) {
1146 // If we matched, then we're done with this rule either way and we flip status to reflect the outcome.
1148 if (request.isPriorityEnabled(SPRequest::SPDebug))
1149 request.log(SPRequest::SPDebug,
1150 string("htaccess: require user ") + (!status ? "rejecting (" : "accepting (") + remote_user + ")");
1155 else if (!strcmp(w,"group") && !remote_user.empty()) {
1156 SH_AP_TABLE* grpstatus = nullptr;
1157 if (sta->m_dc->szAuthGrpFile) {
1158 if (request.isPriorityEnabled(SPRequest::SPDebug))
1159 request.log(SPRequest::SPDebug,string("htaccess plugin using groups file: ") + sta->m_dc->szAuthGrpFile);
1160 grpstatus = groups_for_user(sta->m_req,remote_user.c_str(),sta->m_dc->szAuthGrpFile);
1164 w = ap_getword_conf(sta->m_req->pool,&t);
1166 // A negated rule presumes success unless a match is found.
1171 if (grpstatus && ap_table_get(grpstatus,w)) {
1172 // If we matched, then we're done with this rule either way and we flip status to reflect the outcome.
1174 request.log(SPRequest::SPDebug, string("htaccess: require group ") + (!status ? "rejecting (" : "accepting (") + w + ")");
1179 else if (!strcmp(w,"authnContextClassRef") || !strcmp(w,"authnContextDeclRef")) {
1180 const char* ref = !strcmp(w,"authnContextClassRef") ? session->getAuthnContextClassRef() : session->getAuthnContextDeclRef();
1182 bool regexp = false;
1184 w = ap_getword_conf(sta->m_req->pool,&t);
1189 else if (*w == '!') {
1190 // A negated rule presumes success unless a match is found.
1197 // Figure out if there's a match.
1201 // To do regex matching, we have to convert from UTF-8.
1202 RegularExpression re(w);
1203 match = re.matches(ref);
1205 catch (XMLException& ex) {
1206 auto_ptr_char tmp(ex.getMessage());
1207 request.log(SPRequest::SPError,
1208 string("htaccess plugin caught exception while parsing regular expression (") + w + "): " + tmp.get());
1211 else if (!strcmp(w,ref)) {
1216 // If we matched, then we're done with this rule either way and we flip status to reflect the outcome.
1218 if (request.isPriorityEnabled(SPRequest::SPDebug))
1219 request.log(SPRequest::SPDebug,
1220 string("htaccess: require authnContext ") + (!status ? "rejecting (" : "accepting (") + ref + ")");
1225 else if (request.isPriorityEnabled(SPRequest::SPDebug)) {
1226 request.log(SPRequest::SPDebug, "htaccess: require authnContext rejecting session with no context associated");
1229 else if (!session) {
1230 request.log(SPRequest::SPError, string("htaccess: require ") + w + " not given a valid session, are you using lazy sessions?");
1233 // Find the attribute(s) matching the require rule.
1234 pair<multimap<string,const Attribute*>::const_iterator,multimap<string,const Attribute*>::const_iterator> attrs =
1235 session->getIndexedAttributes().equal_range(w);
1238 while (!status && attrs.first!=attrs.second && *t) {
1239 w=ap_getword_conf(sta->m_req->pool,&t);
1246 auto_ptr<RegularExpression> re;
1248 delete re.release();
1249 auto_arrayptr<XMLCh> trans(fromUTF8(w));
1250 auto_ptr<xercesc::RegularExpression> temp(new xercesc::RegularExpression(trans.get()));
1254 pair<multimap<string,const Attribute*>::const_iterator,multimap<string,const Attribute*>::const_iterator> attrs2(attrs);
1255 for (; !status && attrs2.first!=attrs2.second; ++attrs2.first) {
1256 if (checkAttribute(request, attrs2.first->second, w, regexp ? re.get() : nullptr)) {
1261 catch (XMLException& ex) {
1262 auto_ptr_char tmp(ex.getMessage());
1263 request.log(SPRequest::SPError,
1264 string("htaccess plugin caught exception while parsing regular expression (") + w + "): " + tmp.get()
1270 // If status is false, we found a rule we couldn't satisfy.
1271 // Could be an unknown rule to us, or it just didn't match.
1273 if (status && sta->m_dc->bRequireAll != 1) {
1274 // If we're not insisting that all rules be met, then we're done.
1275 request.log(SPRequest::SPDebug, "htaccess: a rule was successful, granting access");
1276 return shib_acl_true;
1278 else if (!status && sta->m_dc->bRequireAll == 1) {
1279 // If we're insisting that all rules be met, which is not something Apache really handles well,
1280 // then we either return false or indeterminate based on the authoritative option, which defaults on.
1281 if (sta->m_dc->bAuthoritative != 0) {
1282 request.log(SPRequest::SPDebug, "htaccess: a rule was unsuccessful, denying access");
1283 return shib_acl_false;
1286 request.log(SPRequest::SPDebug, "htaccess: a rule was unsuccessful but not authoritative, leaving it up to Apache");
1287 return shib_acl_indeterminate;
1290 // Otherwise, we keep going. If we're requring all, then we have to check every rule.
1291 // If not we just didn't find a successful rule yet, so we keep going anyway.
1294 // If we get here, we either "failed" or we're in require all mode (but not both).
1295 // If no rules possibly apply or we insisted that all rules check out, then we're good.
1296 if (!method_restricted) {
1297 request.log(SPRequest::SPDebug, "htaccess: no rules applied to this request method, granting access");
1298 return shib_acl_true;
1300 else if (sta->m_dc->bRequireAll == 1) {
1301 request.log(SPRequest::SPDebug, "htaccess: all rules successful, granting access");
1302 return shib_acl_true;
1304 else if (sta->m_dc->bAuthoritative != 0) {
1305 request.log(SPRequest::SPDebug, "htaccess: no rules were successful, denying access");
1306 return shib_acl_false;
1309 request.log(SPRequest::SPDebug, "htaccess: no rules were successful but not authoritative, leaving it up to Apache");
1310 return shib_acl_indeterminate;
1314 // Initial look at a request - create the per-request structure
1315 static int shib_post_read(request_rec *r)
1317 init_request_config(r);
1318 //ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_post_read");
1322 // fixups: set environment vars
1324 extern "C" int shib_fixups(request_rec* r)
1326 shib_request_config *rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
1327 shib_dir_config *dc = (shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib);
1328 if (dc->bOff==1 || dc->bUseEnvVars==0)
1331 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_fixup(%d): ENTER", (int)getpid());
1333 if (rc==nullptr || rc->env==nullptr || ap_is_empty_table(rc->env))
1336 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_fixup adding %d vars", ap_table_elts(rc->env)->nelts);
1337 r->subprocess_env = ap_overlay_tables(r->pool, r->subprocess_env, rc->env);
1342 #ifdef SHIB_APACHE_13
1345 * Cleanup the (per-process) pool info.
1347 extern "C" void shib_child_exit(server_rec* s, SH_AP_POOL* p)
1350 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit(%d) dealing with g_Config..", (int)getpid());
1353 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit() done");
1359 * Apache 2.x doesn't allow for per-child cleanup, causes CGI forks to hang.
1361 extern "C" apr_status_t shib_exit(void* data)
1367 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,0,nullptr,"shib_exit() done");
1373 * shire_child_init()
1374 * Things to do when the child process is initialized.
1375 * (or after the configs are read in apache-2)
1377 #ifdef SHIB_APACHE_13
1378 extern "C" void shib_child_init(server_rec* s, SH_AP_POOL* p)
1380 extern "C" void shib_child_init(apr_pool_t* p, server_rec* s)
1383 // Initialize runtime components.
1385 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init(%d) starting", (int)getpid());
1388 ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() already initialized!");
1392 g_Config=&SPConfig::getConfig();
1393 g_Config->setFeatures(
1394 SPConfig::Listener |
1396 SPConfig::RequestMapping |
1397 SPConfig::InProcess |
1401 if (!g_Config->init(g_szSchemaDir, g_szPrefix)) {
1402 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize libraries");
1405 g_Config->AccessControlManager.registerFactory(HT_ACCESS_CONTROL,&htAccessFactory);
1406 g_Config->RequestMapperManager.registerFactory(NATIVE_REQUEST_MAPPER,&ApacheRequestMapFactory);
1409 if (!g_Config->instantiate(g_szSHIBConfig, true))
1410 throw runtime_error("unknown error");
1412 catch (exception& ex) {
1413 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"%s",ex.what());
1414 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to load configuration");
1418 ServiceProvider* sp=g_Config->getServiceProvider();
1419 xmltooling::Locker locker(sp);
1420 const PropertySet* props=sp->getPropertySet("InProcess");
1422 pair<bool,const char*> unsetValue=props->getString("unsetHeaderValue");
1423 if (unsetValue.first)
1424 g_unsetHeaderValue = unsetValue.second;
1425 pair<bool,bool> flag=props->getBool("checkSpoofing");
1426 g_checkSpoofing = !flag.first || flag.second;
1427 if (g_checkSpoofing) {
1428 unsetValue=props->getString("spoofKey");
1429 if (unsetValue.first)
1430 g_spoofKey = unsetValue.second;
1432 flag=props->getBool("catchAll");
1433 g_catchAll = flag.first && flag.second;
1436 // Set the cleanup handler
1437 apr_pool_cleanup_register(p, nullptr, &shib_exit, apr_pool_cleanup_null);
1439 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() done");
1443 #ifdef SHIB_DEFERRED_HEADERS
1444 static void set_output_filter(request_rec *r)
1446 ap_add_output_filter("SHIB_HEADERS_OUT", nullptr, r, r->connection);
1449 static void set_error_filter(request_rec *r)
1451 ap_add_output_filter("SHIB_HEADERS_ERR", nullptr, r, r->connection);
1454 static int _table_add(void *v, const char *key, const char *value)
1456 apr_table_addn((apr_table_t*)v, key, value);
1460 static apr_status_t do_output_filter(ap_filter_t *f, apr_bucket_brigade *in)
1462 request_rec *r = f->r;
1463 shib_request_config *rc = (shib_request_config*) ap_get_module_config(r->request_config, &mod_shib);
1465 if (rc && rc->hdr_out) {
1466 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);
1467 // can't use overlap call because it will collapse Set-Cookie headers
1468 //apr_table_overlap(r->headers_out, rc->hdr_out, APR_OVERLAP_TABLES_MERGE);
1469 apr_table_do(_table_add,r->headers_out, rc->hdr_out,NULL);
1472 /* remove ourselves from the filter chain */
1473 ap_remove_output_filter(f);
1475 /* send the data up the stack */
1476 return ap_pass_brigade(f->next,in);
1479 static apr_status_t do_error_filter(ap_filter_t *f, apr_bucket_brigade *in)
1481 request_rec *r = f->r;
1482 shib_request_config *rc = (shib_request_config*) ap_get_module_config(r->request_config, &mod_shib);
1484 if (rc && rc->hdr_out) {
1485 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);
1486 // can't use overlap call because it will collapse Set-Cookie headers
1487 //apr_table_overlap(r->err_headers_out, rc->hdr_out, APR_OVERLAP_TABLES_MERGE);
1488 apr_table_do(_table_add,r->err_headers_out, rc->hdr_out,NULL);
1491 /* remove ourselves from the filter chain */
1492 ap_remove_output_filter(f);
1494 /* send the data up the stack */
1495 return ap_pass_brigade(f->next,in);
1497 #endif // SHIB_DEFERRED_HEADERS
1499 typedef const char* (*config_fn_t)(void);
1501 #ifdef SHIB_APACHE_13
1503 // SHIB Module commands
1505 static command_rec shire_cmds[] = {
1506 {"ShibPrefix", (config_fn_t)ap_set_global_string_slot, &g_szPrefix,
1507 RSRC_CONF, TAKE1, "Shibboleth installation directory"},
1508 {"ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1509 RSRC_CONF, TAKE1, "Path to shibboleth2.xml config file"},
1510 {"ShibCatalogs", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1511 RSRC_CONF, TAKE1, "Paths of XML schema catalogs"},
1513 {"ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
1514 (void *) XtOffsetOf (shib_server_config, szScheme),
1515 RSRC_CONF, TAKE1, "URL scheme to force into generated URLs for a vhost"},
1517 {"ShibRequestSetting", (config_fn_t)shib_table_set, nullptr,
1518 OR_AUTHCFG, TAKE2, "Set arbitrary Shibboleth request property for content"},
1520 {"ShibAccessControl", (config_fn_t)ap_set_string_slot,
1521 (void *) XtOffsetOf (shib_dir_config, szAccessControl),
1522 OR_AUTHCFG, TAKE1, "Set arbitrary Shibboleth access control plugin for content"},
1524 {"ShibDisable", (config_fn_t)ap_set_flag_slot,
1525 (void *) XtOffsetOf (shib_dir_config, bOff),
1526 OR_AUTHCFG, FLAG, "Disable all Shib module activity here to save processing effort"},
1527 {"ShibApplicationId", (config_fn_t)ap_set_string_slot,
1528 (void *) XtOffsetOf (shib_dir_config, szApplicationId),
1529 OR_AUTHCFG, TAKE1, "Set Shibboleth applicationId property for content"},
1530 {"ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1531 (void *) XtOffsetOf (shib_dir_config, bBasicHijack),
1532 OR_AUTHCFG, FLAG, "(DEPRECATED) Respond to AuthType Basic and convert to shibboleth"},
1533 {"ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1534 (void *) XtOffsetOf (shib_dir_config, bRequireSession),
1535 OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist"},
1536 {"ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
1537 (void *) XtOffsetOf (shib_dir_config, szRequireWith),
1538 OR_AUTHCFG, TAKE1, "Initiates a new session if one does not exist using a specific SessionInitiator"},
1539 {"ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1540 (void *) XtOffsetOf (shib_dir_config, bExportAssertion),
1541 OR_AUTHCFG, FLAG, "Export SAML attribute assertion(s) to Shib-Attributes header"},
1542 {"ShibRedirectToSSL", (config_fn_t)ap_set_string_slot,
1543 (void *) XtOffsetOf (shib_dir_config, szRedirectToSSL),
1544 OR_AUTHCFG, TAKE1, "Redirect non-SSL requests to designated port" },
1545 {"AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
1546 (void *) XtOffsetOf (shib_dir_config, szAuthGrpFile),
1547 OR_AUTHCFG, TAKE1, "text file containing group names and member user IDs"},
1548 {"ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1549 (void *) XtOffsetOf (shib_dir_config, bRequireAll),
1550 OR_AUTHCFG, FLAG, "All require directives must match"},
1551 {"AuthzShibAuthoritative", (config_fn_t)ap_set_flag_slot,
1552 (void *) XtOffsetOf (shib_dir_config, bAuthoritative),
1553 OR_AUTHCFG, FLAG, "Allow failed mod_shib htaccess authorization to fall through to other modules"},
1554 {"ShibUseEnvironment", (config_fn_t)ap_set_flag_slot,
1555 (void *) XtOffsetOf (shib_dir_config, bUseEnvVars),
1556 OR_AUTHCFG, FLAG, "Export attributes using environment variables (default)"},
1557 {"ShibUseHeaders", (config_fn_t)ap_set_flag_slot,
1558 (void *) XtOffsetOf (shib_dir_config, bUseHeaders),
1559 OR_AUTHCFG, FLAG, "Export attributes using custom HTTP headers"},
1565 handler_rec shib_handlers[] = {
1566 { "shib-handler", shib_handler },
1570 module MODULE_VAR_EXPORT mod_shib = {
1571 STANDARD_MODULE_STUFF,
1572 nullptr, /* initializer */
1573 create_shib_dir_config, /* dir config creater */
1574 merge_shib_dir_config, /* dir merger --- default is to override */
1575 create_shib_server_config, /* server config */
1576 merge_shib_server_config, /* merge server config */
1577 shire_cmds, /* command table */
1578 shib_handlers, /* handlers */
1579 nullptr, /* filename translation */
1580 shib_check_user, /* check_user_id */
1581 shib_auth_checker, /* check auth */
1582 nullptr, /* check access */
1583 nullptr, /* type_checker */
1584 shib_fixups, /* fixups */
1585 nullptr, /* logger */
1586 nullptr, /* header parser */
1587 shib_child_init, /* child_init */
1588 shib_child_exit, /* child_exit */
1589 shib_post_read /* post read-request */
1592 #elif defined(SHIB_APACHE_20) || defined(SHIB_APACHE_22)
1594 //static const char * const authnPre[] = { "mod_gss.c", nullptr };
1596 extern "C" void shib_register_hooks (apr_pool_t *p)
1598 #ifdef SHIB_DEFERRED_HEADERS
1599 ap_register_output_filter("SHIB_HEADERS_OUT", do_output_filter, nullptr, AP_FTYPE_CONTENT_SET);
1600 ap_hook_insert_filter(set_output_filter, nullptr, nullptr, APR_HOOK_LAST);
1601 ap_register_output_filter("SHIB_HEADERS_ERR", do_error_filter, nullptr, AP_FTYPE_CONTENT_SET);
1602 ap_hook_insert_error_filter(set_error_filter, nullptr, nullptr, APR_HOOK_LAST);
1603 ap_hook_post_read_request(shib_post_read, nullptr, nullptr, APR_HOOK_MIDDLE);
1605 ap_hook_child_init(shib_child_init, nullptr, nullptr, APR_HOOK_MIDDLE);
1606 const char* prereq = getenv("SHIBSP_APACHE_PREREQ");
1607 if (prereq && *prereq) {
1608 const char* const authnPre[] = { prereq, nullptr };
1609 ap_hook_check_user_id(shib_check_user, authnPre, nullptr, APR_HOOK_MIDDLE);
1612 ap_hook_check_user_id(shib_check_user, nullptr, nullptr, APR_HOOK_MIDDLE);
1614 ap_hook_auth_checker(shib_auth_checker, nullptr, nullptr, APR_HOOK_FIRST);
1615 ap_hook_handler(shib_handler, nullptr, nullptr, APR_HOOK_LAST);
1616 ap_hook_fixups(shib_fixups, nullptr, nullptr, APR_HOOK_MIDDLE);
1619 // SHIB Module commands
1622 static command_rec shib_cmds[] = {
1623 AP_INIT_TAKE1("ShibPrefix", (config_fn_t)ap_set_global_string_slot, &g_szPrefix,
1624 RSRC_CONF, "Shibboleth installation directory"),
1625 AP_INIT_TAKE1("ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1626 RSRC_CONF, "Path to shibboleth2.xml config file"),
1627 AP_INIT_TAKE1("ShibCatalogs", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1628 RSRC_CONF, "Paths of XML schema catalogs"),
1629 AP_INIT_TAKE1("ShibGSSKey", (config_fn_t)ap_set_global_string_slot, &g_szGSSContextKey,
1630 RSRC_CONF, "Name of user data key containing GSS context established by GSS module"),
1632 AP_INIT_TAKE1("ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
1633 (void *) offsetof (shib_server_config, szScheme),
1634 RSRC_CONF, "URL scheme to force into generated URLs for a vhost"),
1636 AP_INIT_TAKE2("ShibRequestSetting", (config_fn_t)shib_table_set, nullptr,
1637 OR_AUTHCFG, "Set arbitrary Shibboleth request property for content"),
1639 AP_INIT_TAKE1("ShibAccessControl", (config_fn_t)ap_set_string_slot,
1640 (void *) offsetof (shib_dir_config, szAccessControl),
1641 OR_AUTHCFG, "Set arbitrary Shibboleth access control plugin for content"),
1643 AP_INIT_FLAG("ShibDisable", (config_fn_t)ap_set_flag_slot,
1644 (void *) offsetof (shib_dir_config, bOff),
1645 OR_AUTHCFG, "Disable all Shib module activity here to save processing effort"),
1646 AP_INIT_TAKE1("ShibApplicationId", (config_fn_t)ap_set_string_slot,
1647 (void *) offsetof (shib_dir_config, szApplicationId),
1648 OR_AUTHCFG, "Set Shibboleth applicationId property for content"),
1649 AP_INIT_FLAG("ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1650 (void *) offsetof (shib_dir_config, bBasicHijack),
1651 OR_AUTHCFG, "(DEPRECATED) Respond to AuthType Basic and convert to shibboleth"),
1652 AP_INIT_FLAG("ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1653 (void *) offsetof (shib_dir_config, bRequireSession),
1654 OR_AUTHCFG, "Initiates a new session if one does not exist"),
1655 AP_INIT_TAKE1("ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
1656 (void *) offsetof (shib_dir_config, szRequireWith),
1657 OR_AUTHCFG, "Initiates a new session if one does not exist using a specific SessionInitiator"),
1658 AP_INIT_FLAG("ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1659 (void *) offsetof (shib_dir_config, bExportAssertion),
1660 OR_AUTHCFG, "Export SAML attribute assertion(s) to Shib-Attributes header"),
1661 AP_INIT_TAKE1("ShibRedirectToSSL", (config_fn_t)ap_set_string_slot,
1662 (void *) offsetof (shib_dir_config, szRedirectToSSL),
1663 OR_AUTHCFG, "Redirect non-SSL requests to designated port"),
1664 AP_INIT_TAKE1("AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
1665 (void *) offsetof (shib_dir_config, szAuthGrpFile),
1666 OR_AUTHCFG, "Text file containing group names and member user IDs"),
1667 AP_INIT_FLAG("ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1668 (void *) offsetof (shib_dir_config, bRequireAll),
1669 OR_AUTHCFG, "All require directives must match"),
1670 AP_INIT_FLAG("AuthzShibAuthoritative", (config_fn_t)ap_set_flag_slot,
1671 (void *) offsetof (shib_dir_config, bAuthoritative),
1672 OR_AUTHCFG, "Allow failed mod_shib htaccess authorization to fall through to other modules"),
1673 AP_INIT_FLAG("ShibUseEnvironment", (config_fn_t)ap_set_flag_slot,
1674 (void *) offsetof (shib_dir_config, bUseEnvVars),
1675 OR_AUTHCFG, "Export attributes using environment variables (default)"),
1676 AP_INIT_FLAG("ShibUseHeaders", (config_fn_t)ap_set_flag_slot,
1677 (void *) offsetof (shib_dir_config, bUseHeaders),
1678 OR_AUTHCFG, "Export attributes using custom HTTP headers"),
1683 module AP_MODULE_DECLARE_DATA mod_shib = {
1684 STANDARD20_MODULE_STUFF,
1685 create_shib_dir_config, /* create dir config */
1686 merge_shib_dir_config, /* merge dir config --- default is to override */
1687 create_shib_server_config, /* create server config */
1688 merge_shib_server_config, /* merge server config */
1689 shib_cmds, /* command table */
1690 shib_register_hooks /* register hooks */
1694 #error "unsupported Apache version"