2 * Licensed to the University Corporation for Advanced Internet
3 * Development, Inc. (UCAID) under one or more contributor license
4 * agreements. See the NOTICE file distributed with this work for
5 * additional information regarding copyright ownership.
7 * UCAID licenses this file to you under the Apache License,
8 * Version 2.0 (the "License"); you may not use this file except
9 * in compliance with the License. You may obtain a copy of the
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17 * either express or implied. See the License for the specific
18 * language governing permissions and limitations under the License.
24 * Apache module implementation.
30 #undef _XOPEN_SOURCE // causes gethostname conflict in unistd.h
34 # define _CRT_NONSTDC_NO_DEPRECATE 1
35 # define _CRT_SECURE_NO_DEPRECATE 1
38 #include <shibsp/exceptions.h>
39 #include <shibsp/AbstractSPRequest.h>
40 #include <shibsp/AccessControl.h>
41 #include <shibsp/GSSRequest.h>
42 #include <shibsp/RequestMapper.h>
43 #include <shibsp/SPConfig.h>
44 #include <shibsp/ServiceProvider.h>
45 #include <shibsp/SessionCache.h>
46 #include <shibsp/attribute/Attribute.h>
48 #include <xercesc/util/XMLUniDefs.hpp>
49 #include <xercesc/util/regx/RegularExpression.hpp>
50 #include <xmltooling/XMLToolingConfig.h>
51 #include <xmltooling/util/NDC.h>
52 #include <xmltooling/util/ParserPool.h>
53 #include <xmltooling/util/Threads.h>
54 #include <xmltooling/util/XMLConstants.h>
55 #include <xmltooling/util/XMLHelper.h>
58 # include <winsock2.h>
59 # include <ws2tcpip.h>
68 #include <boost/lexical_cast.hpp>
70 // Apache specific header files
72 #include <http_config.h>
73 #include <http_protocol.h>
74 #include <http_main.h>
76 #include <http_core.h>
78 #include <http_request.h>
80 #ifndef SHIB_APACHE_13
81 #include <apr_buckets.h>
82 #include <apr_strings.h>
83 #include <apr_pools.h>
92 #include <unistd.h> // for getpid()
95 using namespace shibsp;
96 using namespace xmltooling;
97 using namespace boost;
99 using xercesc::RegularExpression;
100 using xercesc::XMLException;
102 #ifdef APLOG_USE_MODULE
103 extern "C" module AP_MODULE_DECLARE_DATA mod_shib;
104 static int* const aplog_module_index = &(mod_shib.module_index);
106 extern "C" module MODULE_VAR_EXPORT mod_shib;
110 char* g_szSHIBConfig = nullptr;
111 char* g_szSchemaDir = nullptr;
112 char* g_szPrefix = nullptr;
113 SPConfig* g_Config = nullptr;
114 string g_unsetHeaderValue,g_spoofKey;
115 bool g_checkSpoofing = true;
116 bool g_catchAll = false;
117 #ifndef SHIB_APACHE_13
118 char* g_szGSSContextKey = "mod_auth_gssapi:gss_ctx";
120 static const char* g_UserDataKey = "urn:mace:shibboleth:Apache:shib_check_user";
123 /* Apache 2.2.x headers must be accumulated and set in the output filter.
124 Apache 2.0.49+ supports the filter method.
125 Apache 1.3.x and lesser 2.0.x must write the headers directly. */
127 #if (defined(SHIB_APACHE_20) || defined(SHIB_APACHE_22) || defined(SHIB_APACHE_24)) && AP_MODULE_MAGIC_AT_LEAST(20020903,6)
128 #define SHIB_DEFERRED_HEADERS
131 /********************************************************************************/
132 // Basic Apache Configuration code.
135 // per-server module configuration structure
136 struct shib_server_config
139 int bCompatValidUser;
142 // creates the per-server configuration
143 extern "C" void* create_shib_server_config(SH_AP_POOL* p, server_rec* s)
145 shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
146 sc->szScheme = nullptr;
147 sc->bCompatValidUser = -1;
151 // overrides server configuration in virtual servers
152 extern "C" void* merge_shib_server_config (SH_AP_POOL* p, void* base, void* sub)
154 shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
155 shib_server_config* parent=(shib_server_config*)base;
156 shib_server_config* child=(shib_server_config*)sub;
159 sc->szScheme=ap_pstrdup(p,child->szScheme);
160 else if (parent->szScheme)
161 sc->szScheme=ap_pstrdup(p,parent->szScheme);
163 sc->szScheme=nullptr;
165 sc->bCompatValidUser = ((child->bCompatValidUser==-1) ? parent->bCompatValidUser : child->bCompatValidUser);
170 // per-dir module configuration structure
171 struct shib_dir_config
173 SH_AP_TABLE* tSettings; // generic table of extensible settings
176 #ifdef SHIB_APACHE_24
177 int bRequestMapperAuthz;// support RequestMapper AccessControl plugins
179 char* szAuthGrpFile; // Auth GroupFile name
180 char* szAccessControl; // path to "external" AccessControl plugin file
181 int bRequireAll; // all "known" require directives must match, otherwise OR logic
182 int bAuthoritative; // allow htaccess plugin to DECLINE when authz fails
183 int bCompatWith24; // support 2.4-reserved require logic for compatibility
186 // Content Configuration
187 char* szApplicationId; // Shib applicationId value
188 char* szRequireWith; // require a session using a specific initiator?
189 char* szRedirectToSSL; // redirect non-SSL requests to SSL port
190 int bOff; // flat-out disable all Shib processing
191 int bBasicHijack; // activate for AuthType Basic?
192 int bRequireSession; // require a session?
193 int bExportAssertion; // export SAML assertion to the environment?
194 int bUseEnvVars; // use environment?
195 int bUseHeaders; // use headers?
196 int bExpireRedirects; // expire redirects?
199 // creates per-directory config structure
200 extern "C" void* create_shib_dir_config (SH_AP_POOL* p, char* d)
202 shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
203 dc->tSettings = nullptr;
204 #ifdef SHIB_APACHE_24
205 dc->bRequestMapperAuthz = -1;
207 dc->szAuthGrpFile = nullptr;
208 dc->szAccessControl = nullptr;
209 dc->bRequireAll = -1;
210 dc->bAuthoritative = -1;
211 dc->bCompatWith24 = -1;
213 dc->szApplicationId = nullptr;
214 dc->szRequireWith = nullptr;
215 dc->szRedirectToSSL = nullptr;
217 dc->bBasicHijack = -1;
218 dc->bRequireSession = -1;
219 dc->bExportAssertion = -1;
220 dc->bUseEnvVars = -1;
221 dc->bUseHeaders = -1;
222 dc->bExpireRedirects = -1;
226 // overrides server configuration in directories
227 extern "C" void* merge_shib_dir_config (SH_AP_POOL* p, void* base, void* sub)
229 shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
230 shib_dir_config* parent=(shib_dir_config*)base;
231 shib_dir_config* child=(shib_dir_config*)sub;
233 // The child supersedes any matching table settings in the parent.
234 dc->tSettings = nullptr;
235 if (parent->tSettings)
236 dc->tSettings = ap_copy_table(p, parent->tSettings);
237 if (child->tSettings) {
239 ap_overlap_tables(dc->tSettings, child->tSettings, AP_OVERLAP_TABLES_SET);
241 dc->tSettings = ap_copy_table(p, child->tSettings);
244 #ifdef SHIB_APACHE_24
245 dc->bRequestMapperAuthz = ((child->bRequestMapperAuthz==-1) ? parent->bRequestMapperAuthz : child->bRequestMapperAuthz);
247 if (child->szAuthGrpFile)
248 dc->szAuthGrpFile=ap_pstrdup(p,child->szAuthGrpFile);
249 else if (parent->szAuthGrpFile)
250 dc->szAuthGrpFile=ap_pstrdup(p,parent->szAuthGrpFile);
252 dc->szAuthGrpFile=nullptr;
254 if (child->szAccessControl)
255 dc->szAccessControl=ap_pstrdup(p,child->szAccessControl);
256 else if (parent->szAccessControl)
257 dc->szAccessControl=ap_pstrdup(p,parent->szAccessControl);
259 dc->szAccessControl=nullptr;
262 if (child->szApplicationId)
263 dc->szApplicationId=ap_pstrdup(p,child->szApplicationId);
264 else if (parent->szApplicationId)
265 dc->szApplicationId=ap_pstrdup(p,parent->szApplicationId);
267 dc->szApplicationId=nullptr;
269 if (child->szRequireWith)
270 dc->szRequireWith=ap_pstrdup(p,child->szRequireWith);
271 else if (parent->szRequireWith)
272 dc->szRequireWith=ap_pstrdup(p,parent->szRequireWith);
274 dc->szRequireWith=nullptr;
276 if (child->szRedirectToSSL)
277 dc->szRedirectToSSL=ap_pstrdup(p,child->szRedirectToSSL);
278 else if (parent->szRedirectToSSL)
279 dc->szRedirectToSSL=ap_pstrdup(p,parent->szRedirectToSSL);
281 dc->szRedirectToSSL=nullptr;
283 dc->bOff = ((child->bOff==-1) ? parent->bOff : child->bOff);
284 dc->bBasicHijack = ((child->bBasicHijack==-1) ? parent->bBasicHijack : child->bBasicHijack);
285 dc->bRequireSession = ((child->bRequireSession==-1) ? parent->bRequireSession : child->bRequireSession);
286 dc->bExportAssertion = ((child->bExportAssertion==-1) ? parent->bExportAssertion : child->bExportAssertion);
287 #ifndef SHIB_APACHE_24
288 dc->bRequireAll = ((child->bRequireAll==-1) ? parent->bRequireAll : child->bRequireAll);
289 dc->bAuthoritative = ((child->bAuthoritative==-1) ? parent->bAuthoritative : child->bAuthoritative);
290 dc->bCompatWith24 = ((child->bCompatWith24==-1) ? parent->bCompatWith24 : child->bCompatWith24);
292 dc->bUseEnvVars = ((child->bUseEnvVars==-1) ? parent->bUseEnvVars : child->bUseEnvVars);
293 dc->bUseHeaders = ((child->bUseHeaders==-1) ? parent->bUseHeaders : child->bUseHeaders);
294 dc->bExpireRedirects = ((child->bExpireRedirects==-1) ? parent->bExpireRedirects : child->bExpireRedirects);
298 class ShibTargetApache; // forward decl
300 // per-request module structure
301 struct shib_request_config
303 SH_AP_TABLE* env; // environment vars
304 #ifdef SHIB_DEFERRED_HEADERS
305 SH_AP_TABLE* hdr_out; // headers to browser
307 #ifndef SHIB_APACHE_13
308 ShibTargetApache* sta; // SP per-request structure wrapped around Apache's request
312 // create or return a request record
313 static shib_request_config* get_request_config(request_rec *r)
315 shib_request_config* rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
317 ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "get_request_config called redundantly");
320 ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "get_request_config created per-request structure");
321 rc = (shib_request_config*)ap_pcalloc(r->pool,sizeof(shib_request_config));
322 memset(rc, 0, sizeof(shib_request_config));
323 ap_set_module_config(r->request_config, &mod_shib, rc);
328 class ShibTargetApache : public AbstractSPRequest
329 #if defined(SHIBSP_HAVE_GSSAPI) && !defined(SHIB_APACHE_13)
333 mutable string m_body;
334 mutable bool m_gotBody,m_firsttime;
335 mutable vector<string> m_certs;
336 set<string> m_allhttp;
337 #if defined(SHIBSP_HAVE_GSSAPI) && !defined(SHIB_APACHE_13)
338 mutable gss_name_t m_gssname;
344 shib_dir_config* m_dc;
345 shib_server_config* m_sc;
346 shib_request_config* m_rc;
348 ShibTargetApache(request_rec* req) : AbstractSPRequest(SHIBSP_LOGCAT".Apache"),
349 m_gotBody(false),m_firsttime(true),
350 #if defined(SHIBSP_HAVE_GSSAPI) && !defined(SHIB_APACHE_13)
351 m_gssname(GSS_C_NO_NAME),
353 m_handler(false), m_req(req), m_dc(nullptr), m_sc(nullptr), m_rc(nullptr) {
355 virtual ~ShibTargetApache() {
356 #if defined(SHIBSP_HAVE_GSSAPI) && !defined(SHIB_APACHE_13)
357 if (m_gssname != GSS_C_NO_NAME) {
359 gss_release_name(&minor, &m_gssname);
364 bool isInitialized() const {
365 return (m_sc != nullptr);
368 bool init(bool handler, bool check_user) {
371 return !check_user; // only initialize once
372 m_sc = (shib_server_config*)ap_get_module_config(m_req->server->module_config, &mod_shib);
373 m_dc = (shib_dir_config*)ap_get_module_config(m_req->per_dir_config, &mod_shib);
374 m_rc = (shib_request_config*)ap_get_module_config(m_req->request_config, &mod_shib);
376 setRequestURI(m_req->unparsed_uri);
378 if (check_user && m_dc->bUseHeaders == 1) {
379 // Try and see if this request was already processed, to skip spoof checking.
380 if (!ap_is_initial_req(m_req)) {
383 else if (!g_spoofKey.empty()) {
384 const char* hdr = ap_table_get(m_req->headers_in, "Shib-Spoof-Check");
385 if (hdr && g_spoofKey == hdr)
389 log(SPDebug, "shib_check_user running more than once");
394 const char* getScheme() const {
395 return m_sc->szScheme ? m_sc->szScheme : ap_http_method(m_req);
397 bool isSecure() const {
398 return HTTPRequest::isSecure();
400 const char* getHostname() const {
401 #ifdef SHIB_APACHE_24
402 return ap_get_server_name_for_url(m_req);
404 return ap_get_server_name(m_req);
407 int getPort() const {
408 return ap_get_server_port(m_req);
410 const char* getMethod() const {
411 return m_req->method;
413 string getContentType() const {
414 const char* type = ap_table_get(m_req->headers_in, "Content-Type");
415 return type ? type : "";
417 long getContentLength() const {
418 return m_gotBody ? m_body.length() : m_req->remaining;
420 string getRemoteAddr() const {
421 string ret = AbstractSPRequest::getRemoteAddr();
424 #ifdef SHIB_APACHE_24
425 return m_req->useragent_ip;
427 return m_req->connection->remote_ip;
430 void log(SPLogLevel level, const string& msg) const {
431 AbstractSPRequest::log(level,msg);
434 (level == SPDebug ? APLOG_DEBUG :
435 (level == SPInfo ? APLOG_INFO :
436 (level == SPWarn ? APLOG_WARNING :
437 (level == SPError ? APLOG_ERR : APLOG_CRIT))))|APLOG_NOERRNO,
443 const char* getQueryString() const { return m_req->args; }
444 const char* getRequestBody() const {
445 if (m_gotBody || m_req->method_number==M_GET)
446 return m_body.c_str();
447 #ifdef SHIB_APACHE_13
448 // Read the posted data
449 if (ap_setup_client_block(m_req, REQUEST_CHUNKED_DECHUNK) != OK) {
451 log(SPError, "Apache function (setup_client_block) failed while reading request body.");
452 return m_body.c_str();
454 if (!ap_should_client_block(m_req)) {
456 log(SPError, "Apache function (should_client_block) failed while reading request body.");
457 return m_body.c_str();
459 if (m_req->remaining > 1024*1024)
460 throw opensaml::SecurityPolicyException("Blocked request body larger than 1M size limit.");
463 char buff[HUGE_STRING_LEN];
464 ap_hard_timeout("[mod_shib] getRequestBody", m_req);
465 while ((len=ap_get_client_block(m_req, buff, sizeof(buff))) > 0) {
466 ap_reset_timeout(m_req);
467 m_body.append(buff, len);
469 ap_kill_timeout(m_req);
474 apr_bucket_brigade* bb = apr_brigade_create(m_req->pool, m_req->connection->bucket_alloc);
477 apr_status_t rv = ap_get_brigade(m_req->input_filters, bb, AP_MODE_READBYTES, APR_BLOCK_READ, HUGE_STRING_LEN);
478 if (rv != APR_SUCCESS) {
479 log(SPError, "Apache function (ap_get_brigade) failed while reading request body.");
483 for (bucket = APR_BRIGADE_FIRST(bb); bucket != APR_BRIGADE_SENTINEL(bb); bucket = APR_BUCKET_NEXT(bucket)) {
484 if (APR_BUCKET_IS_EOS(bucket)) {
489 /* We can't do much with this. */
490 if (APR_BUCKET_IS_FLUSH(bucket))
494 apr_bucket_read(bucket, &data, &len, APR_BLOCK_READ);
496 m_body.append(data, len);
498 apr_brigade_cleanup(bb);
500 apr_brigade_destroy(bb);
503 return m_body.c_str();
505 const char* getParameter(const char* name) const {
506 return AbstractSPRequest::getParameter(name);
508 vector<const char*>::size_type getParameters(const char* name, vector<const char*>& values) const {
509 return AbstractSPRequest::getParameters(name, values);
511 void clearHeader(const char* rawname, const char* cginame) {
512 if (m_dc->bUseHeaders == 1) {
513 // ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_clear_header: hdr\n");
514 if (g_checkSpoofing && m_firsttime) {
515 if (m_allhttp.empty()) {
516 // First time, so populate set with "CGI" versions of client-supplied headers.
517 #ifdef SHIB_APACHE_13
518 array_header *hdrs_arr = ap_table_elts(m_req->headers_in);
519 table_entry *hdrs = (table_entry *) hdrs_arr->elts;
521 const apr_array_header_t *hdrs_arr = apr_table_elts(m_req->headers_in);
522 const apr_table_entry_t *hdrs = (const apr_table_entry_t *) hdrs_arr->elts;
524 for (int i = 0; i < hdrs_arr->nelts; ++i) {
527 string cgiversion("HTTP_");
528 const char* pch = hdrs[i].key;
530 cgiversion += (isalnum(*pch) ? toupper(*pch) : '_');
533 m_allhttp.insert(cgiversion);
537 if (m_allhttp.count(cginame) > 0)
538 throw opensaml::SecurityPolicyException("Attempt to spoof header ($1) was detected.", params(1, rawname));
540 ap_table_unset(m_req->headers_in, rawname);
541 ap_table_set(m_req->headers_in, rawname, g_unsetHeaderValue.c_str());
544 void setHeader(const char* name, const char* value) {
545 if (m_dc->bUseEnvVars != 0) {
547 // this happens on subrequests
548 // ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_setheader: no_m_rc\n");
549 m_rc = get_request_config(m_req);
552 m_rc->env = ap_make_table(m_req->pool, 10);
553 // ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_set_env: %s=%s\n", name, value?value:"Null");
554 ap_table_set(m_rc->env, name, value ? value : "");
556 if (m_dc->bUseHeaders == 1)
557 ap_table_set(m_req->headers_in, name, value);
559 string getHeader(const char* name) const {
560 const char* hdr = ap_table_get(m_req->headers_in, name);
561 return string(hdr ? hdr : "");
563 string getSecureHeader(const char* name) const {
564 if (m_dc->bUseEnvVars != 0) {
566 if (m_rc && m_rc->env)
567 hdr = ap_table_get(m_rc->env, name);
570 return string(hdr ? hdr : "");
572 return getHeader(name);
574 void setRemoteUser(const char* user) {
575 SH_AP_USER(m_req) = user ? ap_pstrdup(m_req->pool, user) : nullptr;
576 if (m_dc->bUseHeaders == 1) {
578 ap_table_set(m_req->headers_in, "REMOTE_USER", user);
581 ap_table_unset(m_req->headers_in, "REMOTE_USER");
582 ap_table_set(m_req->headers_in, "REMOTE_USER", g_unsetHeaderValue.c_str());
586 string getRemoteUser() const {
587 return string(SH_AP_USER(m_req) ? SH_AP_USER(m_req) : "");
589 void setAuthType(const char* authtype) {
590 if (authtype && m_dc->bBasicHijack == 1)
592 SH_AP_AUTH_TYPE(m_req) = authtype ? ap_pstrdup(m_req->pool, authtype) : nullptr;
594 string getAuthType() const {
595 return string(SH_AP_AUTH_TYPE(m_req) ? SH_AP_AUTH_TYPE(m_req) : "");
597 void setContentType(const char* type) {
598 m_req->content_type = ap_psprintf(m_req->pool, "%s", type);
600 void setResponseHeader(const char* name, const char* value) {
601 HTTPResponse::setResponseHeader(name, value);
602 #ifdef SHIB_DEFERRED_HEADERS
604 // this happens on subrequests
605 m_rc = get_request_config(m_req);
608 m_rc->hdr_out = ap_make_table(m_req->pool, 5);
609 ap_table_add(m_rc->hdr_out, name, value);
613 ap_table_add(m_req->err_headers_out, name, value);
615 long sendResponse(istream& in, long status) {
616 if (status != XMLTOOLING_HTTP_STATUS_OK)
617 m_req->status = status;
618 ap_send_http_header(m_req);
622 ap_rwrite(buf,in.gcount(),m_req);
624 #if (defined(SHIB_APACHE_20) || defined(SHIB_APACHE_22) || defined(SHIB_APACHE_24))
625 if (status != XMLTOOLING_HTTP_STATUS_OK && status != XMLTOOLING_HTTP_STATUS_ERROR)
630 long sendRedirect(const char* url) {
631 HTTPResponse::sendRedirect(url);
632 ap_table_set(m_req->headers_out, "Location", url);
633 if (m_dc->bExpireRedirects != 0) {
634 ap_table_set(m_req->err_headers_out, "Expires", "Wed, 01 Jan 1997 12:00:00 GMT");
635 ap_table_set(m_req->err_headers_out, "Cache-Control", "private,no-store,no-cache,max-age=0");
639 const vector<string>& getClientCertificates() const {
640 if (m_certs.empty()) {
641 const char* cert = ap_table_get(m_req->subprocess_env, "SSL_CLIENT_CERT");
643 m_certs.push_back(cert);
646 cert = ap_table_get(m_req->subprocess_env, ap_psprintf(m_req->pool, "SSL_CLIENT_CERT_CHAIN_%d", i++));
648 m_certs.push_back(cert);
653 long returnDecline(void) { return DECLINED; }
654 long returnOK(void) { return OK; }
655 #if defined(SHIBSP_HAVE_GSSAPI) && !defined(SHIB_APACHE_13)
656 gss_ctx_id_t getGSSContext() const {
657 gss_ctx_id_t ctx = GSS_C_NO_CONTEXT;
658 apr_pool_userdata_get((void**)&ctx, g_szGSSContextKey, m_req->pool);
661 gss_name_t getGSSName() const {
662 if (m_gssname == GSS_C_NO_NAME) {
663 gss_ctx_id_t ctx = getGSSContext();
664 if (ctx != GSS_C_NO_CONTEXT) {
666 OM_uint32 major = gss_inquire_context(&minor, ctx, &m_gssname, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr);
667 if (major != GSS_S_COMPLETE)
668 m_gssname = GSS_C_NO_NAME;
676 /********************************************************************************/
679 #ifndef SHIB_APACHE_13
680 extern "C" apr_status_t shib_request_cleanup(void* rc)
682 if (rc && reinterpret_cast<shib_request_config*>(rc)->sta) {
683 delete reinterpret_cast<ShibTargetApache*>(reinterpret_cast<shib_request_config*>(rc)->sta);
684 reinterpret_cast<shib_request_config*>(rc)->sta = nullptr;
690 // Initial look at a request - create the per-request structure if need be
691 static int shib_post_read(request_rec *r)
693 shib_request_config* rc = get_request_config(r);
694 #ifdef SHIB_APACHE_24
696 rc->sta = new ShibTargetApache(r);
697 apr_pool_cleanup_register(r->pool, rc, shib_request_cleanup, apr_pool_cleanup_null);
703 // Performs authentication and enforce session requirements.
704 // Also does header/env export from session, and will dispatch
705 // SP handler requests if it detects a handler URL.
706 extern "C" int shib_check_user(request_rec* r)
708 // Short-circuit entirely?
709 if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff == 1)
712 ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user entered in pid (%d)", (int)getpid());
714 string threadid("[");
715 threadid += lexical_cast<string>(getpid()) + "] shib_check_user";
716 xmltooling::NDC ndc(threadid.c_str());
719 #ifndef SHIB_APACHE_24
720 ShibTargetApache sta(r);
721 ShibTargetApache* psta = &sta;
723 shib_request_config* rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
724 if (!rc || !rc->sta) {
725 ap_log_rerror(APLOG_MARK, APLOG_INFO|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user found no per-request structure");
726 shib_post_read(r); // ensures objects are created if post_read hook didn't run
727 rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
729 ShibTargetApache* psta = rc->sta;
731 if (!psta->init(false, true)) {
732 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user unable to initialize SP request object");
736 // Check user authentication and export information, then set the handler bypass
737 pair<bool,long> res = psta->getServiceProvider().doAuthentication(*psta, true);
738 apr_pool_userdata_setn((const void*)42,g_UserDataKey,nullptr,r->pool);
739 // If directed, install a spoof key to recognize when we've already cleared headers.
740 if (!g_spoofKey.empty() && (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bUseHeaders == 1))
741 ap_table_set(r->headers_in, "Shib-Spoof-Check", g_spoofKey.c_str());
743 #ifdef SHIB_APACHE_24
744 // This is insane, but Apache's internal request.c logic insists that an auth module
745 // returning OK MUST set r->user to avoid a failure. But they check for NULL and not
746 // for an empty string. If this turns out to cause trouble, there's no solution except
747 // to set a dummy ID any time it's not set.
748 if (res.second == OK && !r->user)
754 // user auth was okay -- export the session data now
755 res = psta->getServiceProvider().doExport(*psta);
757 #ifdef SHIB_APACHE_24
758 // See above for explanation of this hack.
759 if (res.second == OK && !r->user)
765 #ifdef SHIB_APACHE_24
766 // See above for explanation of this hack.
772 catch (std::exception& e) {
773 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user threw an exception: %s", e.what());
777 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user threw an unknown exception!");
784 // Runs SP handler requests when invoked directly.
785 extern "C" int shib_handler(request_rec* r)
787 // Short-circuit entirely?
788 if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff == 1)
791 string threadid("[");
792 threadid += lexical_cast<string>(getpid()) + "] shib_handler";
793 xmltooling::NDC ndc(threadid.c_str());
795 #ifndef SHIB_APACHE_13
796 // With 2.x, this handler always runs, though last.
797 // We check if shib_check_user ran, because it will detect a handler request
798 // and dispatch it directly.
800 apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
801 if (data==(const void*)42) {
802 ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "shib_handler skipped since check_user ran");
807 ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "shib_handler entered in pid (%d): %s", (int)getpid(), r->handler);
810 #ifndef SHIB_APACHE_24
811 ShibTargetApache sta(r);
812 ShibTargetApache* psta = &sta;
814 shib_request_config* rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
815 if (!rc || !rc->sta) {
816 ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "shib_handler found no per-request structure");
817 shib_post_read(r); // ensures objects are created if post_read hook didn't run
818 rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
820 ShibTargetApache* psta = rc->sta;
822 if (!psta->init(true, false)) {
823 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler unable to initialize SP request object");
827 pair<bool,long> res = psta->getServiceProvider().doHandler(*psta);
828 if (res.first) return res.second;
830 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "doHandler() did not handle the request");
833 catch (std::exception& e) {
834 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler threw an exception: %s", e.what());
838 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler threw an unknown exception!");
845 // This performs authorization functions to limit access.
846 // On all versions, this runs any RequestMap-attached plugins.
847 // For pre-2.4 versions, the RequestMap will always find an htAccess plugin
848 // that runs code to parse and enforce Apache Require rules.
849 // On 2.4, we have to short-circuit that and let Apache run callbacks
850 // for each Require rule we handle.
851 extern "C" int shib_auth_checker(request_rec* r)
853 // Short-circuit entirely?
854 shib_dir_config* dc = (shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib);
856 #ifdef SHIB_APACHE_24
857 || dc->bRequestMapperAuthz == 0 // this allows for bypass of the full auth_checker hook if only htaccess is used
863 ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker entered in pid (%d)", (int)getpid());
865 string threadid("[");
866 threadid += lexical_cast<string>(getpid()) + "] shib_auth_checker";
867 xmltooling::NDC ndc(threadid.c_str());
870 #ifndef SHIB_APACHE_24
871 ShibTargetApache sta(r);
872 ShibTargetApache* psta = &sta;
874 shib_request_config* rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
875 if (!rc || !rc->sta) {
876 ap_log_rerror(APLOG_MARK, APLOG_INFO|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker found no per-request structure");
877 shib_post_read(r); // ensures objects are created if post_read hook didn't run
878 rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
880 ShibTargetApache* psta = rc->sta;
882 if (!psta->init(false, false)) {
883 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker unable to initialize SP request object");
887 pair<bool,long> res = psta->getServiceProvider().doAuthorization(*psta);
888 if (res.first) return res.second;
890 // The SP method should always return true, so if we get this far, something unusual happened.
891 // Just let Apache (or some other module) decide what to do.
894 catch (std::exception& e) {
895 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an exception: %s", e.what());
899 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an unknown exception!");
906 // Overlays environment variables on top of subprocess table.
907 extern "C" int shib_fixups(request_rec* r)
909 shib_dir_config *dc = (shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib);
910 if (dc->bOff==1 || dc->bUseEnvVars==0)
913 ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "shib_fixups entered in pid (%d)", (int)getpid());
915 shib_request_config *rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
916 if (rc==nullptr || rc->env==nullptr || ap_is_empty_table(rc->env))
919 ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "shib_fixups adding %d vars", ap_table_elts(rc->env)->nelts);
920 r->subprocess_env = ap_overlay_tables(r->pool, r->subprocess_env, rc->env);
926 // Access control plugin that enforces pre-2.4 htaccess rules.
927 // Post-2.4, we have to register individual methods to respond
928 // to each require rule we want to handle, and have those call
929 // into these methods directly.
930 class htAccessControl : virtual public AccessControl
934 ~htAccessControl() {}
935 Lockable* lock() {return this;}
937 aclresult_t authorized(const SPRequest& request, const Session* session) const;
939 aclresult_t doAccessControl(const ShibTargetApache& sta, const Session* session, const char* plugin) const;
940 aclresult_t doUser(const ShibTargetApache& sta, const char* params) const;
941 #ifndef SHIB_APACHE_24
942 aclresult_t doGroup(const ShibTargetApache& sta, const char* params) const;
944 aclresult_t doAuthnContext(const ShibTargetApache& sta, const char* acRef, const char* params) const;
945 aclresult_t doShibAttr(const ShibTargetApache& sta, const Session* session, const char* rule, const char* params) const;
948 bool checkAttribute(const SPRequest& request, const Attribute* attr, const char* toMatch, RegularExpression* re) const;
951 AccessControl* htAccessFactory(const xercesc::DOMElement* const & e)
953 return new htAccessControl();
956 AccessControl::aclresult_t htAccessControl::doAccessControl(const ShibTargetApache& sta, const Session* session, const char* plugin) const
958 aclresult_t result = shib_acl_false;
960 ifstream aclfile(plugin);
962 throw ConfigurationException("Unable to open access control file ($1).", params(1, plugin));
963 xercesc::DOMDocument* acldoc = XMLToolingConfig::getConfig().getParser().parse(aclfile);
964 XercesJanitor<xercesc::DOMDocument> docjanitor(acldoc);
965 static XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
966 string t(XMLHelper::getAttrString(acldoc ? acldoc->getDocumentElement() : nullptr, nullptr, _type));
968 throw ConfigurationException("Missing type attribute in AccessControl plugin configuration.");
969 scoped_ptr<AccessControl> aclplugin(SPConfig::getConfig().AccessControlManager.newPlugin(t.c_str(), acldoc->getDocumentElement()));
970 Locker acllock(aclplugin.get());
971 result = aclplugin->authorized(sta, session);
973 catch (std::exception& ex) {
974 sta.log(SPRequest::SPError, ex.what());
979 AccessControl::aclresult_t htAccessControl::doUser(const ShibTargetApache& sta, const char* params) const
982 bool negated = false;
984 const char* w = ap_getword_conf(sta.m_req->pool, ¶ms);
989 else if (*w == '!') {
990 // A negated rule presumes success unless a match is found.
997 // Figure out if there's a match.
1001 // To do regex matching, we have to convert from UTF-8.
1002 auto_arrayptr<XMLCh> trans(fromUTF8(w));
1003 RegularExpression re(trans.get());
1004 auto_arrayptr<XMLCh> trans2(fromUTF8(sta.getRemoteUser().c_str()));
1005 match = re.matches(trans2.get());
1007 catch (XMLException& ex) {
1008 auto_ptr_char tmp(ex.getMessage());
1009 sta.log(SPRequest::SPError,
1010 string("htaccess plugin caught exception while parsing regular expression (") + w + "): " + tmp.get());
1013 else if (sta.getRemoteUser() == w) {
1018 if (sta.isPriorityEnabled(SPRequest::SPDebug))
1019 sta.log(SPRequest::SPDebug,
1020 string("htaccess: require user ") + (negated ? "rejecting (" : "accepting (") + sta.getRemoteUser() + ")");
1021 return (negated ? shib_acl_false : shib_acl_true);
1024 return (negated ? shib_acl_true : shib_acl_false);
1027 #ifndef SHIB_APACHE_24
1028 static SH_AP_TABLE* groups_for_user(request_rec* r, const char* user, char* grpfile)
1030 SH_AP_CONFIGFILE* f;
1031 SH_AP_TABLE* grps=ap_make_table(r->pool,15);
1032 char l[MAX_STRING_LEN];
1033 const char *group_name, *ll, *w;
1035 #ifdef SHIB_APACHE_13
1036 if (!(f=ap_pcfg_openfile(r->pool, grpfile))) {
1038 if (ap_pcfg_openfile(&f,r->pool,grpfile) != APR_SUCCESS) {
1040 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, SH_AP_R(r), "groups_for_user: could not open group file: %s\n", grpfile);
1045 #ifdef SHIB_APACHE_13
1046 sp=ap_make_sub_pool(r->pool);
1048 if (apr_pool_create(&sp,r->pool) != APR_SUCCESS) {
1049 ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,
1050 "groups_for_user: could not create a subpool");
1055 while (!(ap_cfg_getline(l,MAX_STRING_LEN,f))) {
1056 if ((*l=='#') || (!*l))
1060 group_name = ap_getword(sp,&ll,':');
1062 w=ap_getword_conf(sp,&ll);
1063 if (!strcmp(w,user)) {
1064 ap_table_setn(grps,ap_pstrdup(r->pool,group_name),"in");
1069 ap_cfg_closefile(f);
1070 ap_destroy_pool(sp);
1074 AccessControl::aclresult_t htAccessControl::doGroup(const ShibTargetApache& sta, const char* params) const
1076 SH_AP_TABLE* grpstatus = nullptr;
1077 if (sta.m_dc->szAuthGrpFile) {
1078 if (sta.isPriorityEnabled(SPRequest::SPDebug))
1079 sta.log(SPRequest::SPDebug, string("htaccess plugin using groups file: ") + sta.m_dc->szAuthGrpFile);
1080 grpstatus = groups_for_user(sta.m_req, sta.getRemoteUser().c_str(), sta.m_dc->szAuthGrpFile);
1083 bool negated = false;
1085 const char* w = ap_getword_conf(sta.m_req->pool, ¶ms);
1087 // A negated rule presumes success unless a match is found.
1092 if (grpstatus && ap_table_get(grpstatus, w)) {
1093 // If we matched, then we're done with this rule either way and we flip status to reflect the outcome.
1094 sta.log(SPRequest::SPDebug, string("htaccess: require group ") + (negated ? "rejecting (" : "accepting (") + w + ")");
1095 return (negated ? shib_acl_false : shib_acl_true);
1099 return (negated ? shib_acl_true : shib_acl_false);
1103 AccessControl::aclresult_t htAccessControl::doAuthnContext(const ShibTargetApache& sta, const char* ref, const char* params) const
1106 bool regexp = false;
1107 bool negated = false;
1108 while (ref && *params) {
1109 const char* w = ap_getword_conf(sta.m_req->pool, ¶ms);
1114 else if (*w == '!') {
1115 // A negated rule presumes success unless a match is found.
1122 // Figure out if there's a match.
1126 RegularExpression re(w);
1127 match = re.matches(ref);
1129 catch (XMLException& ex) {
1130 auto_ptr_char tmp(ex.getMessage());
1131 sta.log(SPRequest::SPError,
1132 string("htaccess plugin caught exception while parsing regular expression (") + w + "): " + tmp.get());
1135 else if (!strcmp(w, ref)) {
1140 if (sta.isPriorityEnabled(SPRequest::SPDebug))
1141 sta.log(SPRequest::SPDebug,
1142 string("htaccess: require authnContext ") + (negated ? "rejecting (" : "accepting (") + ref + ")");
1143 return (negated ? shib_acl_false : shib_acl_true);
1146 return (negated ? shib_acl_true : shib_acl_false);
1149 if (sta.isPriorityEnabled(SPRequest::SPDebug))
1150 sta.log(SPRequest::SPDebug, "htaccess: require authnContext rejecting session with no context associated");
1151 return shib_acl_false;
1154 bool htAccessControl::checkAttribute(const SPRequest& request, const Attribute* attr, const char* toMatch, RegularExpression* re) const
1156 bool caseSensitive = attr->isCaseSensitive();
1157 const vector<string>& vals = attr->getSerializedValues();
1158 for (vector<string>::const_iterator v = vals.begin(); v != vals.end(); ++v) {
1160 auto_arrayptr<XMLCh> trans(fromUTF8(v->c_str()));
1161 if (re->matches(trans.get())) {
1162 if (request.isPriorityEnabled(SPRequest::SPDebug))
1163 request.log(SPRequest::SPDebug, string("htaccess: expecting regexp ") + toMatch + ", got " + *v + ": acccepted");
1167 else if ((caseSensitive && *v == toMatch) || (!caseSensitive && !strcasecmp(v->c_str(), toMatch))) {
1168 if (request.isPriorityEnabled(SPRequest::SPDebug))
1169 request.log(SPRequest::SPDebug, string("htaccess: expecting ") + toMatch + ", got " + *v + ": accepted");
1172 else if (request.isPriorityEnabled(SPRequest::SPDebug)) {
1173 request.log(SPRequest::SPDebug, string("htaccess: expecting ") + toMatch + ", got " + *v + ": rejected");
1179 AccessControl::aclresult_t htAccessControl::doShibAttr(const ShibTargetApache& sta, const Session* session, const char* rule, const char* params) const
1181 #ifndef SHIB_APACHE_24
1182 // Look for the new shib-attr placeholder and move past it.
1183 if (sta.m_dc->bCompatWith24 == 1 && rule && !strcmp(rule, "shib-attr")) {
1185 rule = ap_getword_conf(sta.m_req->pool, ¶ms);
1189 // Find the attribute(s) matching the require rule.
1190 pair<multimap<string,const Attribute*>::const_iterator,multimap<string,const Attribute*>::const_iterator> attrs =
1191 session->getIndexedAttributes().equal_range(rule ? rule : "");
1193 bool regexp = false;
1194 while (attrs.first != attrs.second && *params) {
1195 const char* w = ap_getword_conf(sta.m_req->pool, ¶ms);
1202 scoped_ptr<RegularExpression> re;
1204 auto_arrayptr<XMLCh> trans(fromUTF8(w));
1205 re.reset(new xercesc::RegularExpression(trans.get()));
1208 pair<multimap<string,const Attribute*>::const_iterator,multimap<string,const Attribute*>::const_iterator> attrs2(attrs);
1209 for (; attrs2.first != attrs2.second; ++attrs2.first) {
1210 if (checkAttribute(sta, attrs2.first->second, w, regexp ? re.get() : nullptr)) {
1211 return shib_acl_true;
1215 catch (XMLException& ex) {
1216 auto_ptr_char tmp(ex.getMessage());
1217 sta.log(SPRequest::SPError, string("htaccess plugin caught exception while parsing regular expression (") + w + "): " + tmp.get());
1220 return shib_acl_false;
1223 AccessControl::aclresult_t htAccessControl::authorized(const SPRequest& request, const Session* session) const
1225 #ifdef SHIB_APACHE_24
1226 // We should never be invoked in 2.4 as an SP plugin.
1227 throw ConfigurationException("Save my walrus!");
1229 // Make sure the object is our type.
1230 const ShibTargetApache* sta=dynamic_cast<const ShibTargetApache*>(&request);
1232 throw ConfigurationException("Request wrapper object was not of correct type.");
1234 int m = sta->m_req->method_number;
1235 bool method_restricted = false;
1238 const array_header* reqs_arr = ap_requires(sta->m_req);
1240 return shib_acl_indeterminate; // should never happen
1242 // Check for an "embedded" AccessControl plugin.
1243 if (sta->m_dc->szAccessControl) {
1244 aclresult_t result = doAccessControl(*sta, session, sta->m_dc->szAccessControl);
1245 if (result == shib_acl_true && sta->m_dc->bRequireAll != 1) {
1246 // If we're not insisting that all rules be met, then we're done.
1247 request.log(SPRequest::SPDebug, "htaccess: embedded AccessControl plugin was successful, granting access");
1248 return shib_acl_true;
1250 else if (result != shib_acl_true && sta->m_dc->bRequireAll == 1) {
1251 // If we're insisting that all rules be met, which is not something Apache really handles well,
1252 // then we either return false or indeterminate based on the authoritative option, which defaults on.
1253 if (sta->m_dc->bAuthoritative != 0) {
1254 request.log(SPRequest::SPDebug, "htaccess: embedded AccessControl plugin was unsuccessful, denying access");
1255 return shib_acl_false;
1258 request.log(SPRequest::SPDebug, "htaccess: embedded AccessControl plugin was unsuccessful but not authoritative, leaving it up to Apache");
1259 return shib_acl_indeterminate;
1263 require_line* reqs = (require_line*)reqs_arr->elts;
1265 for (int x = 0; x < reqs_arr->nelts; ++x) {
1266 // This rule should be completely ignored, the method doesn't fit.
1267 // The rule just doesn't exist for our purposes.
1268 if (!(reqs[x].method_mask & (1 << m)))
1271 method_restricted = true; // this lets us know at the end that at least one rule was potentially enforcable.
1273 // Tracks status of this rule's evaluation.
1274 bool status = false;
1276 string remote_user = request.getRemoteUser();
1278 t = reqs[x].requirement;
1279 w = ap_getword_white(sta->m_req->pool, &t);
1281 if (!strcasecmp(w,"shibboleth")) {
1282 // This is a dummy rule needed because Apache conflates authn and authz.
1283 // Without some require rule, AuthType is ignored and no check_user hooks run.
1285 // We evaluate to false if ShibAccessControl is used and ShibRequireAll is off.
1286 // This allows actual rules to dictate the result, since ShibAccessControl returned
1287 // non-true, and if nothing else is used, access will be denied.
1288 if (!sta->m_dc->szAccessControl || sta->m_dc->bRequireAll == 1) {
1289 // We evaluate to true, because ShibRequireAll is enabled (so a true is just a no-op)
1290 // or because there was no other AccessControl rule in place, so this may be the only
1295 else if (!strcmp(w,"valid-user") && session) {
1296 request.log(SPRequest::SPDebug, "htaccess: accepting valid-user based on active session");
1299 else if (sta->m_dc->bCompatWith24 == 1 && !strcmp(w,"shib-session") && session) {
1300 request.log(SPRequest::SPDebug, "htaccess: accepting shib-session based on active session");
1303 else if (!strcmp(w,"user") && !remote_user.empty()) {
1304 status = (doUser(*sta, t) == shib_acl_true);
1306 else if (sta->m_dc->bCompatWith24 == 1 && !strcmp(w,"shib-user") && !remote_user.empty()) {
1307 status = (doUser(*sta, t) == shib_acl_true);
1309 else if (!strcmp(w,"group") && !remote_user.empty()) {
1310 status = (doGroup(*sta, t) == shib_acl_true);
1312 else if (!strcmp(w,"authnContextClassRef") || !strcmp(w,"authnContextDeclRef")) {
1313 const char* ref = !strcmp(w, "authnContextClassRef") ? session->getAuthnContextClassRef() : session->getAuthnContextDeclRef();
1314 status = (doAuthnContext(*sta, ref, t) == shib_acl_true);
1316 else if (!session) {
1317 request.log(SPRequest::SPError, string("htaccess: require ") + w + " not given a valid session, are you using lazy sessions?");
1319 else if (sta->m_dc->bCompatWith24 == 1 && !strcmp(w,"shib-plugin")) {
1320 w = ap_getword_conf(sta->m_req->pool, &t);
1322 status = (doAccessControl(*sta, session, w) == shib_acl_true);
1326 status = (doShibAttr(*sta, session, w, t) == shib_acl_true);
1329 // If status is false, we found a rule we couldn't satisfy.
1330 // Could be an unknown rule to us, or it just didn't match.
1332 if (status && sta->m_dc->bRequireAll != 1) {
1333 // If we're not insisting that all rules be met, then we're done.
1334 request.log(SPRequest::SPDebug, "htaccess: a rule was successful, granting access");
1335 return shib_acl_true;
1337 else if (!status && sta->m_dc->bRequireAll == 1) {
1338 // If we're insisting that all rules be met, which is not something Apache really handles well,
1339 // then we either return false or indeterminate based on the authoritative option, which defaults on.
1340 if (sta->m_dc->bAuthoritative != 0) {
1341 request.log(SPRequest::SPDebug, "htaccess: a rule was unsuccessful, denying access");
1342 return shib_acl_false;
1345 request.log(SPRequest::SPDebug, "htaccess: a rule was unsuccessful but not authoritative, leaving it up to Apache");
1346 return shib_acl_indeterminate;
1349 // Otherwise, we keep going. If we're requring all, then we have to check every rule.
1350 // If not we just didn't find a successful rule yet, so we keep going anyway.
1353 // If we get here, we either "failed" or we're in require all mode (but not both).
1354 // If no rules possibly apply or we insisted that all rules check out, then we're good.
1355 if (!method_restricted) {
1356 request.log(SPRequest::SPDebug, "htaccess: no rules applied to this request method, granting access");
1357 return shib_acl_true;
1359 else if (sta->m_dc->bRequireAll == 1) {
1360 request.log(SPRequest::SPDebug, "htaccess: all rules successful, granting access");
1361 return shib_acl_true;
1363 else if (sta->m_dc->bAuthoritative != 0) {
1364 request.log(SPRequest::SPDebug, "htaccess: no rules were successful, denying access");
1365 return shib_acl_false;
1368 request.log(SPRequest::SPDebug, "htaccess: no rules were successful but not authoritative, leaving it up to Apache");
1369 return shib_acl_indeterminate;
1373 class ApacheRequestMapper : public virtual RequestMapper, public virtual PropertySet
1376 ApacheRequestMapper(const xercesc::DOMElement* e);
1377 ~ApacheRequestMapper() {}
1378 Lockable* lock() { return m_mapper->lock(); }
1379 void unlock() { m_staKey->setData(nullptr); m_propsKey->setData(nullptr); m_mapper->unlock(); }
1380 Settings getSettings(const HTTPRequest& request) const;
1382 const PropertySet* getParent() const { return nullptr; }
1383 void setParent(const PropertySet*) {}
1384 pair<bool,bool> getBool(const char* name, const char* ns=nullptr) const;
1385 pair<bool,const char*> getString(const char* name, const char* ns=nullptr) const;
1386 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=nullptr) const;
1387 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=nullptr) const;
1388 pair<bool,int> getInt(const char* name, const char* ns=nullptr) const;
1389 void getAll(map<string,const char*>& properties) const;
1390 const PropertySet* getPropertySet(const char* name, const char* ns=shibspconstants::ASCII_SHIB2SPCONFIG_NS) const;
1391 const xercesc::DOMElement* getElement() const;
1393 const htAccessControl& getHTAccessControl() const { return m_htaccess; }
1396 scoped_ptr<RequestMapper> m_mapper;
1397 scoped_ptr<ThreadKey> m_staKey,m_propsKey;
1398 mutable htAccessControl m_htaccess;
1401 RequestMapper* ApacheRequestMapFactory(const xercesc::DOMElement* const & e)
1403 return new ApacheRequestMapper(e);
1406 ApacheRequestMapper::ApacheRequestMapper(const xercesc::DOMElement* e)
1407 : m_mapper(SPConfig::getConfig().RequestMapperManager.newPlugin(XML_REQUEST_MAPPER,e)),
1408 m_staKey(ThreadKey::create(nullptr)), m_propsKey(ThreadKey::create(nullptr))
1412 RequestMapper::Settings ApacheRequestMapper::getSettings(const HTTPRequest& request) const
1414 Settings s = m_mapper->getSettings(request);
1415 m_staKey->setData((void*)dynamic_cast<const ShibTargetApache*>(&request));
1416 m_propsKey->setData((void*)s.first);
1417 // Only return the htAccess plugin for pre-2.4 servers.
1418 #ifdef SHIB_APACHE_24
1419 return pair<const PropertySet*,AccessControl*>(this, s.second);
1421 return pair<const PropertySet*,AccessControl*>(this, s.second ? s.second : &m_htaccess);
1425 pair<bool,bool> ApacheRequestMapper::getBool(const char* name, const char* ns) const
1427 const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
1428 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
1430 // Override Apache-settable boolean properties.
1431 if (name && !strcmp(name,"requireSession") && sta->m_dc->bRequireSession != -1)
1432 return make_pair(true, sta->m_dc->bRequireSession==1);
1433 else if (name && !strcmp(name,"exportAssertion") && sta->m_dc->bExportAssertion != -1)
1434 return make_pair(true, sta->m_dc->bExportAssertion==1);
1435 else if (sta->m_dc->tSettings) {
1436 const char* prop = ap_table_get(sta->m_dc->tSettings, name);
1438 return make_pair(true, !strcmp(prop, "true") || !strcmp(prop, "1") || !strcmp(prop, "On"));
1441 return s ? s->getBool(name,ns) : make_pair(false,false);
1444 pair<bool,const char*> ApacheRequestMapper::getString(const char* name, const char* ns) const
1446 const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
1447 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
1449 // Override Apache-settable string properties.
1450 if (name && !strcmp(name,"authType")) {
1451 const char* auth_type = ap_auth_type(sta->m_req);
1453 // Check for Basic Hijack
1454 if (!strcasecmp(auth_type, "basic") && sta->m_dc->bBasicHijack == 1)
1455 auth_type = "shibboleth";
1456 return make_pair(true, auth_type);
1459 else if (name && !strcmp(name,"applicationId") && sta->m_dc->szApplicationId)
1460 return pair<bool,const char*>(true,sta->m_dc->szApplicationId);
1461 else if (name && !strcmp(name,"requireSessionWith") && sta->m_dc->szRequireWith)
1462 return pair<bool,const char*>(true,sta->m_dc->szRequireWith);
1463 else if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
1464 return pair<bool,const char*>(true,sta->m_dc->szRedirectToSSL);
1465 else if (sta->m_dc->tSettings) {
1466 const char* prop = ap_table_get(sta->m_dc->tSettings, name);
1468 return make_pair(true, prop);
1471 return s ? s->getString(name,ns) : pair<bool,const char*>(false,nullptr);
1474 pair<bool,const XMLCh*> ApacheRequestMapper::getXMLString(const char* name, const char* ns) const
1476 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
1477 return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,nullptr);
1480 pair<bool,unsigned int> ApacheRequestMapper::getUnsignedInt(const char* name, const char* ns) const
1482 const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
1483 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
1485 // Override Apache-settable int properties.
1486 if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
1487 return pair<bool,unsigned int>(true, strtol(sta->m_dc->szRedirectToSSL, nullptr, 10));
1488 else if (sta->m_dc->tSettings) {
1489 const char* prop = ap_table_get(sta->m_dc->tSettings, name);
1491 return pair<bool,unsigned int>(true, atoi(prop));
1494 return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
1497 pair<bool,int> ApacheRequestMapper::getInt(const char* name, const char* ns) const
1499 const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
1500 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
1502 // Override Apache-settable int properties.
1503 if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
1504 return pair<bool,int>(true,atoi(sta->m_dc->szRedirectToSSL));
1505 else if (sta->m_dc->tSettings) {
1506 const char* prop = ap_table_get(sta->m_dc->tSettings, name);
1508 return make_pair(true, atoi(prop));
1511 return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
1514 static int _rm_get_all_table_walk(void *v, const char *key, const char *value)
1516 reinterpret_cast<map<string,const char*>*>(v)->insert(pair<string,const char*>(key, value));
1520 void ApacheRequestMapper::getAll(map<string,const char*>& properties) const
1522 const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
1523 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
1526 s->getAll(properties);
1530 const char* auth_type=ap_auth_type(sta->m_req);
1532 // Check for Basic Hijack
1533 if (!strcasecmp(auth_type, "basic") && sta->m_dc->bBasicHijack == 1)
1534 auth_type = "shibboleth";
1535 properties["authType"] = auth_type;
1538 if (sta->m_dc->szApplicationId)
1539 properties["applicationId"] = sta->m_dc->szApplicationId;
1540 if (sta->m_dc->szRequireWith)
1541 properties["requireSessionWith"] = sta->m_dc->szRequireWith;
1542 if (sta->m_dc->szRedirectToSSL)
1543 properties["redirectToSSL"] = sta->m_dc->szRedirectToSSL;
1544 if (sta->m_dc->bRequireSession != 0)
1545 properties["requireSession"] = (sta->m_dc->bRequireSession==1) ? "true" : "false";
1546 if (sta->m_dc->bExportAssertion != 0)
1547 properties["exportAssertion"] = (sta->m_dc->bExportAssertion==1) ? "true" : "false";
1549 if (sta->m_dc->tSettings)
1550 ap_table_do(_rm_get_all_table_walk, &properties, sta->m_dc->tSettings, NULL);
1553 const PropertySet* ApacheRequestMapper::getPropertySet(const char* name, const char* ns) const
1555 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
1556 return s ? s->getPropertySet(name,ns) : nullptr;
1559 const xercesc::DOMElement* ApacheRequestMapper::getElement() const
1561 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
1562 return s ? s->getElement() : nullptr;
1565 // Authz callbacks for Apache 2.4
1566 // For some reason, these get run twice for each request, once before hooks like check_user, etc.
1567 // and once after. The first time through, the request object exists, but isn't initialized.
1568 // The other case is subrequests of some kinds: then post_read doesn't run, and the objects
1569 // themselves don't exist. We do deferred creation of the objects in check_user to fix that case.
1570 // In each screwed up case, we return "denied" so that nothing bad happens.
1571 #ifdef SHIB_APACHE_24
1572 pair<ShibTargetApache*,authz_status> shib_base_check_authz(request_rec* r)
1574 shib_request_config* rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
1575 if (!rc || !rc->sta) {
1576 ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "shib_base_check_authz found no per-request structure");
1577 return make_pair((ShibTargetApache*)nullptr, AUTHZ_DENIED_NO_USER);
1579 else if (!rc->sta->isInitialized()) {
1580 ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "shib_base_check_authz found uninitialized request object");
1581 return make_pair((ShibTargetApache*)nullptr, AUTHZ_DENIED_NO_USER);
1583 return make_pair(rc->sta, AUTHZ_GRANTED);
1586 extern "C" authz_status shib_shibboleth_check_authz(request_rec* r, const char* require_line, const void*)
1588 pair<ShibTargetApache*,authz_status> sta = shib_base_check_authz(r);
1591 return AUTHZ_GRANTED;
1594 extern "C" authz_status shib_session_check_authz(request_rec* r, const char* require_line, const void*)
1596 pair<ShibTargetApache*,authz_status> sta = shib_base_check_authz(r);
1601 Session* session = sta.first->getSession(false, true, false);
1602 Locker slocker(session, false);
1604 sta.first->log(SPRequest::SPDebug, "htaccess: accepting shib-session/valid-user based on active session");
1605 return AUTHZ_GRANTED;
1608 catch (std::exception& e) {
1609 sta.first->log(SPRequest::SPWarn, string("htaccess: unable to obtain session for access control check: ") + e.what());
1612 sta.first->log(SPRequest::SPDebug, "htaccess: denying shib-access/valid-user rule, no active session");
1613 return AUTHZ_DENIED_NO_USER;
1616 extern "C" authz_status shib_validuser_check_authz(request_rec* r, const char* require_line, const void*)
1618 // Shouldn't have actually ever hooked this, and now we're in conflict with mod_authz_user over the meaning.
1619 // For now, added a command to restore "normal" semantics for valid-user so that combined deployments can
1620 // use valid-user for non-Shibboleth cases and shib-session for the Shibboleth semantic.
1622 // In future, we may want to expose the AuthType set to honor down at this level so we can differentiate
1623 // based on AuthType. Unfortunately we allow overriding the AuthType to honor and we don't have access to
1624 // that setting from the ServiceProvider class..
1626 shib_server_config* sc = (shib_server_config*)ap_get_module_config(r->server->module_config, &mod_shib);
1627 if (sc->bCompatValidUser != 1) {
1628 return shib_session_check_authz(r, require_line, nullptr);
1631 // Reproduce mod_authz_user version...
1634 return AUTHZ_DENIED_NO_USER;
1637 return AUTHZ_GRANTED;
1640 extern "C" authz_status shib_ext_user_check_authz(request_rec* r, const char* require_line, const void*)
1642 pair<ShibTargetApache*,authz_status> sta = shib_base_check_authz(r);
1646 const htAccessControl& hta = dynamic_cast<const ApacheRequestMapper*>(sta.first->getRequestSettings().first)->getHTAccessControl();
1647 if (hta.doUser(*sta.first, require_line) == AccessControl::shib_acl_true)
1648 return AUTHZ_GRANTED;
1649 return AUTHZ_DENIED;
1652 extern "C" authz_status shib_user_check_authz(request_rec* r, const char* require_line, const void*)
1654 // Shouldn't have actually ever hooked this, and now we're in conflict with mod_authz_user over the meaning.
1655 // For now, added a command to restore "normal" semantics for user rules so that combined deployments can
1656 // use user for non-Shibboleth cases and shib-user for the Shibboleth semantic.
1658 // In future, we may want to expose the AuthType set to honor down at this level so we can differentiate
1659 // based on AuthType. Unfortunately we allow overriding the AuthType to honor and we don't have access to
1660 // that setting from the ServiceProvider class..
1662 shib_server_config* sc = (shib_server_config*)ap_get_module_config(r->server->module_config, &mod_shib);
1663 if (sc->bCompatValidUser != 1) {
1664 return shib_ext_user_check_authz(r, require_line, nullptr);
1667 // Reproduce mod_authz_user version...
1670 return AUTHZ_DENIED_NO_USER;
1673 const char* t = require_line;
1675 while ((w = ap_getword_conf(r->pool, &t)) && w[0]) {
1676 if (!strcmp(r->user, w)) {
1677 return AUTHZ_GRANTED;
1681 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01663)
1682 "access to %s failed, reason: user '%s' does not meet "
1683 "'require'ments for user to be allowed access",
1686 return AUTHZ_DENIED;
1689 extern "C" authz_status shib_acclass_check_authz(request_rec* r, const char* require_line, const void*)
1691 pair<ShibTargetApache*,authz_status> sta = shib_base_check_authz(r);
1695 const htAccessControl& hta = dynamic_cast<const ApacheRequestMapper*>(sta.first->getRequestSettings().first)->getHTAccessControl();
1698 Session* session = sta.first->getSession(false, true, false);
1699 Locker slocker(session, false);
1700 if (session && hta.doAuthnContext(*sta.first, session->getAuthnContextClassRef(), require_line) == AccessControl::shib_acl_true)
1701 return AUTHZ_GRANTED;
1702 return session ? AUTHZ_DENIED : AUTHZ_DENIED_NO_USER;
1704 catch (std::exception& e) {
1705 sta.first->log(SPRequest::SPWarn, string("htaccess: unable to obtain session for access control check: ") + e.what());
1708 return AUTHZ_GENERAL_ERROR;
1711 extern "C" authz_status shib_acdecl_check_authz(request_rec* r, const char* require_line, const void*)
1713 pair<ShibTargetApache*,authz_status> sta = shib_base_check_authz(r);
1717 const htAccessControl& hta = dynamic_cast<const ApacheRequestMapper*>(sta.first->getRequestSettings().first)->getHTAccessControl();
1720 Session* session = sta.first->getSession(false, true, false);
1721 Locker slocker(session, false);
1722 if (session && hta.doAuthnContext(*sta.first, session->getAuthnContextDeclRef(), require_line) == AccessControl::shib_acl_true)
1723 return AUTHZ_GRANTED;
1724 return session ? AUTHZ_DENIED : AUTHZ_DENIED_NO_USER;
1726 catch (std::exception& e) {
1727 sta.first->log(SPRequest::SPWarn, string("htaccess: unable to obtain session for access control check: ") + e.what());
1730 return AUTHZ_GENERAL_ERROR;
1733 extern "C" authz_status shib_attr_check_authz(request_rec* r, const char* require_line, const void*)
1735 pair<ShibTargetApache*,authz_status> sta = shib_base_check_authz(r);
1739 const htAccessControl& hta = dynamic_cast<const ApacheRequestMapper*>(sta.first->getRequestSettings().first)->getHTAccessControl();
1742 Session* session = sta.first->getSession(false, true, false);
1743 Locker slocker(session, false);
1745 const char* rule = ap_getword_conf(r->pool, &require_line);
1746 if (rule && hta.doShibAttr(*sta.first, session, rule, require_line) == AccessControl::shib_acl_true)
1747 return AUTHZ_GRANTED;
1749 return session ? AUTHZ_DENIED : AUTHZ_DENIED_NO_USER;
1751 catch (std::exception& e) {
1752 sta.first->log(SPRequest::SPWarn, string("htaccess: unable to obtain session for access control check: ") + e.what());
1755 return AUTHZ_GENERAL_ERROR;
1758 extern "C" authz_status shib_plugin_check_authz(request_rec* r, const char* require_line, const void*)
1760 pair<ShibTargetApache*,authz_status> sta = shib_base_check_authz(r);
1764 const htAccessControl& hta = dynamic_cast<const ApacheRequestMapper*>(sta.first->getRequestSettings().first)->getHTAccessControl();
1767 Session* session = sta.first->getSession(false, true, false);
1768 Locker slocker(session, false);
1770 const char* config = ap_getword_conf(r->pool, &require_line);
1771 if (config && hta.doAccessControl(*sta.first, session, config) == AccessControl::shib_acl_true)
1772 return AUTHZ_GRANTED;
1774 return session ? AUTHZ_DENIED : AUTHZ_DENIED_NO_USER;
1776 catch (std::exception& e) {
1777 sta.first->log(SPRequest::SPWarn, string("htaccess: unable to obtain session for access control check: ") + e.what());
1780 return AUTHZ_GENERAL_ERROR;
1784 // Command manipulation functions
1786 extern "C" const char* ap_set_global_string_slot(cmd_parms* parms, void*, const char* arg)
1788 *((char**)(parms->info))=ap_pstrdup(parms->pool,arg);
1792 extern "C" const char* shib_set_server_string_slot(cmd_parms* parms, void*, const char* arg)
1794 char* base=(char*)ap_get_module_config(parms->server->module_config,&mod_shib);
1795 size_t offset=(size_t)parms->info;
1796 *((char**)(base + offset))=ap_pstrdup(parms->pool,arg);
1800 extern "C" const char* shib_set_server_flag_slot(cmd_parms* parms, void*, int arg)
1802 char* base=(char*)ap_get_module_config(parms->server->module_config,&mod_shib);
1803 size_t offset=(size_t)parms->info;
1804 *((int*)(base + offset)) = arg;
1808 extern "C" const char* shib_ap_set_file_slot(cmd_parms* parms,
1809 #ifdef SHIB_APACHE_13
1810 char* arg1, char* arg2
1812 void* arg1, const char* arg2
1816 ap_set_file_slot(parms, arg1, arg2);
1820 extern "C" const char* shib_table_set(cmd_parms* parms, shib_dir_config* dc, const char* arg1, const char* arg2)
1823 dc->tSettings = ap_make_table(parms->pool, 4);
1824 ap_table_set(dc->tSettings, arg1, arg2);
1828 #ifndef SHIB_APACHE_24
1829 extern "C" const char* shib_set_acl_slot(cmd_parms* params, shib_dir_config* dc, char* arg)
1841 absolute = (*(arg+1) == '.' || *(arg+1) == '/' || *(arg+1) == '\\');
1844 absolute = *(arg+1) == ':';
1847 if (absolute || !params->path)
1848 dc->szAccessControl = ap_pstrdup(params->pool, arg);
1850 dc->szAccessControl = ap_pstrcat(params->pool, params->path, arg, NULL);
1856 #ifdef SHIB_APACHE_13
1859 * Cleanup the (per-process) pool info.
1861 extern "C" void shib_child_exit(server_rec* s, SH_AP_POOL* p)
1867 ap_log_error(APLOG_MARK, APLOG_INFO|APLOG_NOERRNO, SH_AP_R(s), "child_exit: mod_shib shutdown in pid (%d)", (int)getpid());
1872 * Apache 2.x doesn't allow for per-child cleanup, causes CGI forks to hang.
1874 extern "C" apr_status_t shib_exit(void* data)
1880 server_rec* s = reinterpret_cast<server_rec*>(data);
1881 ap_log_error(APLOG_MARK, APLOG_INFO|APLOG_NOERRNO, SH_AP_R(s), "shib_exit: mod_shib shutdown in pid (%d)", (int)getpid());
1886 * shib_post_config()
1887 * We do the library init/term work here for 2.x to reduce overhead and
1888 * get default logging established before the fork happens.
1890 apr_status_t shib_post_config(apr_pool_t* p, apr_pool_t*, apr_pool_t*, server_rec* s)
1892 // Initialize runtime components.
1893 ap_log_error(APLOG_MARK, APLOG_INFO|APLOG_NOERRNO, SH_AP_R(s),"post_config: mod_shib initializing in pid (%d)", (int)getpid());
1896 ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(s), "post_config: mod_shib already initialized");
1900 g_Config = &SPConfig::getConfig();
1901 g_Config->setFeatures(
1902 SPConfig::Listener |
1904 SPConfig::RequestMapping |
1905 SPConfig::InProcess |
1909 if (!g_Config->init(g_szSchemaDir, g_szPrefix)) {
1910 ap_log_error(APLOG_MARK, APLOG_CRIT|APLOG_NOERRNO, SH_AP_R(s), "post_config: mod_shib failed to initialize libraries");
1913 #ifndef SHIB_APACHE_24
1914 g_Config->AccessControlManager.registerFactory(HT_ACCESS_CONTROL, &htAccessFactory);
1916 g_Config->RequestMapperManager.registerFactory(NATIVE_REQUEST_MAPPER, &ApacheRequestMapFactory);
1918 // Set the cleanup handler, passing in the server_rec for logging.
1919 apr_pool_cleanup_register(p, s, &shib_exit, apr_pool_cleanup_null);
1928 * Things to do when the child process is initialized.
1929 * We can't use post-config for all of it on 2.x because only the forking thread shows
1930 * up in the child, losing the internal threads spun up by plugins in the SP.
1932 #ifdef SHIB_APACHE_13
1933 extern "C" void shib_child_init(server_rec* s, SH_AP_POOL* p)
1935 extern "C" void shib_child_init(apr_pool_t* p, server_rec* s)
1938 // Initialize runtime components.
1940 ap_log_error(APLOG_MARK, APLOG_INFO|APLOG_NOERRNO, SH_AP_R(s),"child_init: mod_shib initializing in pid (%d)", (int)getpid());
1942 // 2.x versions have already initialized the libraries.
1943 #ifdef SHIB_APACHE_13
1945 ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(s), "child_init: mod_shib already initialized, exiting");
1949 g_Config = &SPConfig::getConfig();
1950 g_Config->setFeatures(
1951 SPConfig::Listener |
1953 SPConfig::RequestMapping |
1954 SPConfig::InProcess |
1958 if (!g_Config->init(g_szSchemaDir, g_szPrefix)) {
1959 ap_log_error(APLOG_MARK, APLOG_CRIT|APLOG_NOERRNO, SH_AP_R(s), "child_init: mod_shib failed to initialize libraries");
1962 g_Config->AccessControlManager.registerFactory(HT_ACCESS_CONTROL, &htAccessFactory);
1963 g_Config->RequestMapperManager.registerFactory(NATIVE_REQUEST_MAPPER, &ApacheRequestMapFactory);
1966 // The config gets installed for all versions here due to the background thread/fork issues.
1968 if (!g_Config->instantiate(g_szSHIBConfig, true))
1969 throw runtime_error("unknown error");
1971 catch (std::exception& ex) {
1972 ap_log_error(APLOG_MARK, APLOG_CRIT|APLOG_NOERRNO, SH_AP_R(s), "child_init: mod_shib failed to load configuration: %s", ex.what());
1977 ServiceProvider* sp = g_Config->getServiceProvider();
1978 xmltooling::Locker locker(sp);
1979 const PropertySet* props = sp->getPropertySet("InProcess");
1981 pair<bool,const char*> unsetValue = props->getString("unsetHeaderValue");
1982 if (unsetValue.first)
1983 g_unsetHeaderValue = unsetValue.second;
1984 pair<bool,bool> flag=props->getBool("checkSpoofing");
1985 g_checkSpoofing = !flag.first || flag.second;
1986 if (g_checkSpoofing) {
1987 unsetValue=props->getString("spoofKey");
1988 if (unsetValue.first)
1989 g_spoofKey = unsetValue.second;
1991 flag=props->getBool("catchAll");
1992 g_catchAll = flag.first && flag.second;
1995 // Set the cleanup handler, passing in the server_rec for logging.
1996 apr_pool_cleanup_register(p, s, &shib_exit, apr_pool_cleanup_null);
1998 ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(s), "child_init: mod_shib config initialized");
2002 #ifdef SHIB_DEFERRED_HEADERS
2003 static void set_output_filter(request_rec *r)
2005 ap_add_output_filter("SHIB_HEADERS_OUT", nullptr, r, r->connection);
2008 static void set_error_filter(request_rec *r)
2010 ap_add_output_filter("SHIB_HEADERS_ERR", nullptr, r, r->connection);
2013 static int _table_add(void *v, const char *key, const char *value)
2015 apr_table_addn((apr_table_t*)v, key, value);
2019 static apr_status_t do_output_filter(ap_filter_t *f, apr_bucket_brigade *in)
2021 request_rec *r = f->r;
2022 shib_request_config *rc = (shib_request_config*) ap_get_module_config(r->request_config, &mod_shib);
2024 if (rc && rc->hdr_out) {
2025 ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "output_filter: merging %d headers", apr_table_elts(rc->hdr_out)->nelts);
2026 // can't use overlap call because it will collapse Set-Cookie headers
2027 //apr_table_overlap(r->headers_out, rc->hdr_out, APR_OVERLAP_TABLES_MERGE);
2028 apr_table_do(_table_add,r->headers_out, rc->hdr_out,NULL);
2031 /* remove ourselves from the filter chain */
2032 ap_remove_output_filter(f);
2034 /* send the data up the stack */
2035 return ap_pass_brigade(f->next,in);
2038 static apr_status_t do_error_filter(ap_filter_t *f, apr_bucket_brigade *in)
2040 request_rec *r = f->r;
2041 shib_request_config *rc = (shib_request_config*) ap_get_module_config(r->request_config, &mod_shib);
2043 if (rc && rc->hdr_out) {
2044 ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "error_filter: merging %d headers", apr_table_elts(rc->hdr_out)->nelts);
2045 // can't use overlap call because it will collapse Set-Cookie headers
2046 //apr_table_overlap(r->err_headers_out, rc->hdr_out, APR_OVERLAP_TABLES_MERGE);
2047 apr_table_do(_table_add,r->err_headers_out, rc->hdr_out,NULL);
2050 /* remove ourselves from the filter chain */
2051 ap_remove_output_filter(f);
2053 /* send the data up the stack */
2054 return ap_pass_brigade(f->next,in);
2056 #endif // SHIB_DEFERRED_HEADERS
2058 typedef const char* (*config_fn_t)(void);
2060 #ifdef SHIB_APACHE_13
2062 // SHIB Module commands
2064 static command_rec shire_cmds[] = {
2065 {"ShibPrefix", (config_fn_t)ap_set_global_string_slot, &g_szPrefix,
2066 RSRC_CONF, TAKE1, "Shibboleth installation directory"},
2067 {"ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
2068 RSRC_CONF, TAKE1, "Path to shibboleth2.xml config file"},
2069 {"ShibCatalogs", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
2070 RSRC_CONF, TAKE1, "Paths of XML schema catalogs"},
2072 {"ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
2073 (void *) XtOffsetOf (shib_server_config, szScheme),
2074 RSRC_CONF, TAKE1, "URL scheme to force into generated URLs for a vhost"},
2076 {"ShibRequestSetting", (config_fn_t)shib_table_set, nullptr,
2077 OR_AUTHCFG, TAKE2, "Set arbitrary Shibboleth request property for content"},
2079 {"ShibAccessControl", (config_fn_t)shib_set_acl_slot, nullptr,
2080 OR_AUTHCFG, TAKE1, "Set arbitrary Shibboleth access control plugin for content"},
2082 {"ShibDisable", (config_fn_t)ap_set_flag_slot,
2083 (void *) XtOffsetOf (shib_dir_config, bOff),
2084 OR_AUTHCFG, FLAG, "Disable all Shib module activity here to save processing effort"},
2085 {"ShibApplicationId", (config_fn_t)ap_set_string_slot,
2086 (void *) XtOffsetOf (shib_dir_config, szApplicationId),
2087 OR_AUTHCFG, TAKE1, "Set Shibboleth applicationId property for content"},
2088 {"ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
2089 (void *) XtOffsetOf (shib_dir_config, bBasicHijack),
2090 OR_AUTHCFG, FLAG, "(DEPRECATED) Respond to AuthType Basic and convert to shibboleth"},
2091 {"ShibRequireSession", (config_fn_t)ap_set_flag_slot,
2092 (void *) XtOffsetOf (shib_dir_config, bRequireSession),
2093 OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist"},
2094 {"ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
2095 (void *) XtOffsetOf (shib_dir_config, szRequireWith),
2096 OR_AUTHCFG, TAKE1, "Initiates a new session if one does not exist using a specific SessionInitiator"},
2097 {"ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
2098 (void *) XtOffsetOf (shib_dir_config, bExportAssertion),
2099 OR_AUTHCFG, FLAG, "Export SAML attribute assertion(s) to Shib-Attributes header"},
2100 {"ShibRedirectToSSL", (config_fn_t)ap_set_string_slot,
2101 (void *) XtOffsetOf (shib_dir_config, szRedirectToSSL),
2102 OR_AUTHCFG, TAKE1, "Redirect non-SSL requests to designated port" },
2103 {"AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
2104 (void *) XtOffsetOf (shib_dir_config, szAuthGrpFile),
2105 OR_AUTHCFG, TAKE1, "text file containing group names and member user IDs"},
2106 {"ShibRequireAll", (config_fn_t)ap_set_flag_slot,
2107 (void *) XtOffsetOf (shib_dir_config, bRequireAll),
2108 OR_AUTHCFG, FLAG, "All require directives must match"},
2109 {"AuthzShibAuthoritative", (config_fn_t)ap_set_flag_slot,
2110 (void *) XtOffsetOf (shib_dir_config, bAuthoritative),
2111 OR_AUTHCFG, FLAG, "Allow failed mod_shib htaccess authorization to fall through to other modules"},
2112 {"ShibCompatWith24", (config_fn_t)ap_set_flag_slot,
2113 (void *) XtOffsetOf (shib_dir_config, bCompatWith24),
2114 OR_AUTHCFG, FLAG, "Support Apache 2.4-style require rules"},
2115 {"ShibUseEnvironment", (config_fn_t)ap_set_flag_slot,
2116 (void *) XtOffsetOf (shib_dir_config, bUseEnvVars),
2117 OR_AUTHCFG, FLAG, "Export attributes using environment variables (default)"},
2118 {"ShibUseHeaders", (config_fn_t)ap_set_flag_slot,
2119 (void *) XtOffsetOf (shib_dir_config, bUseHeaders),
2120 OR_AUTHCFG, FLAG, "Export attributes using custom HTTP headers"},
2121 {"ShibExpireRedirects", (config_fn_t)ap_set_flag_slot,
2122 (void *) XtOffsetOf (shib_dir_config, bExpireRedirects),
2123 OR_AUTHCFG, FLAG, "Expire SP-generated redirects"},
2129 handler_rec shib_handlers[] = {
2130 { "shib-handler", shib_handler },
2134 module MODULE_VAR_EXPORT mod_shib = {
2135 STANDARD_MODULE_STUFF,
2136 nullptr, /* initializer */
2137 create_shib_dir_config, /* dir config creater */
2138 merge_shib_dir_config, /* dir merger --- default is to override */
2139 create_shib_server_config, /* server config */
2140 merge_shib_server_config, /* merge server config */
2141 shire_cmds, /* command table */
2142 shib_handlers, /* handlers */
2143 nullptr, /* filename translation */
2144 shib_check_user, /* check_user_id */
2145 shib_auth_checker, /* check auth */
2146 nullptr, /* check access */
2147 nullptr, /* type_checker */
2148 shib_fixups, /* fixups */
2149 nullptr, /* logger */
2150 nullptr, /* header parser */
2151 shib_child_init, /* child_init */
2152 shib_child_exit, /* child_exit */
2153 shib_post_read /* post read-request */
2158 #ifdef SHIB_APACHE_24
2159 extern "C" const authz_provider shib_authz_shibboleth_provider = { &shib_shibboleth_check_authz, nullptr };
2160 extern "C" const authz_provider shib_authz_validuser_provider = { &shib_validuser_check_authz, nullptr };
2161 extern "C" const authz_provider shib_authz_session_provider = { &shib_session_check_authz, nullptr };
2162 extern "C" const authz_provider shib_authz_user_provider = { &shib_user_check_authz, nullptr };
2163 extern "C" const authz_provider shib_authz_ext_user_provider = { &shib_ext_user_check_authz, nullptr };
2164 extern "C" const authz_provider shib_authz_acclass_provider = { &shib_acclass_check_authz, nullptr };
2165 extern "C" const authz_provider shib_authz_acdecl_provider = { &shib_acdecl_check_authz, nullptr };
2166 extern "C" const authz_provider shib_authz_attr_provider = { &shib_attr_check_authz, nullptr };
2167 extern "C" const authz_provider shib_authz_plugin_provider = { &shib_plugin_check_authz, nullptr };
2170 extern "C" void shib_register_hooks (apr_pool_t *p)
2172 #ifdef SHIB_DEFERRED_HEADERS
2173 ap_register_output_filter("SHIB_HEADERS_OUT", do_output_filter, nullptr, AP_FTYPE_CONTENT_SET);
2174 ap_hook_insert_filter(set_output_filter, nullptr, nullptr, APR_HOOK_LAST);
2175 ap_register_output_filter("SHIB_HEADERS_ERR", do_error_filter, nullptr, AP_FTYPE_CONTENT_SET);
2176 ap_hook_insert_error_filter(set_error_filter, nullptr, nullptr, APR_HOOK_LAST);
2177 ap_hook_post_read_request(shib_post_read, nullptr, nullptr, APR_HOOK_MIDDLE);
2179 ap_hook_post_config(shib_post_config, nullptr, nullptr, APR_HOOK_MIDDLE);
2180 ap_hook_child_init(shib_child_init, nullptr, nullptr, APR_HOOK_MIDDLE);
2181 const char* prereq = getenv("SHIBSP_APACHE_PREREQ");
2182 #ifdef SHIB_APACHE_24
2183 if (prereq && *prereq) {
2184 const char* const authnPre[] = { prereq, nullptr };
2185 ap_hook_check_authn(shib_check_user, authnPre, nullptr, APR_HOOK_MIDDLE, AP_AUTH_INTERNAL_PER_URI);
2188 ap_hook_check_authn(shib_check_user, nullptr, nullptr, APR_HOOK_MIDDLE, AP_AUTH_INTERNAL_PER_URI);
2190 ap_hook_check_authz(shib_auth_checker, nullptr, nullptr, APR_HOOK_FIRST, AP_AUTH_INTERNAL_PER_URI);
2192 if (prereq && *prereq) {
2193 const char* const authnPre[] = { prereq, nullptr };
2194 ap_hook_check_user_id(shib_check_user, authnPre, nullptr, APR_HOOK_MIDDLE);
2197 ap_hook_check_user_id(shib_check_user, nullptr, nullptr, APR_HOOK_MIDDLE);
2199 ap_hook_auth_checker(shib_auth_checker, nullptr, nullptr, APR_HOOK_FIRST);
2201 ap_hook_handler(shib_handler, nullptr, nullptr, APR_HOOK_LAST);
2202 ap_hook_fixups(shib_fixups, nullptr, nullptr, APR_HOOK_MIDDLE);
2204 #ifdef SHIB_APACHE_24
2205 ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "shibboleth", AUTHZ_PROVIDER_VERSION, &shib_authz_shibboleth_provider, AP_AUTH_INTERNAL_PER_CONF);
2206 ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "valid-user", AUTHZ_PROVIDER_VERSION, &shib_authz_validuser_provider, AP_AUTH_INTERNAL_PER_CONF);
2207 ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "shib-session", AUTHZ_PROVIDER_VERSION, &shib_authz_session_provider, AP_AUTH_INTERNAL_PER_CONF);
2208 ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "user", AUTHZ_PROVIDER_VERSION, &shib_authz_user_provider, AP_AUTH_INTERNAL_PER_CONF);
2209 ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "shib-user", AUTHZ_PROVIDER_VERSION, &shib_authz_ext_user_provider, AP_AUTH_INTERNAL_PER_CONF);
2210 ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "authnContextClassRef", AUTHZ_PROVIDER_VERSION, &shib_authz_acclass_provider, AP_AUTH_INTERNAL_PER_CONF);
2211 ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "authnContextDeclRef", AUTHZ_PROVIDER_VERSION, &shib_authz_acdecl_provider, AP_AUTH_INTERNAL_PER_CONF);
2212 ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "shib-attr", AUTHZ_PROVIDER_VERSION, &shib_authz_attr_provider, AP_AUTH_INTERNAL_PER_CONF);
2213 ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "shib-plugin", AUTHZ_PROVIDER_VERSION, &shib_authz_plugin_provider, AP_AUTH_INTERNAL_PER_CONF);
2217 // SHIB Module commands
2220 static command_rec shib_cmds[] = {
2221 AP_INIT_TAKE1("ShibPrefix", (config_fn_t)ap_set_global_string_slot, &g_szPrefix,
2222 RSRC_CONF, "Shibboleth installation directory"),
2223 AP_INIT_TAKE1("ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
2224 RSRC_CONF, "Path to shibboleth2.xml config file"),
2225 AP_INIT_TAKE1("ShibCatalogs", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
2226 RSRC_CONF, "Paths of XML schema catalogs"),
2227 AP_INIT_TAKE1("ShibGSSKey", (config_fn_t)ap_set_global_string_slot, &g_szGSSContextKey,
2228 RSRC_CONF, "Name of user data key containing GSS context established by GSS module"),
2230 AP_INIT_TAKE1("ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
2231 (void *) offsetof (shib_server_config, szScheme),
2232 RSRC_CONF, "URL scheme to force into generated URLs for a vhost"),
2234 AP_INIT_TAKE2("ShibRequestSetting", (config_fn_t)shib_table_set, nullptr,
2235 OR_AUTHCFG, "Set arbitrary Shibboleth request property for content"),
2237 AP_INIT_FLAG("ShibDisable", (config_fn_t)ap_set_flag_slot,
2238 (void *) offsetof (shib_dir_config, bOff),
2239 OR_AUTHCFG, "Disable all Shib module activity here to save processing effort"),
2240 AP_INIT_TAKE1("ShibApplicationId", (config_fn_t)ap_set_string_slot,
2241 (void *) offsetof (shib_dir_config, szApplicationId),
2242 OR_AUTHCFG, "Set Shibboleth applicationId property for content"),
2243 AP_INIT_FLAG("ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
2244 (void *) offsetof (shib_dir_config, bBasicHijack),
2245 OR_AUTHCFG, "(DEPRECATED) Respond to AuthType Basic and convert to shibboleth"),
2246 AP_INIT_FLAG("ShibRequireSession", (config_fn_t)ap_set_flag_slot,
2247 (void *) offsetof (shib_dir_config, bRequireSession),
2248 OR_AUTHCFG, "Initiates a new session if one does not exist"),
2249 AP_INIT_TAKE1("ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
2250 (void *) offsetof (shib_dir_config, szRequireWith),
2251 OR_AUTHCFG, "Initiates a new session if one does not exist using a specific SessionInitiator"),
2252 AP_INIT_FLAG("ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
2253 (void *) offsetof (shib_dir_config, bExportAssertion),
2254 OR_AUTHCFG, "Export SAML attribute assertion(s) to Shib-Attributes header"),
2255 AP_INIT_TAKE1("ShibRedirectToSSL", (config_fn_t)ap_set_string_slot,
2256 (void *) offsetof (shib_dir_config, szRedirectToSSL),
2257 OR_AUTHCFG, "Redirect non-SSL requests to designated port"),
2258 #ifdef SHIB_APACHE_24
2259 AP_INIT_FLAG("ShibRequestMapperAuthz", (config_fn_t)ap_set_flag_slot,
2260 (void *) offsetof (shib_dir_config, bRequestMapperAuthz),
2261 OR_AUTHCFG, "Support access control via shibboleth2.xml / RequestMapper"),
2262 AP_INIT_FLAG("ShibCompatValidUser", (config_fn_t)shib_set_server_flag_slot,
2263 (void *) offsetof (shib_server_config, bCompatValidUser),
2264 RSRC_CONF, "Handle 'require valid-user' in mod_authz_user-compatible fashion (requiring username)"),
2266 AP_INIT_TAKE1("AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
2267 (void *) offsetof (shib_dir_config, szAuthGrpFile),
2268 OR_AUTHCFG, "Text file containing group names and member user IDs"),
2269 AP_INIT_TAKE1("ShibAccessControl", (config_fn_t)shib_set_acl_slot, nullptr,
2270 OR_AUTHCFG, "Set arbitrary Shibboleth access control plugin for content"),
2271 AP_INIT_FLAG("ShibRequireAll", (config_fn_t)ap_set_flag_slot,
2272 (void *) offsetof (shib_dir_config, bRequireAll),
2273 OR_AUTHCFG, "All require directives must match"),
2274 AP_INIT_FLAG("AuthzShibAuthoritative", (config_fn_t)ap_set_flag_slot,
2275 (void *) offsetof (shib_dir_config, bAuthoritative),
2276 OR_AUTHCFG, "Allow failed mod_shib htaccess authorization to fall through to other modules"),
2277 AP_INIT_FLAG("ShibCompatWith24", (config_fn_t)ap_set_flag_slot,
2278 (void *) offsetof (shib_dir_config, bCompatWith24),
2279 OR_AUTHCFG, "Support Apache 2.4-style require rules"),
2281 AP_INIT_FLAG("ShibUseEnvironment", (config_fn_t)ap_set_flag_slot,
2282 (void *) offsetof (shib_dir_config, bUseEnvVars),
2283 OR_AUTHCFG, "Export attributes using environment variables (default)"),
2284 AP_INIT_FLAG("ShibUseHeaders", (config_fn_t)ap_set_flag_slot,
2285 (void *) offsetof (shib_dir_config, bUseHeaders),
2286 OR_AUTHCFG, "Export attributes using custom HTTP headers"),
2287 AP_INIT_FLAG("ShibExpireRedirects", (config_fn_t)ap_set_flag_slot,
2288 (void *) offsetof (shib_dir_config, bExpireRedirects),
2289 OR_AUTHCFG, "Expire SP-generated redirects"),
2294 module AP_MODULE_DECLARE_DATA mod_shib = {
2295 STANDARD20_MODULE_STUFF,
2296 create_shib_dir_config, /* create dir config */
2297 merge_shib_dir_config, /* merge dir config --- default is to override */
2298 create_shib_server_config, /* create server config */
2299 merge_shib_server_config, /* merge server config */
2300 shib_cmds, /* command table */
2301 shib_register_hooks /* register hooks */