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
141 // creates the per-server configuration
142 extern "C" void* create_shib_server_config(SH_AP_POOL* p, server_rec* s)
144 shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
145 sc->szScheme = nullptr;
149 // overrides server configuration in virtual servers
150 extern "C" void* merge_shib_server_config (SH_AP_POOL* p, void* base, void* sub)
152 shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
153 shib_server_config* parent=(shib_server_config*)base;
154 shib_server_config* child=(shib_server_config*)sub;
157 sc->szScheme=ap_pstrdup(p,child->szScheme);
158 else if (parent->szScheme)
159 sc->szScheme=ap_pstrdup(p,parent->szScheme);
161 sc->szScheme=nullptr;
166 // per-dir module configuration structure
167 struct shib_dir_config
169 SH_AP_TABLE* tSettings; // generic table of extensible settings
172 #ifdef SHIB_APACHE_24
173 int bRequestMapperAuthz;// support RequestMapper AccessControl plugins
175 char* szAuthGrpFile; // Auth GroupFile name
176 char* szAccessControl; // path to "external" AccessControl plugin file
177 int bRequireAll; // all "known" require directives must match, otherwise OR logic
178 int bAuthoritative; // allow htaccess plugin to DECLINE when authz fails
179 int bCompatWith24; // support 2.4-reserved require logic for compatibility
182 // Content Configuration
183 char* szApplicationId; // Shib applicationId value
184 char* szRequireWith; // require a session using a specific initiator?
185 char* szRedirectToSSL; // redirect non-SSL requests to SSL port
186 int bOff; // flat-out disable all Shib processing
187 int bBasicHijack; // activate for AuthType Basic?
188 int bRequireSession; // require a session?
189 int bExportAssertion; // export SAML assertion to the environment?
190 int bUseEnvVars; // use environment?
191 int bUseHeaders; // use headers?
192 int bExpireRedirects; // expire redirects?
195 // creates per-directory config structure
196 extern "C" void* create_shib_dir_config (SH_AP_POOL* p, char* d)
198 shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
199 dc->tSettings = nullptr;
200 #ifdef SHIB_APACHE_24
201 dc->bRequestMapperAuthz = -1;
203 dc->szAuthGrpFile = nullptr;
204 dc->szAccessControl = nullptr;
205 dc->bRequireAll = -1;
206 dc->bAuthoritative = -1;
207 dc->bCompatWith24 = -1;
209 dc->szApplicationId = nullptr;
210 dc->szRequireWith = nullptr;
211 dc->szRedirectToSSL = nullptr;
213 dc->bBasicHijack = -1;
214 dc->bRequireSession = -1;
215 dc->bExportAssertion = -1;
216 dc->bUseEnvVars = -1;
217 dc->bUseHeaders = -1;
218 dc->bExpireRedirects = -1;
222 // overrides server configuration in directories
223 extern "C" void* merge_shib_dir_config (SH_AP_POOL* p, void* base, void* sub)
225 shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
226 shib_dir_config* parent=(shib_dir_config*)base;
227 shib_dir_config* child=(shib_dir_config*)sub;
229 // The child supersedes any matching table settings in the parent.
230 dc->tSettings = nullptr;
231 if (parent->tSettings)
232 dc->tSettings = ap_copy_table(p, parent->tSettings);
233 if (child->tSettings) {
235 ap_overlap_tables(dc->tSettings, child->tSettings, AP_OVERLAP_TABLES_SET);
237 dc->tSettings = ap_copy_table(p, child->tSettings);
240 #ifdef SHIB_APACHE_24
241 dc->bRequestMapperAuthz = ((child->bRequestMapperAuthz==-1) ? parent->bRequestMapperAuthz : child->bRequestMapperAuthz);
243 if (child->szAuthGrpFile)
244 dc->szAuthGrpFile=ap_pstrdup(p,child->szAuthGrpFile);
245 else if (parent->szAuthGrpFile)
246 dc->szAuthGrpFile=ap_pstrdup(p,parent->szAuthGrpFile);
248 dc->szAuthGrpFile=nullptr;
250 if (child->szAccessControl)
251 dc->szAccessControl=ap_pstrdup(p,child->szAccessControl);
252 else if (parent->szAccessControl)
253 dc->szAccessControl=ap_pstrdup(p,parent->szAccessControl);
255 dc->szAccessControl=nullptr;
258 if (child->szApplicationId)
259 dc->szApplicationId=ap_pstrdup(p,child->szApplicationId);
260 else if (parent->szApplicationId)
261 dc->szApplicationId=ap_pstrdup(p,parent->szApplicationId);
263 dc->szApplicationId=nullptr;
265 if (child->szRequireWith)
266 dc->szRequireWith=ap_pstrdup(p,child->szRequireWith);
267 else if (parent->szRequireWith)
268 dc->szRequireWith=ap_pstrdup(p,parent->szRequireWith);
270 dc->szRequireWith=nullptr;
272 if (child->szRedirectToSSL)
273 dc->szRedirectToSSL=ap_pstrdup(p,child->szRedirectToSSL);
274 else if (parent->szRedirectToSSL)
275 dc->szRedirectToSSL=ap_pstrdup(p,parent->szRedirectToSSL);
277 dc->szRedirectToSSL=nullptr;
279 dc->bOff = ((child->bOff==-1) ? parent->bOff : child->bOff);
280 dc->bBasicHijack = ((child->bBasicHijack==-1) ? parent->bBasicHijack : child->bBasicHijack);
281 dc->bRequireSession = ((child->bRequireSession==-1) ? parent->bRequireSession : child->bRequireSession);
282 dc->bExportAssertion = ((child->bExportAssertion==-1) ? parent->bExportAssertion : child->bExportAssertion);
283 #ifndef SHIB_APACHE_24
284 dc->bRequireAll = ((child->bRequireAll==-1) ? parent->bRequireAll : child->bRequireAll);
285 dc->bAuthoritative = ((child->bAuthoritative==-1) ? parent->bAuthoritative : child->bAuthoritative);
286 dc->bCompatWith24 = ((child->bCompatWith24==-1) ? parent->bCompatWith24 : child->bCompatWith24);
288 dc->bUseEnvVars = ((child->bUseEnvVars==-1) ? parent->bUseEnvVars : child->bUseEnvVars);
289 dc->bUseHeaders = ((child->bUseHeaders==-1) ? parent->bUseHeaders : child->bUseHeaders);
290 dc->bExpireRedirects = ((child->bExpireRedirects==-1) ? parent->bExpireRedirects : child->bExpireRedirects);
294 class ShibTargetApache; // forward decl
296 // per-request module structure
297 struct shib_request_config
299 SH_AP_TABLE* env; // environment vars
300 #ifdef SHIB_DEFERRED_HEADERS
301 SH_AP_TABLE* hdr_out; // headers to browser
303 #ifndef SHIB_APACHE_13
304 ShibTargetApache* sta; // SP per-request structure wrapped around Apache's request
308 // create or return a request record
309 static shib_request_config* get_request_config(request_rec *r)
311 shib_request_config* rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
313 ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "get_request_config called redundantly");
316 ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "get_request_config created per-request structure");
317 rc = (shib_request_config*)ap_pcalloc(r->pool,sizeof(shib_request_config));
318 memset(rc, 0, sizeof(shib_request_config));
319 ap_set_module_config(r->request_config, &mod_shib, rc);
324 class ShibTargetApache : public AbstractSPRequest
325 #if defined(SHIBSP_HAVE_GSSAPI) && !defined(SHIB_APACHE_13)
329 mutable string m_body;
330 mutable bool m_gotBody,m_firsttime;
331 mutable vector<string> m_certs;
332 set<string> m_allhttp;
333 #if defined(SHIBSP_HAVE_GSSAPI) && !defined(SHIB_APACHE_13)
334 mutable gss_name_t m_gssname;
340 shib_dir_config* m_dc;
341 shib_server_config* m_sc;
342 shib_request_config* m_rc;
344 ShibTargetApache(request_rec* req) : AbstractSPRequest(SHIBSP_LOGCAT".Apache"),
345 m_gotBody(false),m_firsttime(true),
346 #if defined(SHIBSP_HAVE_GSSAPI) && !defined(SHIB_APACHE_13)
347 m_gssname(GSS_C_NO_NAME),
349 m_handler(false), m_req(req), m_dc(nullptr), m_sc(nullptr), m_rc(nullptr) {
351 virtual ~ShibTargetApache() {
352 #if defined(SHIBSP_HAVE_GSSAPI) && !defined(SHIB_APACHE_13)
353 if (m_gssname != GSS_C_NO_NAME) {
355 gss_release_name(&minor, &m_gssname);
360 bool isInitialized() const {
361 return (m_sc != nullptr);
364 bool init(bool handler, bool check_user) {
367 return !check_user; // only initialize once
368 m_sc = (shib_server_config*)ap_get_module_config(m_req->server->module_config, &mod_shib);
369 m_dc = (shib_dir_config*)ap_get_module_config(m_req->per_dir_config, &mod_shib);
370 m_rc = (shib_request_config*)ap_get_module_config(m_req->request_config, &mod_shib);
372 setRequestURI(m_req->unparsed_uri);
374 if (check_user && m_dc->bUseHeaders == 1) {
375 // Try and see if this request was already processed, to skip spoof checking.
376 if (!ap_is_initial_req(m_req)) {
379 else if (!g_spoofKey.empty()) {
380 const char* hdr = ap_table_get(m_req->headers_in, "Shib-Spoof-Check");
381 if (hdr && g_spoofKey == hdr)
385 log(SPDebug, "shib_check_user running more than once");
390 const char* getScheme() const {
391 return m_sc->szScheme ? m_sc->szScheme : ap_http_method(m_req);
393 bool isSecure() const {
394 return HTTPRequest::isSecure();
396 const char* getHostname() const {
397 #ifdef SHIB_APACHE_24
398 return ap_get_server_name_for_url(m_req);
400 return ap_get_server_name(m_req);
403 int getPort() const {
404 return ap_get_server_port(m_req);
406 const char* getMethod() const {
407 return m_req->method;
409 string getContentType() const {
410 const char* type = ap_table_get(m_req->headers_in, "Content-Type");
411 return type ? type : "";
413 long getContentLength() const {
414 return m_gotBody ? m_body.length() : m_req->remaining;
416 string getRemoteAddr() const {
417 string ret = AbstractSPRequest::getRemoteAddr();
420 #ifdef SHIB_APACHE_24
421 return m_req->useragent_ip;
423 return m_req->connection->remote_ip;
426 void log(SPLogLevel level, const string& msg) const {
427 AbstractSPRequest::log(level,msg);
430 (level == SPDebug ? APLOG_DEBUG :
431 (level == SPInfo ? APLOG_INFO :
432 (level == SPWarn ? APLOG_WARNING :
433 (level == SPError ? APLOG_ERR : APLOG_CRIT))))|APLOG_NOERRNO,
439 const char* getQueryString() const { return m_req->args; }
440 const char* getRequestBody() const {
441 if (m_gotBody || m_req->method_number==M_GET)
442 return m_body.c_str();
443 #ifdef SHIB_APACHE_13
444 // Read the posted data
445 if (ap_setup_client_block(m_req, REQUEST_CHUNKED_DECHUNK) != OK) {
447 log(SPError, "Apache function (setup_client_block) failed while reading request body.");
448 return m_body.c_str();
450 if (!ap_should_client_block(m_req)) {
452 log(SPError, "Apache function (should_client_block) failed while reading request body.");
453 return m_body.c_str();
455 if (m_req->remaining > 1024*1024)
456 throw opensaml::SecurityPolicyException("Blocked request body larger than 1M size limit.");
459 char buff[HUGE_STRING_LEN];
460 ap_hard_timeout("[mod_shib] getRequestBody", m_req);
461 while ((len=ap_get_client_block(m_req, buff, sizeof(buff))) > 0) {
462 ap_reset_timeout(m_req);
463 m_body.append(buff, len);
465 ap_kill_timeout(m_req);
470 apr_bucket_brigade* bb = apr_brigade_create(m_req->pool, m_req->connection->bucket_alloc);
473 apr_status_t rv = ap_get_brigade(m_req->input_filters, bb, AP_MODE_READBYTES, APR_BLOCK_READ, HUGE_STRING_LEN);
474 if (rv != APR_SUCCESS) {
475 log(SPError, "Apache function (ap_get_brigade) failed while reading request body.");
479 for (bucket = APR_BRIGADE_FIRST(bb); bucket != APR_BRIGADE_SENTINEL(bb); bucket = APR_BUCKET_NEXT(bucket)) {
480 if (APR_BUCKET_IS_EOS(bucket)) {
485 /* We can't do much with this. */
486 if (APR_BUCKET_IS_FLUSH(bucket))
490 apr_bucket_read(bucket, &data, &len, APR_BLOCK_READ);
492 m_body.append(data, len);
494 apr_brigade_cleanup(bb);
496 apr_brigade_destroy(bb);
499 return m_body.c_str();
501 const char* getParameter(const char* name) const {
502 return AbstractSPRequest::getParameter(name);
504 vector<const char*>::size_type getParameters(const char* name, vector<const char*>& values) const {
505 return AbstractSPRequest::getParameters(name, values);
507 void clearHeader(const char* rawname, const char* cginame) {
508 if (m_dc->bUseHeaders == 1) {
509 // ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_clear_header: hdr\n");
510 if (g_checkSpoofing && m_firsttime) {
511 if (m_allhttp.empty()) {
512 // First time, so populate set with "CGI" versions of client-supplied headers.
513 #ifdef SHIB_APACHE_13
514 array_header *hdrs_arr = ap_table_elts(m_req->headers_in);
515 table_entry *hdrs = (table_entry *) hdrs_arr->elts;
517 const apr_array_header_t *hdrs_arr = apr_table_elts(m_req->headers_in);
518 const apr_table_entry_t *hdrs = (const apr_table_entry_t *) hdrs_arr->elts;
520 for (int i = 0; i < hdrs_arr->nelts; ++i) {
523 string cgiversion("HTTP_");
524 const char* pch = hdrs[i].key;
526 cgiversion += (isalnum(*pch) ? toupper(*pch) : '_');
529 m_allhttp.insert(cgiversion);
533 if (m_allhttp.count(cginame) > 0)
534 throw opensaml::SecurityPolicyException("Attempt to spoof header ($1) was detected.", params(1, rawname));
536 ap_table_unset(m_req->headers_in, rawname);
537 ap_table_set(m_req->headers_in, rawname, g_unsetHeaderValue.c_str());
540 void setHeader(const char* name, const char* value) {
541 if (m_dc->bUseEnvVars != 0) {
543 // this happens on subrequests
544 // ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_setheader: no_m_rc\n");
545 m_rc = get_request_config(m_req);
548 m_rc->env = ap_make_table(m_req->pool, 10);
549 // ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_set_env: %s=%s\n", name, value?value:"Null");
550 ap_table_set(m_rc->env, name, value ? value : "");
552 if (m_dc->bUseHeaders == 1)
553 ap_table_set(m_req->headers_in, name, value);
555 string getHeader(const char* name) const {
556 const char* hdr = ap_table_get(m_req->headers_in, name);
557 return string(hdr ? hdr : "");
559 string getSecureHeader(const char* name) const {
560 if (m_dc->bUseEnvVars != 0) {
562 if (m_rc && m_rc->env)
563 hdr = ap_table_get(m_rc->env, name);
566 return string(hdr ? hdr : "");
568 return getHeader(name);
570 void setRemoteUser(const char* user) {
571 SH_AP_USER(m_req) = user ? ap_pstrdup(m_req->pool, user) : nullptr;
572 if (m_dc->bUseHeaders == 1) {
574 ap_table_set(m_req->headers_in, "REMOTE_USER", user);
577 ap_table_unset(m_req->headers_in, "REMOTE_USER");
578 ap_table_set(m_req->headers_in, "REMOTE_USER", g_unsetHeaderValue.c_str());
582 string getRemoteUser() const {
583 return string(SH_AP_USER(m_req) ? SH_AP_USER(m_req) : "");
585 void setAuthType(const char* authtype) {
586 if (authtype && m_dc->bBasicHijack == 1)
588 SH_AP_AUTH_TYPE(m_req) = authtype ? ap_pstrdup(m_req->pool, authtype) : nullptr;
590 string getAuthType() const {
591 return string(SH_AP_AUTH_TYPE(m_req) ? SH_AP_AUTH_TYPE(m_req) : "");
593 void setContentType(const char* type) {
594 m_req->content_type = ap_psprintf(m_req->pool, "%s", type);
596 void setResponseHeader(const char* name, const char* value) {
597 HTTPResponse::setResponseHeader(name, value);
598 #ifdef SHIB_DEFERRED_HEADERS
600 // this happens on subrequests
601 m_rc = get_request_config(m_req);
604 m_rc->hdr_out = ap_make_table(m_req->pool, 5);
605 ap_table_add(m_rc->hdr_out, name, value);
609 ap_table_add(m_req->err_headers_out, name, value);
611 long sendResponse(istream& in, long status) {
612 if (status != XMLTOOLING_HTTP_STATUS_OK)
613 m_req->status = status;
614 ap_send_http_header(m_req);
618 ap_rwrite(buf,in.gcount(),m_req);
620 #if (defined(SHIB_APACHE_20) || defined(SHIB_APACHE_22) || defined(SHIB_APACHE_24))
621 if (status != XMLTOOLING_HTTP_STATUS_OK && status != XMLTOOLING_HTTP_STATUS_ERROR)
626 long sendRedirect(const char* url) {
627 HTTPResponse::sendRedirect(url);
628 ap_table_set(m_req->headers_out, "Location", url);
629 if (m_dc->bExpireRedirects != 0) {
630 ap_table_set(m_req->err_headers_out, "Expires", "Wed, 01 Jan 1997 12:00:00 GMT");
631 ap_table_set(m_req->err_headers_out, "Cache-Control", "private,no-store,no-cache,max-age=0");
635 const vector<string>& getClientCertificates() const {
636 if (m_certs.empty()) {
637 const char* cert = ap_table_get(m_req->subprocess_env, "SSL_CLIENT_CERT");
639 m_certs.push_back(cert);
642 cert = ap_table_get(m_req->subprocess_env, ap_psprintf(m_req->pool, "SSL_CLIENT_CERT_CHAIN_%d", i++));
644 m_certs.push_back(cert);
649 long returnDecline(void) { return DECLINED; }
650 long returnOK(void) { return OK; }
651 #if defined(SHIBSP_HAVE_GSSAPI) && !defined(SHIB_APACHE_13)
652 gss_ctx_id_t getGSSContext() const {
653 gss_ctx_id_t ctx = GSS_C_NO_CONTEXT;
654 apr_pool_userdata_get((void**)&ctx, g_szGSSContextKey, m_req->pool);
657 gss_name_t getGSSName() const {
658 if (m_gssname == GSS_C_NO_NAME) {
659 gss_ctx_id_t ctx = getGSSContext();
660 if (ctx != GSS_C_NO_CONTEXT) {
662 OM_uint32 major = gss_inquire_context(&minor, ctx, &m_gssname, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr);
663 if (major != GSS_S_COMPLETE)
664 m_gssname = GSS_C_NO_NAME;
672 /********************************************************************************/
675 #ifndef SHIB_APACHE_13
676 extern "C" apr_status_t shib_request_cleanup(void* rc)
678 if (rc && reinterpret_cast<shib_request_config*>(rc)->sta) {
679 delete reinterpret_cast<ShibTargetApache*>(reinterpret_cast<shib_request_config*>(rc)->sta);
680 reinterpret_cast<shib_request_config*>(rc)->sta = nullptr;
686 // Initial look at a request - create the per-request structure if need be
687 static int shib_post_read(request_rec *r)
689 shib_request_config* rc = get_request_config(r);
690 #ifdef SHIB_APACHE_24
692 rc->sta = new ShibTargetApache(r);
693 apr_pool_cleanup_register(r->pool, rc, shib_request_cleanup, apr_pool_cleanup_null);
699 // Performs authentication and enforce session requirements.
700 // Also does header/env export from session, and will dispatch
701 // SP handler requests if it detects a handler URL.
702 extern "C" int shib_check_user(request_rec* r)
704 // Short-circuit entirely?
705 if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff == 1)
708 ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user entered in pid (%d)", (int)getpid());
710 string threadid("[");
711 threadid += lexical_cast<string>(getpid()) + "] shib_check_user";
712 xmltooling::NDC ndc(threadid.c_str());
715 #ifndef SHIB_APACHE_24
716 ShibTargetApache sta(r);
717 ShibTargetApache* psta = &sta;
719 shib_request_config* rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
720 if (!rc || !rc->sta) {
721 ap_log_rerror(APLOG_MARK, APLOG_INFO|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user found no per-request structure");
722 shib_post_read(r); // ensures objects are created if post_read hook didn't run
723 rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
725 ShibTargetApache* psta = rc->sta;
727 if (!psta->init(false, true)) {
728 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user unable to initialize SP request object");
732 // Check user authentication and export information, then set the handler bypass
733 pair<bool,long> res = psta->getServiceProvider().doAuthentication(*psta, true);
734 apr_pool_userdata_setn((const void*)42,g_UserDataKey,nullptr,r->pool);
735 // If directed, install a spoof key to recognize when we've already cleared headers.
736 if (!g_spoofKey.empty() && (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bUseHeaders == 1))
737 ap_table_set(r->headers_in, "Shib-Spoof-Check", g_spoofKey.c_str());
739 #ifdef SHIB_APACHE_24
740 // This is insane, but Apache's internal request.c logic insists that an auth module
741 // returning OK MUST set r->user to avoid a failure. But they check for NULL and not
742 // for an empty string. If this turns out to cause trouble, there's no solution except
743 // to set a dummy ID any time it's not set.
744 if (res.second == OK && !r->user)
750 // user auth was okay -- export the session data now
751 res = psta->getServiceProvider().doExport(*psta);
753 #ifdef SHIB_APACHE_24
754 // See above for explanation of this hack.
755 if (res.second == OK && !r->user)
761 #ifdef SHIB_APACHE_24
762 // See above for explanation of this hack.
768 catch (std::exception& e) {
769 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user threw an exception: %s", e.what());
773 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user threw an unknown exception!");
780 // Runs SP handler requests when invoked directly.
781 extern "C" int shib_handler(request_rec* r)
783 // Short-circuit entirely?
784 if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff == 1)
787 string threadid("[");
788 threadid += lexical_cast<string>(getpid()) + "] shib_handler";
789 xmltooling::NDC ndc(threadid.c_str());
791 #ifndef SHIB_APACHE_13
792 // With 2.x, this handler always runs, though last.
793 // We check if shib_check_user ran, because it will detect a handler request
794 // and dispatch it directly.
796 apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
797 if (data==(const void*)42) {
798 ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "shib_handler skipped since check_user ran");
803 ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "shib_handler entered in pid (%d): %s", (int)getpid(), r->handler);
806 #ifndef SHIB_APACHE_24
807 ShibTargetApache sta(r);
808 ShibTargetApache* psta = &sta;
810 shib_request_config* rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
811 if (!rc || !rc->sta) {
812 ap_log_rerror(APLOG_MARK, APLOG_INFO|APLOG_NOERRNO, SH_AP_R(r), "shib_handler found no per-request structure");
813 shib_post_read(r); // ensures objects are created if post_read hook didn't run
814 rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
816 ShibTargetApache* psta = rc->sta;
818 if (!psta->init(true, false)) {
819 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler unable to initialize SP request object");
823 pair<bool,long> res = psta->getServiceProvider().doHandler(*psta);
824 if (res.first) return res.second;
826 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "doHandler() did not handle the request");
829 catch (std::exception& e) {
830 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler threw an exception: %s", e.what());
834 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler threw an unknown exception!");
841 // This performs authorization functions to limit access.
842 // On all versions, this runs any RequestMap-attached plugins.
843 // For pre-2.4 versions, the RequestMap will always find an htAccess plugin
844 // that runs code to parse and enforce Apache Require rules.
845 // On 2.4, we have to short-circuit that and let Apache run callbacks
846 // for each Require rule we handle.
847 extern "C" int shib_auth_checker(request_rec* r)
849 // Short-circuit entirely?
850 shib_dir_config* dc = (shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib);
852 #ifdef SHIB_APACHE_24
853 || dc->bRequestMapperAuthz == 0 // this allows for bypass of the full auth_checker hook if only htaccess is used
859 ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker entered in pid (%d)", (int)getpid());
861 string threadid("[");
862 threadid += lexical_cast<string>(getpid()) + "] shib_auth_checker";
863 xmltooling::NDC ndc(threadid.c_str());
866 #ifndef SHIB_APACHE_24
867 ShibTargetApache sta(r);
868 ShibTargetApache* psta = &sta;
870 shib_request_config* rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
871 if (!rc || !rc->sta) {
872 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker found no per-request structure");
875 ShibTargetApache* psta = rc->sta;
877 if (!psta->init(false, false)) {
878 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker unable to initialize SP request object");
882 pair<bool,long> res = psta->getServiceProvider().doAuthorization(*psta);
883 if (res.first) return res.second;
885 // The SP method should always return true, so if we get this far, something unusual happened.
886 // Just let Apache (or some other module) decide what to do.
889 catch (std::exception& e) {
890 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an exception: %s", e.what());
894 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an unknown exception!");
901 // Overlays environment variables on top of subprocess table.
902 extern "C" int shib_fixups(request_rec* r)
904 shib_dir_config *dc = (shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib);
905 if (dc->bOff==1 || dc->bUseEnvVars==0)
908 ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "shib_fixups entered in pid (%d)", (int)getpid());
910 shib_request_config *rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
911 if (rc==nullptr || rc->env==nullptr || ap_is_empty_table(rc->env))
914 ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "shib_fixups adding %d vars", ap_table_elts(rc->env)->nelts);
915 r->subprocess_env = ap_overlay_tables(r->pool, r->subprocess_env, rc->env);
921 // Access control plugin that enforces pre-2.4 htaccess rules.
922 // Post-2.4, we have to register individual methods to respond
923 // to each require rule we want to handle, and have those call
924 // into these methods directly.
925 class htAccessControl : virtual public AccessControl
929 ~htAccessControl() {}
930 Lockable* lock() {return this;}
932 aclresult_t authorized(const SPRequest& request, const Session* session) const;
934 aclresult_t doAccessControl(const ShibTargetApache& sta, const Session* session, const char* plugin) const;
935 aclresult_t doUser(const ShibTargetApache& sta, const char* params) const;
936 #ifndef SHIB_APACHE_24
937 aclresult_t doGroup(const ShibTargetApache& sta, const char* params) const;
939 aclresult_t doAuthnContext(const ShibTargetApache& sta, const char* acRef, const char* params) const;
940 aclresult_t doShibAttr(const ShibTargetApache& sta, const Session* session, const char* rule, const char* params) const;
943 bool checkAttribute(const SPRequest& request, const Attribute* attr, const char* toMatch, RegularExpression* re) const;
946 AccessControl* htAccessFactory(const xercesc::DOMElement* const & e)
948 return new htAccessControl();
951 AccessControl::aclresult_t htAccessControl::doAccessControl(const ShibTargetApache& sta, const Session* session, const char* plugin) const
953 aclresult_t result = shib_acl_false;
955 ifstream aclfile(plugin);
957 throw ConfigurationException("Unable to open access control file ($1).", params(1, plugin));
958 xercesc::DOMDocument* acldoc = XMLToolingConfig::getConfig().getParser().parse(aclfile);
959 XercesJanitor<xercesc::DOMDocument> docjanitor(acldoc);
960 static XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
961 string t(XMLHelper::getAttrString(acldoc ? acldoc->getDocumentElement() : nullptr, nullptr, _type));
963 throw ConfigurationException("Missing type attribute in AccessControl plugin configuration.");
964 scoped_ptr<AccessControl> aclplugin(SPConfig::getConfig().AccessControlManager.newPlugin(t.c_str(), acldoc->getDocumentElement()));
965 Locker acllock(aclplugin.get());
966 result = aclplugin->authorized(sta, session);
968 catch (std::exception& ex) {
969 sta.log(SPRequest::SPError, ex.what());
974 AccessControl::aclresult_t htAccessControl::doUser(const ShibTargetApache& sta, const char* params) const
977 bool negated = false;
979 const char* w = ap_getword_conf(sta.m_req->pool, ¶ms);
984 else if (*w == '!') {
985 // A negated rule presumes success unless a match is found.
992 // Figure out if there's a match.
996 // To do regex matching, we have to convert from UTF-8.
997 auto_arrayptr<XMLCh> trans(fromUTF8(w));
998 RegularExpression re(trans.get());
999 auto_arrayptr<XMLCh> trans2(fromUTF8(sta.getRemoteUser().c_str()));
1000 match = re.matches(trans2.get());
1002 catch (XMLException& ex) {
1003 auto_ptr_char tmp(ex.getMessage());
1004 sta.log(SPRequest::SPError,
1005 string("htaccess plugin caught exception while parsing regular expression (") + w + "): " + tmp.get());
1008 else if (sta.getRemoteUser() == w) {
1013 if (sta.isPriorityEnabled(SPRequest::SPDebug))
1014 sta.log(SPRequest::SPDebug,
1015 string("htaccess: require user ") + (negated ? "rejecting (" : "accepting (") + sta.getRemoteUser() + ")");
1016 return (negated ? shib_acl_false : shib_acl_true);
1019 return (negated ? shib_acl_true : shib_acl_false);
1022 #ifndef SHIB_APACHE_24
1023 static SH_AP_TABLE* groups_for_user(request_rec* r, const char* user, char* grpfile)
1025 SH_AP_CONFIGFILE* f;
1026 SH_AP_TABLE* grps=ap_make_table(r->pool,15);
1027 char l[MAX_STRING_LEN];
1028 const char *group_name, *ll, *w;
1030 #ifdef SHIB_APACHE_13
1031 if (!(f=ap_pcfg_openfile(r->pool, grpfile))) {
1033 if (ap_pcfg_openfile(&f,r->pool,grpfile) != APR_SUCCESS) {
1035 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, SH_AP_R(r), "groups_for_user: could not open group file: %s\n", grpfile);
1040 #ifdef SHIB_APACHE_13
1041 sp=ap_make_sub_pool(r->pool);
1043 if (apr_pool_create(&sp,r->pool) != APR_SUCCESS) {
1044 ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,
1045 "groups_for_user: could not create a subpool");
1050 while (!(ap_cfg_getline(l,MAX_STRING_LEN,f))) {
1051 if ((*l=='#') || (!*l))
1055 group_name = ap_getword(sp,&ll,':');
1057 w=ap_getword_conf(sp,&ll);
1058 if (!strcmp(w,user)) {
1059 ap_table_setn(grps,ap_pstrdup(r->pool,group_name),"in");
1064 ap_cfg_closefile(f);
1065 ap_destroy_pool(sp);
1069 AccessControl::aclresult_t htAccessControl::doGroup(const ShibTargetApache& sta, const char* params) const
1071 SH_AP_TABLE* grpstatus = nullptr;
1072 if (sta.m_dc->szAuthGrpFile) {
1073 if (sta.isPriorityEnabled(SPRequest::SPDebug))
1074 sta.log(SPRequest::SPDebug, string("htaccess plugin using groups file: ") + sta.m_dc->szAuthGrpFile);
1075 grpstatus = groups_for_user(sta.m_req, sta.getRemoteUser().c_str(), sta.m_dc->szAuthGrpFile);
1078 bool negated = false;
1080 const char* w = ap_getword_conf(sta.m_req->pool, ¶ms);
1082 // A negated rule presumes success unless a match is found.
1087 if (grpstatus && ap_table_get(grpstatus, w)) {
1088 // If we matched, then we're done with this rule either way and we flip status to reflect the outcome.
1089 sta.log(SPRequest::SPDebug, string("htaccess: require group ") + (negated ? "rejecting (" : "accepting (") + w + ")");
1090 return (negated ? shib_acl_false : shib_acl_true);
1094 return (negated ? shib_acl_true : shib_acl_false);
1098 AccessControl::aclresult_t htAccessControl::doAuthnContext(const ShibTargetApache& sta, const char* ref, const char* params) const
1101 bool regexp = false;
1102 bool negated = false;
1103 while (ref && *params) {
1104 const char* w = ap_getword_conf(sta.m_req->pool, ¶ms);
1109 else if (*w == '!') {
1110 // A negated rule presumes success unless a match is found.
1117 // Figure out if there's a match.
1121 RegularExpression re(w);
1122 match = re.matches(ref);
1124 catch (XMLException& ex) {
1125 auto_ptr_char tmp(ex.getMessage());
1126 sta.log(SPRequest::SPError,
1127 string("htaccess plugin caught exception while parsing regular expression (") + w + "): " + tmp.get());
1130 else if (!strcmp(w, ref)) {
1135 if (sta.isPriorityEnabled(SPRequest::SPDebug))
1136 sta.log(SPRequest::SPDebug,
1137 string("htaccess: require authnContext ") + (negated ? "rejecting (" : "accepting (") + ref + ")");
1138 return (negated ? shib_acl_false : shib_acl_true);
1141 return (negated ? shib_acl_true : shib_acl_false);
1144 if (sta.isPriorityEnabled(SPRequest::SPDebug))
1145 sta.log(SPRequest::SPDebug, "htaccess: require authnContext rejecting session with no context associated");
1146 return shib_acl_false;
1149 bool htAccessControl::checkAttribute(const SPRequest& request, const Attribute* attr, const char* toMatch, RegularExpression* re) const
1151 bool caseSensitive = attr->isCaseSensitive();
1152 const vector<string>& vals = attr->getSerializedValues();
1153 for (vector<string>::const_iterator v = vals.begin(); v != vals.end(); ++v) {
1155 auto_arrayptr<XMLCh> trans(fromUTF8(v->c_str()));
1156 if (re->matches(trans.get())) {
1157 if (request.isPriorityEnabled(SPRequest::SPDebug))
1158 request.log(SPRequest::SPDebug, string("htaccess: expecting regexp ") + toMatch + ", got " + *v + ": acccepted");
1162 else if ((caseSensitive && *v == toMatch) || (!caseSensitive && !strcasecmp(v->c_str(), toMatch))) {
1163 if (request.isPriorityEnabled(SPRequest::SPDebug))
1164 request.log(SPRequest::SPDebug, string("htaccess: expecting ") + toMatch + ", got " + *v + ": accepted");
1167 else if (request.isPriorityEnabled(SPRequest::SPDebug)) {
1168 request.log(SPRequest::SPDebug, string("htaccess: expecting ") + toMatch + ", got " + *v + ": rejected");
1174 AccessControl::aclresult_t htAccessControl::doShibAttr(const ShibTargetApache& sta, const Session* session, const char* rule, const char* params) const
1176 #ifndef SHIB_APACHE_24
1177 // Look for the new shib-attr placeholder and move past it.
1178 if (sta.m_dc->bCompatWith24 == 1 && rule && !strcmp(rule, "shib-attr")) {
1180 rule = ap_getword_conf(sta.m_req->pool, ¶ms);
1184 // Find the attribute(s) matching the require rule.
1185 pair<multimap<string,const Attribute*>::const_iterator,multimap<string,const Attribute*>::const_iterator> attrs =
1186 session->getIndexedAttributes().equal_range(rule ? rule : "");
1188 bool regexp = false;
1189 while (attrs.first != attrs.second && *params) {
1190 const char* w = ap_getword_conf(sta.m_req->pool, ¶ms);
1197 scoped_ptr<RegularExpression> re;
1199 auto_arrayptr<XMLCh> trans(fromUTF8(w));
1200 re.reset(new xercesc::RegularExpression(trans.get()));
1203 pair<multimap<string,const Attribute*>::const_iterator,multimap<string,const Attribute*>::const_iterator> attrs2(attrs);
1204 for (; attrs2.first != attrs2.second; ++attrs2.first) {
1205 if (checkAttribute(sta, attrs2.first->second, w, regexp ? re.get() : nullptr)) {
1206 return shib_acl_true;
1210 catch (XMLException& ex) {
1211 auto_ptr_char tmp(ex.getMessage());
1212 sta.log(SPRequest::SPError, string("htaccess plugin caught exception while parsing regular expression (") + w + "): " + tmp.get());
1215 return shib_acl_false;
1218 AccessControl::aclresult_t htAccessControl::authorized(const SPRequest& request, const Session* session) const
1220 #ifdef SHIB_APACHE_24
1221 // We should never be invoked in 2.4 as an SP plugin.
1222 throw ConfigurationException("Save my walrus!");
1224 // Make sure the object is our type.
1225 const ShibTargetApache* sta=dynamic_cast<const ShibTargetApache*>(&request);
1227 throw ConfigurationException("Request wrapper object was not of correct type.");
1229 int m = sta->m_req->method_number;
1230 bool method_restricted = false;
1233 const array_header* reqs_arr = ap_requires(sta->m_req);
1235 return shib_acl_indeterminate; // should never happen
1237 // Check for an "embedded" AccessControl plugin.
1238 if (sta->m_dc->szAccessControl) {
1239 aclresult_t result = doAccessControl(*sta, session, sta->m_dc->szAccessControl);
1240 if (result == shib_acl_true && sta->m_dc->bRequireAll != 1) {
1241 // If we're not insisting that all rules be met, then we're done.
1242 request.log(SPRequest::SPDebug, "htaccess: embedded AccessControl plugin was successful, granting access");
1243 return shib_acl_true;
1245 else if (result != shib_acl_true && sta->m_dc->bRequireAll == 1) {
1246 // If we're insisting that all rules be met, which is not something Apache really handles well,
1247 // then we either return false or indeterminate based on the authoritative option, which defaults on.
1248 if (sta->m_dc->bAuthoritative != 0) {
1249 request.log(SPRequest::SPDebug, "htaccess: embedded AccessControl plugin was unsuccessful, denying access");
1250 return shib_acl_false;
1253 request.log(SPRequest::SPDebug, "htaccess: embedded AccessControl plugin was unsuccessful but not authoritative, leaving it up to Apache");
1254 return shib_acl_indeterminate;
1258 require_line* reqs = (require_line*)reqs_arr->elts;
1260 for (int x = 0; x < reqs_arr->nelts; ++x) {
1261 // This rule should be completely ignored, the method doesn't fit.
1262 // The rule just doesn't exist for our purposes.
1263 if (!(reqs[x].method_mask & (1 << m)))
1266 method_restricted = true; // this lets us know at the end that at least one rule was potentially enforcable.
1268 // Tracks status of this rule's evaluation.
1269 bool status = false;
1271 string remote_user = request.getRemoteUser();
1273 t = reqs[x].requirement;
1274 w = ap_getword_white(sta->m_req->pool, &t);
1276 if (!strcasecmp(w,"shibboleth")) {
1277 // This is a dummy rule needed because Apache conflates authn and authz.
1278 // Without some require rule, AuthType is ignored and no check_user hooks run.
1280 // We evaluate to false if ShibAccessControl is used and ShibRequireAll is off.
1281 // This allows actual rules to dictate the result, since ShibAccessControl returned
1282 // non-true, and if nothing else is used, access will be denied.
1283 if (!sta->m_dc->szAccessControl || sta->m_dc->bRequireAll == 1) {
1284 // We evaluate to true, because ShibRequireAll is enabled (so a true is just a no-op)
1285 // or because there was no other AccessControl rule in place, so this may be the only
1290 else if (!strcmp(w,"valid-user") && session) {
1291 request.log(SPRequest::SPDebug, "htaccess: accepting valid-user based on active session");
1294 else if (!strcmp(w,"user") && !remote_user.empty()) {
1295 status = (doUser(*sta, t) == shib_acl_true);
1297 else if (!strcmp(w,"group") && !remote_user.empty()) {
1298 status = (doGroup(*sta, t) == shib_acl_true);
1300 else if (!strcmp(w,"authnContextClassRef") || !strcmp(w,"authnContextDeclRef")) {
1301 const char* ref = !strcmp(w, "authnContextClassRef") ? session->getAuthnContextClassRef() : session->getAuthnContextDeclRef();
1302 status = (doAuthnContext(*sta, ref, t) == shib_acl_true);
1304 else if (!session) {
1305 request.log(SPRequest::SPError, string("htaccess: require ") + w + " not given a valid session, are you using lazy sessions?");
1307 else if (sta->m_dc->bCompatWith24 == 1 && !strcmp(w,"shib-plugin")) {
1308 w = ap_getword_conf(sta->m_req->pool, &t);
1310 status = (doAccessControl(*sta, session, w) == shib_acl_true);
1314 status = (doShibAttr(*sta, session, w, t) == shib_acl_true);
1317 // If status is false, we found a rule we couldn't satisfy.
1318 // Could be an unknown rule to us, or it just didn't match.
1320 if (status && sta->m_dc->bRequireAll != 1) {
1321 // If we're not insisting that all rules be met, then we're done.
1322 request.log(SPRequest::SPDebug, "htaccess: a rule was successful, granting access");
1323 return shib_acl_true;
1325 else if (!status && sta->m_dc->bRequireAll == 1) {
1326 // If we're insisting that all rules be met, which is not something Apache really handles well,
1327 // then we either return false or indeterminate based on the authoritative option, which defaults on.
1328 if (sta->m_dc->bAuthoritative != 0) {
1329 request.log(SPRequest::SPDebug, "htaccess: a rule was unsuccessful, denying access");
1330 return shib_acl_false;
1333 request.log(SPRequest::SPDebug, "htaccess: a rule was unsuccessful but not authoritative, leaving it up to Apache");
1334 return shib_acl_indeterminate;
1337 // Otherwise, we keep going. If we're requring all, then we have to check every rule.
1338 // If not we just didn't find a successful rule yet, so we keep going anyway.
1341 // If we get here, we either "failed" or we're in require all mode (but not both).
1342 // If no rules possibly apply or we insisted that all rules check out, then we're good.
1343 if (!method_restricted) {
1344 request.log(SPRequest::SPDebug, "htaccess: no rules applied to this request method, granting access");
1345 return shib_acl_true;
1347 else if (sta->m_dc->bRequireAll == 1) {
1348 request.log(SPRequest::SPDebug, "htaccess: all rules successful, granting access");
1349 return shib_acl_true;
1351 else if (sta->m_dc->bAuthoritative != 0) {
1352 request.log(SPRequest::SPDebug, "htaccess: no rules were successful, denying access");
1353 return shib_acl_false;
1356 request.log(SPRequest::SPDebug, "htaccess: no rules were successful but not authoritative, leaving it up to Apache");
1357 return shib_acl_indeterminate;
1361 class ApacheRequestMapper : public virtual RequestMapper, public virtual PropertySet
1364 ApacheRequestMapper(const xercesc::DOMElement* e);
1365 ~ApacheRequestMapper() {}
1366 Lockable* lock() { return m_mapper->lock(); }
1367 void unlock() { m_staKey->setData(nullptr); m_propsKey->setData(nullptr); m_mapper->unlock(); }
1368 Settings getSettings(const HTTPRequest& request) const;
1370 const PropertySet* getParent() const { return nullptr; }
1371 void setParent(const PropertySet*) {}
1372 pair<bool,bool> getBool(const char* name, const char* ns=nullptr) const;
1373 pair<bool,const char*> getString(const char* name, const char* ns=nullptr) const;
1374 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=nullptr) const;
1375 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=nullptr) const;
1376 pair<bool,int> getInt(const char* name, const char* ns=nullptr) const;
1377 void getAll(map<string,const char*>& properties) const;
1378 const PropertySet* getPropertySet(const char* name, const char* ns=shibspconstants::ASCII_SHIB2SPCONFIG_NS) const;
1379 const xercesc::DOMElement* getElement() const;
1381 const htAccessControl& getHTAccessControl() const { return m_htaccess; }
1384 scoped_ptr<RequestMapper> m_mapper;
1385 scoped_ptr<ThreadKey> m_staKey,m_propsKey;
1386 mutable htAccessControl m_htaccess;
1389 RequestMapper* ApacheRequestMapFactory(const xercesc::DOMElement* const & e)
1391 return new ApacheRequestMapper(e);
1394 ApacheRequestMapper::ApacheRequestMapper(const xercesc::DOMElement* e)
1395 : m_mapper(SPConfig::getConfig().RequestMapperManager.newPlugin(XML_REQUEST_MAPPER,e)),
1396 m_staKey(ThreadKey::create(nullptr)), m_propsKey(ThreadKey::create(nullptr))
1400 RequestMapper::Settings ApacheRequestMapper::getSettings(const HTTPRequest& request) const
1402 Settings s = m_mapper->getSettings(request);
1403 m_staKey->setData((void*)dynamic_cast<const ShibTargetApache*>(&request));
1404 m_propsKey->setData((void*)s.first);
1405 // Only return the htAccess plugin for pre-2.4 servers.
1406 #ifdef SHIB_APACHE_24
1407 return pair<const PropertySet*,AccessControl*>(this, s.second);
1409 return pair<const PropertySet*,AccessControl*>(this, s.second ? s.second : &m_htaccess);
1413 pair<bool,bool> ApacheRequestMapper::getBool(const char* name, const char* ns) const
1415 const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
1416 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
1418 // Override Apache-settable boolean properties.
1419 if (name && !strcmp(name,"requireSession") && sta->m_dc->bRequireSession != -1)
1420 return make_pair(true, sta->m_dc->bRequireSession==1);
1421 else if (name && !strcmp(name,"exportAssertion") && sta->m_dc->bExportAssertion != -1)
1422 return make_pair(true, sta->m_dc->bExportAssertion==1);
1423 else if (sta->m_dc->tSettings) {
1424 const char* prop = ap_table_get(sta->m_dc->tSettings, name);
1426 return make_pair(true, !strcmp(prop, "true") || !strcmp(prop, "1") || !strcmp(prop, "On"));
1429 return s ? s->getBool(name,ns) : make_pair(false,false);
1432 pair<bool,const char*> ApacheRequestMapper::getString(const char* name, const char* ns) const
1434 const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
1435 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
1437 // Override Apache-settable string properties.
1438 if (name && !strcmp(name,"authType")) {
1439 const char* auth_type = ap_auth_type(sta->m_req);
1441 // Check for Basic Hijack
1442 if (!strcasecmp(auth_type, "basic") && sta->m_dc->bBasicHijack == 1)
1443 auth_type = "shibboleth";
1444 return make_pair(true, auth_type);
1447 else if (name && !strcmp(name,"applicationId") && sta->m_dc->szApplicationId)
1448 return pair<bool,const char*>(true,sta->m_dc->szApplicationId);
1449 else if (name && !strcmp(name,"requireSessionWith") && sta->m_dc->szRequireWith)
1450 return pair<bool,const char*>(true,sta->m_dc->szRequireWith);
1451 else if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
1452 return pair<bool,const char*>(true,sta->m_dc->szRedirectToSSL);
1453 else if (sta->m_dc->tSettings) {
1454 const char* prop = ap_table_get(sta->m_dc->tSettings, name);
1456 return make_pair(true, prop);
1459 return s ? s->getString(name,ns) : pair<bool,const char*>(false,nullptr);
1462 pair<bool,const XMLCh*> ApacheRequestMapper::getXMLString(const char* name, const char* ns) const
1464 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
1465 return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,nullptr);
1468 pair<bool,unsigned int> ApacheRequestMapper::getUnsignedInt(const char* name, const char* ns) const
1470 const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
1471 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
1473 // Override Apache-settable int properties.
1474 if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
1475 return pair<bool,unsigned int>(true, strtol(sta->m_dc->szRedirectToSSL, nullptr, 10));
1476 else if (sta->m_dc->tSettings) {
1477 const char* prop = ap_table_get(sta->m_dc->tSettings, name);
1479 return pair<bool,unsigned int>(true, atoi(prop));
1482 return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
1485 pair<bool,int> ApacheRequestMapper::getInt(const char* name, const char* ns) const
1487 const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
1488 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
1490 // Override Apache-settable int properties.
1491 if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
1492 return pair<bool,int>(true,atoi(sta->m_dc->szRedirectToSSL));
1493 else if (sta->m_dc->tSettings) {
1494 const char* prop = ap_table_get(sta->m_dc->tSettings, name);
1496 return make_pair(true, atoi(prop));
1499 return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
1502 static int _rm_get_all_table_walk(void *v, const char *key, const char *value)
1504 reinterpret_cast<map<string,const char*>*>(v)->insert(pair<string,const char*>(key, value));
1508 void ApacheRequestMapper::getAll(map<string,const char*>& properties) const
1510 const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
1511 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
1514 s->getAll(properties);
1518 const char* auth_type=ap_auth_type(sta->m_req);
1520 // Check for Basic Hijack
1521 if (!strcasecmp(auth_type, "basic") && sta->m_dc->bBasicHijack == 1)
1522 auth_type = "shibboleth";
1523 properties["authType"] = auth_type;
1526 if (sta->m_dc->szApplicationId)
1527 properties["applicationId"] = sta->m_dc->szApplicationId;
1528 if (sta->m_dc->szRequireWith)
1529 properties["requireSessionWith"] = sta->m_dc->szRequireWith;
1530 if (sta->m_dc->szRedirectToSSL)
1531 properties["redirectToSSL"] = sta->m_dc->szRedirectToSSL;
1532 if (sta->m_dc->bRequireSession != 0)
1533 properties["requireSession"] = (sta->m_dc->bRequireSession==1) ? "true" : "false";
1534 if (sta->m_dc->bExportAssertion != 0)
1535 properties["exportAssertion"] = (sta->m_dc->bExportAssertion==1) ? "true" : "false";
1537 if (sta->m_dc->tSettings)
1538 ap_table_do(_rm_get_all_table_walk, &properties, sta->m_dc->tSettings, NULL);
1541 const PropertySet* ApacheRequestMapper::getPropertySet(const char* name, const char* ns) const
1543 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
1544 return s ? s->getPropertySet(name,ns) : nullptr;
1547 const xercesc::DOMElement* ApacheRequestMapper::getElement() const
1549 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
1550 return s ? s->getElement() : nullptr;
1553 // Authz callbacks for Apache 2.4
1554 // For some reason, these get run twice for each request, once before hooks like check_user, etc.
1555 // and once after. The first time through, the request object exists, but isn't initialized.
1556 // The other case is subrequests of some kinds: then post_read doesn't run, and the objects
1557 // themselves don't exist. We do deferred creation of the objects in check_user to fix that case.
1558 // In each screwed up case, we return "denied" so that nothing bad happens.
1559 #ifdef SHIB_APACHE_24
1560 pair<ShibTargetApache*,authz_status> shib_base_check_authz(request_rec* r)
1562 shib_request_config* rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
1563 if (!rc || !rc->sta) {
1564 ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "shib_base_check_authz found no per-request structure");
1565 return make_pair((ShibTargetApache*)nullptr, AUTHZ_DENIED_NO_USER);
1567 else if (!rc->sta->isInitialized()) {
1568 ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "shib_base_check_authz found uninitialized request object");
1569 return make_pair((ShibTargetApache*)nullptr, AUTHZ_DENIED_NO_USER);
1571 return make_pair(rc->sta, AUTHZ_GRANTED);
1574 extern "C" authz_status shib_shibboleth_check_authz(request_rec* r, const char* require_line, const void*)
1576 pair<ShibTargetApache*,authz_status> sta = shib_base_check_authz(r);
1579 return AUTHZ_GRANTED;
1582 extern "C" authz_status shib_validuser_check_authz(request_rec* r, const char* require_line, const void*)
1584 pair<ShibTargetApache*,authz_status> sta = shib_base_check_authz(r);
1589 Session* session = sta.first->getSession(false, true, false);
1590 Locker slocker(session, false);
1592 sta.first->log(SPRequest::SPDebug, "htaccess: accepting valid-user based on active session");
1593 return AUTHZ_GRANTED;
1596 catch (std::exception& e) {
1597 sta.first->log(SPRequest::SPWarn, string("htaccess: unable to obtain session for access control check: ") + e.what());
1600 return AUTHZ_DENIED_NO_USER;
1603 extern "C" authz_status shib_user_check_authz(request_rec* r, const char* require_line, const void*)
1605 if (!r->user || !*(r->user))
1606 return AUTHZ_DENIED_NO_USER;
1607 pair<ShibTargetApache*,authz_status> sta = shib_base_check_authz(r);
1611 const htAccessControl& hta = dynamic_cast<const ApacheRequestMapper*>(sta.first->getRequestSettings().first)->getHTAccessControl();
1612 if (hta.doUser(*sta.first, require_line) == AccessControl::shib_acl_true)
1613 return AUTHZ_GRANTED;
1614 return AUTHZ_DENIED;
1617 extern "C" authz_status shib_acclass_check_authz(request_rec* r, const char* require_line, const void*)
1619 pair<ShibTargetApache*,authz_status> sta = shib_base_check_authz(r);
1623 const htAccessControl& hta = dynamic_cast<const ApacheRequestMapper*>(sta.first->getRequestSettings().first)->getHTAccessControl();
1626 Session* session = sta.first->getSession(false, true, false);
1627 Locker slocker(session, false);
1628 if (session && hta.doAuthnContext(*sta.first, session->getAuthnContextClassRef(), require_line) == AccessControl::shib_acl_true)
1629 return AUTHZ_GRANTED;
1630 return session ? AUTHZ_DENIED : AUTHZ_DENIED_NO_USER;
1632 catch (std::exception& e) {
1633 sta.first->log(SPRequest::SPWarn, string("htaccess: unable to obtain session for access control check: ") + e.what());
1636 return AUTHZ_GENERAL_ERROR;
1639 extern "C" authz_status shib_acdecl_check_authz(request_rec* r, const char* require_line, const void*)
1641 pair<ShibTargetApache*,authz_status> sta = shib_base_check_authz(r);
1645 const htAccessControl& hta = dynamic_cast<const ApacheRequestMapper*>(sta.first->getRequestSettings().first)->getHTAccessControl();
1648 Session* session = sta.first->getSession(false, true, false);
1649 Locker slocker(session, false);
1650 if (session && hta.doAuthnContext(*sta.first, session->getAuthnContextDeclRef(), require_line) == AccessControl::shib_acl_true)
1651 return AUTHZ_GRANTED;
1652 return session ? AUTHZ_DENIED : AUTHZ_DENIED_NO_USER;
1654 catch (std::exception& e) {
1655 sta.first->log(SPRequest::SPWarn, string("htaccess: unable to obtain session for access control check: ") + e.what());
1658 return AUTHZ_GENERAL_ERROR;
1661 extern "C" authz_status shib_attr_check_authz(request_rec* r, const char* require_line, const void*)
1663 pair<ShibTargetApache*,authz_status> sta = shib_base_check_authz(r);
1667 const htAccessControl& hta = dynamic_cast<const ApacheRequestMapper*>(sta.first->getRequestSettings().first)->getHTAccessControl();
1670 Session* session = sta.first->getSession(false, true, false);
1671 Locker slocker(session, false);
1673 const char* rule = ap_getword_conf(r->pool, &require_line);
1674 if (rule && hta.doShibAttr(*sta.first, session, rule, require_line) == AccessControl::shib_acl_true)
1675 return AUTHZ_GRANTED;
1677 return session ? AUTHZ_DENIED : AUTHZ_DENIED_NO_USER;
1679 catch (std::exception& e) {
1680 sta.first->log(SPRequest::SPWarn, string("htaccess: unable to obtain session for access control check: ") + e.what());
1683 return AUTHZ_GENERAL_ERROR;
1686 extern "C" authz_status shib_plugin_check_authz(request_rec* r, const char* require_line, const void*)
1688 pair<ShibTargetApache*,authz_status> sta = shib_base_check_authz(r);
1692 const htAccessControl& hta = dynamic_cast<const ApacheRequestMapper*>(sta.first->getRequestSettings().first)->getHTAccessControl();
1695 Session* session = sta.first->getSession(false, true, false);
1696 Locker slocker(session, false);
1698 const char* config = ap_getword_conf(r->pool, &require_line);
1699 if (config && hta.doAccessControl(*sta.first, session, config) == AccessControl::shib_acl_true)
1700 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;
1712 // Command manipulation functions
1714 extern "C" const char* ap_set_global_string_slot(cmd_parms* parms, void*, const char* arg)
1716 *((char**)(parms->info))=ap_pstrdup(parms->pool,arg);
1720 extern "C" const char* shib_set_server_string_slot(cmd_parms* parms, void*, const char* arg)
1722 char* base=(char*)ap_get_module_config(parms->server->module_config,&mod_shib);
1723 size_t offset=(size_t)parms->info;
1724 *((char**)(base + offset))=ap_pstrdup(parms->pool,arg);
1728 extern "C" const char* shib_ap_set_file_slot(cmd_parms* parms,
1729 #ifdef SHIB_APACHE_13
1730 char* arg1, char* arg2
1732 void* arg1, const char* arg2
1736 ap_set_file_slot(parms, arg1, arg2);
1740 extern "C" const char* shib_table_set(cmd_parms* parms, shib_dir_config* dc, const char* arg1, const char* arg2)
1743 dc->tSettings = ap_make_table(parms->pool, 4);
1744 ap_table_set(dc->tSettings, arg1, arg2);
1748 #ifndef SHIB_APACHE_24
1749 extern "C" const char* shib_set_acl_slot(cmd_parms* params, shib_dir_config* dc, char* arg)
1761 absolute = (*(arg+1) == '.' || *(arg+1) == '/' || *(arg+1) == '\\');
1764 absolute = *(arg+1) == ':';
1767 if (absolute || !params->path)
1768 dc->szAccessControl = ap_pstrdup(params->pool, arg);
1770 dc->szAccessControl = ap_pstrcat(params->pool, params->path, arg, NULL);
1776 #ifdef SHIB_APACHE_13
1779 * Cleanup the (per-process) pool info.
1781 extern "C" void shib_child_exit(server_rec* s, SH_AP_POOL* p)
1787 ap_log_error(APLOG_MARK, APLOG_INFO|APLOG_NOERRNO, SH_AP_R(s), "child_exit: mod_shib shutdown in pid (%d)", (int)getpid());
1792 * Apache 2.x doesn't allow for per-child cleanup, causes CGI forks to hang.
1794 extern "C" apr_status_t shib_exit(void* data)
1800 server_rec* s = reinterpret_cast<server_rec*>(data);
1801 ap_log_error(APLOG_MARK, APLOG_INFO|APLOG_NOERRNO, SH_AP_R(s), "shib_exit: mod_shib shutdown in pid (%d)", (int)getpid());
1806 * shib_post_config()
1807 * We do the library init/term work here for 2.x to reduce overhead and
1808 * get default logging established before the fork happens.
1810 apr_status_t shib_post_config(apr_pool_t* p, apr_pool_t*, apr_pool_t*, server_rec* s)
1812 // Initialize runtime components.
1813 ap_log_error(APLOG_MARK, APLOG_INFO|APLOG_NOERRNO, SH_AP_R(s),"post_config: mod_shib initializing in pid (%d)", (int)getpid());
1816 ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(s), "post_config: mod_shib already initialized");
1820 g_Config = &SPConfig::getConfig();
1821 g_Config->setFeatures(
1822 SPConfig::Listener |
1824 SPConfig::RequestMapping |
1825 SPConfig::InProcess |
1829 if (!g_Config->init(g_szSchemaDir, g_szPrefix)) {
1830 ap_log_error(APLOG_MARK, APLOG_CRIT|APLOG_NOERRNO, SH_AP_R(s), "post_config: mod_shib failed to initialize libraries");
1833 #ifndef SHIB_APACHE_24
1834 g_Config->AccessControlManager.registerFactory(HT_ACCESS_CONTROL, &htAccessFactory);
1836 g_Config->RequestMapperManager.registerFactory(NATIVE_REQUEST_MAPPER, &ApacheRequestMapFactory);
1838 // Set the cleanup handler, passing in the server_rec for logging.
1839 apr_pool_cleanup_register(p, s, &shib_exit, apr_pool_cleanup_null);
1848 * Things to do when the child process is initialized.
1849 * We can't use post-config for all of it on 2.x because only the forking thread shows
1850 * up in the child, losing the internal threads spun up by plugins in the SP.
1852 #ifdef SHIB_APACHE_13
1853 extern "C" void shib_child_init(server_rec* s, SH_AP_POOL* p)
1855 extern "C" void shib_child_init(apr_pool_t* p, server_rec* s)
1858 // Initialize runtime components.
1860 ap_log_error(APLOG_MARK, APLOG_INFO|APLOG_NOERRNO, SH_AP_R(s),"child_init: mod_shib initializing in pid (%d)", (int)getpid());
1862 // 2.x versions have already initialized the libraries.
1863 #ifdef SHIB_APACHE_13
1865 ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(s), "child_init: mod_shib already initialized, exiting");
1869 g_Config = &SPConfig::getConfig();
1870 g_Config->setFeatures(
1871 SPConfig::Listener |
1873 SPConfig::RequestMapping |
1874 SPConfig::InProcess |
1878 if (!g_Config->init(g_szSchemaDir, g_szPrefix)) {
1879 ap_log_error(APLOG_MARK, APLOG_CRIT|APLOG_NOERRNO, SH_AP_R(s), "child_init: mod_shib failed to initialize libraries");
1882 g_Config->AccessControlManager.registerFactory(HT_ACCESS_CONTROL, &htAccessFactory);
1883 g_Config->RequestMapperManager.registerFactory(NATIVE_REQUEST_MAPPER, &ApacheRequestMapFactory);
1886 // The config gets installed for all versions here due to the background thread/fork issues.
1888 if (!g_Config->instantiate(g_szSHIBConfig, true))
1889 throw runtime_error("unknown error");
1891 catch (std::exception& ex) {
1892 ap_log_error(APLOG_MARK, APLOG_CRIT|APLOG_NOERRNO, SH_AP_R(s), "child_init: mod_shib failed to load configuration: %s", ex.what());
1897 ServiceProvider* sp = g_Config->getServiceProvider();
1898 xmltooling::Locker locker(sp);
1899 const PropertySet* props = sp->getPropertySet("InProcess");
1901 pair<bool,const char*> unsetValue = props->getString("unsetHeaderValue");
1902 if (unsetValue.first)
1903 g_unsetHeaderValue = unsetValue.second;
1904 pair<bool,bool> flag=props->getBool("checkSpoofing");
1905 g_checkSpoofing = !flag.first || flag.second;
1906 if (g_checkSpoofing) {
1907 unsetValue=props->getString("spoofKey");
1908 if (unsetValue.first)
1909 g_spoofKey = unsetValue.second;
1911 flag=props->getBool("catchAll");
1912 g_catchAll = flag.first && flag.second;
1915 // Set the cleanup handler, passing in the server_rec for logging.
1916 apr_pool_cleanup_register(p, s, &shib_exit, apr_pool_cleanup_null);
1918 ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(s), "child_init: mod_shib config initialized");
1922 #ifdef SHIB_DEFERRED_HEADERS
1923 static void set_output_filter(request_rec *r)
1925 ap_add_output_filter("SHIB_HEADERS_OUT", nullptr, r, r->connection);
1928 static void set_error_filter(request_rec *r)
1930 ap_add_output_filter("SHIB_HEADERS_ERR", nullptr, r, r->connection);
1933 static int _table_add(void *v, const char *key, const char *value)
1935 apr_table_addn((apr_table_t*)v, key, value);
1939 static apr_status_t do_output_filter(ap_filter_t *f, apr_bucket_brigade *in)
1941 request_rec *r = f->r;
1942 shib_request_config *rc = (shib_request_config*) ap_get_module_config(r->request_config, &mod_shib);
1944 if (rc && rc->hdr_out) {
1945 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);
1946 // can't use overlap call because it will collapse Set-Cookie headers
1947 //apr_table_overlap(r->headers_out, rc->hdr_out, APR_OVERLAP_TABLES_MERGE);
1948 apr_table_do(_table_add,r->headers_out, rc->hdr_out,NULL);
1951 /* remove ourselves from the filter chain */
1952 ap_remove_output_filter(f);
1954 /* send the data up the stack */
1955 return ap_pass_brigade(f->next,in);
1958 static apr_status_t do_error_filter(ap_filter_t *f, apr_bucket_brigade *in)
1960 request_rec *r = f->r;
1961 shib_request_config *rc = (shib_request_config*) ap_get_module_config(r->request_config, &mod_shib);
1963 if (rc && rc->hdr_out) {
1964 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);
1965 // can't use overlap call because it will collapse Set-Cookie headers
1966 //apr_table_overlap(r->err_headers_out, rc->hdr_out, APR_OVERLAP_TABLES_MERGE);
1967 apr_table_do(_table_add,r->err_headers_out, rc->hdr_out,NULL);
1970 /* remove ourselves from the filter chain */
1971 ap_remove_output_filter(f);
1973 /* send the data up the stack */
1974 return ap_pass_brigade(f->next,in);
1976 #endif // SHIB_DEFERRED_HEADERS
1978 typedef const char* (*config_fn_t)(void);
1980 #ifdef SHIB_APACHE_13
1982 // SHIB Module commands
1984 static command_rec shire_cmds[] = {
1985 {"ShibPrefix", (config_fn_t)ap_set_global_string_slot, &g_szPrefix,
1986 RSRC_CONF, TAKE1, "Shibboleth installation directory"},
1987 {"ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1988 RSRC_CONF, TAKE1, "Path to shibboleth2.xml config file"},
1989 {"ShibCatalogs", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1990 RSRC_CONF, TAKE1, "Paths of XML schema catalogs"},
1992 {"ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
1993 (void *) XtOffsetOf (shib_server_config, szScheme),
1994 RSRC_CONF, TAKE1, "URL scheme to force into generated URLs for a vhost"},
1996 {"ShibRequestSetting", (config_fn_t)shib_table_set, nullptr,
1997 OR_AUTHCFG, TAKE2, "Set arbitrary Shibboleth request property for content"},
1999 {"ShibAccessControl", (config_fn_t)shib_set_acl_slot, nullptr,
2000 OR_AUTHCFG, TAKE1, "Set arbitrary Shibboleth access control plugin for content"},
2002 {"ShibDisable", (config_fn_t)ap_set_flag_slot,
2003 (void *) XtOffsetOf (shib_dir_config, bOff),
2004 OR_AUTHCFG, FLAG, "Disable all Shib module activity here to save processing effort"},
2005 {"ShibApplicationId", (config_fn_t)ap_set_string_slot,
2006 (void *) XtOffsetOf (shib_dir_config, szApplicationId),
2007 OR_AUTHCFG, TAKE1, "Set Shibboleth applicationId property for content"},
2008 {"ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
2009 (void *) XtOffsetOf (shib_dir_config, bBasicHijack),
2010 OR_AUTHCFG, FLAG, "(DEPRECATED) Respond to AuthType Basic and convert to shibboleth"},
2011 {"ShibRequireSession", (config_fn_t)ap_set_flag_slot,
2012 (void *) XtOffsetOf (shib_dir_config, bRequireSession),
2013 OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist"},
2014 {"ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
2015 (void *) XtOffsetOf (shib_dir_config, szRequireWith),
2016 OR_AUTHCFG, TAKE1, "Initiates a new session if one does not exist using a specific SessionInitiator"},
2017 {"ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
2018 (void *) XtOffsetOf (shib_dir_config, bExportAssertion),
2019 OR_AUTHCFG, FLAG, "Export SAML attribute assertion(s) to Shib-Attributes header"},
2020 {"ShibRedirectToSSL", (config_fn_t)ap_set_string_slot,
2021 (void *) XtOffsetOf (shib_dir_config, szRedirectToSSL),
2022 OR_AUTHCFG, TAKE1, "Redirect non-SSL requests to designated port" },
2023 {"AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
2024 (void *) XtOffsetOf (shib_dir_config, szAuthGrpFile),
2025 OR_AUTHCFG, TAKE1, "text file containing group names and member user IDs"},
2026 {"ShibRequireAll", (config_fn_t)ap_set_flag_slot,
2027 (void *) XtOffsetOf (shib_dir_config, bRequireAll),
2028 OR_AUTHCFG, FLAG, "All require directives must match"},
2029 {"AuthzShibAuthoritative", (config_fn_t)ap_set_flag_slot,
2030 (void *) XtOffsetOf (shib_dir_config, bAuthoritative),
2031 OR_AUTHCFG, FLAG, "Allow failed mod_shib htaccess authorization to fall through to other modules"},
2032 {"ShibCompatWith24", (config_fn_t)ap_set_flag_slot,
2033 (void *) XtOffsetOf (shib_dir_config, bCompatWith24),
2034 OR_AUTHCFG, FLAG, "Support Apache 2.4-style require rules"},
2035 {"ShibUseEnvironment", (config_fn_t)ap_set_flag_slot,
2036 (void *) XtOffsetOf (shib_dir_config, bUseEnvVars),
2037 OR_AUTHCFG, FLAG, "Export attributes using environment variables (default)"},
2038 {"ShibUseHeaders", (config_fn_t)ap_set_flag_slot,
2039 (void *) XtOffsetOf (shib_dir_config, bUseHeaders),
2040 OR_AUTHCFG, FLAG, "Export attributes using custom HTTP headers"},
2041 {"ShibExpireRedirects", (config_fn_t)ap_set_flag_slot,
2042 (void *) XtOffsetOf (shib_dir_config, bExpireRedirects),
2043 OR_AUTHCFG, FLAG, "Expire SP-generated redirects"},
2049 handler_rec shib_handlers[] = {
2050 { "shib-handler", shib_handler },
2054 module MODULE_VAR_EXPORT mod_shib = {
2055 STANDARD_MODULE_STUFF,
2056 nullptr, /* initializer */
2057 create_shib_dir_config, /* dir config creater */
2058 merge_shib_dir_config, /* dir merger --- default is to override */
2059 create_shib_server_config, /* server config */
2060 merge_shib_server_config, /* merge server config */
2061 shire_cmds, /* command table */
2062 shib_handlers, /* handlers */
2063 nullptr, /* filename translation */
2064 shib_check_user, /* check_user_id */
2065 shib_auth_checker, /* check auth */
2066 nullptr, /* check access */
2067 nullptr, /* type_checker */
2068 shib_fixups, /* fixups */
2069 nullptr, /* logger */
2070 nullptr, /* header parser */
2071 shib_child_init, /* child_init */
2072 shib_child_exit, /* child_exit */
2073 shib_post_read /* post read-request */
2078 #ifdef SHIB_APACHE_24
2079 extern "C" const authz_provider shib_authz_shibboleth_provider = { &shib_shibboleth_check_authz, nullptr };
2080 extern "C" const authz_provider shib_authz_validuser_provider = { &shib_validuser_check_authz, nullptr };
2081 extern "C" const authz_provider shib_authz_user_provider = { &shib_user_check_authz, nullptr };
2082 extern "C" const authz_provider shib_authz_acclass_provider = { &shib_acclass_check_authz, nullptr };
2083 extern "C" const authz_provider shib_authz_acdecl_provider = { &shib_acdecl_check_authz, nullptr };
2084 extern "C" const authz_provider shib_authz_attr_provider = { &shib_attr_check_authz, nullptr };
2085 extern "C" const authz_provider shib_authz_plugin_provider = { &shib_plugin_check_authz, nullptr };
2088 extern "C" void shib_register_hooks (apr_pool_t *p)
2090 #ifdef SHIB_DEFERRED_HEADERS
2091 ap_register_output_filter("SHIB_HEADERS_OUT", do_output_filter, nullptr, AP_FTYPE_CONTENT_SET);
2092 ap_hook_insert_filter(set_output_filter, nullptr, nullptr, APR_HOOK_LAST);
2093 ap_register_output_filter("SHIB_HEADERS_ERR", do_error_filter, nullptr, AP_FTYPE_CONTENT_SET);
2094 ap_hook_insert_error_filter(set_error_filter, nullptr, nullptr, APR_HOOK_LAST);
2095 ap_hook_post_read_request(shib_post_read, nullptr, nullptr, APR_HOOK_MIDDLE);
2097 ap_hook_post_config(shib_post_config, nullptr, nullptr, APR_HOOK_MIDDLE);
2098 ap_hook_child_init(shib_child_init, nullptr, nullptr, APR_HOOK_MIDDLE);
2099 const char* prereq = getenv("SHIBSP_APACHE_PREREQ");
2100 #ifdef SHIB_APACHE_24
2101 if (prereq && *prereq) {
2102 const char* const authnPre[] = { prereq, nullptr };
2103 ap_hook_check_authn(shib_check_user, authnPre, nullptr, APR_HOOK_MIDDLE, AP_AUTH_INTERNAL_PER_URI);
2106 ap_hook_check_authn(shib_check_user, nullptr, nullptr, APR_HOOK_MIDDLE, AP_AUTH_INTERNAL_PER_URI);
2108 ap_hook_check_authz(shib_auth_checker, nullptr, nullptr, APR_HOOK_FIRST, AP_AUTH_INTERNAL_PER_URI);
2110 if (prereq && *prereq) {
2111 const char* const authnPre[] = { prereq, nullptr };
2112 ap_hook_check_user_id(shib_check_user, authnPre, nullptr, APR_HOOK_MIDDLE);
2115 ap_hook_check_user_id(shib_check_user, nullptr, nullptr, APR_HOOK_MIDDLE);
2117 ap_hook_auth_checker(shib_auth_checker, nullptr, nullptr, APR_HOOK_FIRST);
2119 ap_hook_handler(shib_handler, nullptr, nullptr, APR_HOOK_LAST);
2120 ap_hook_fixups(shib_fixups, nullptr, nullptr, APR_HOOK_MIDDLE);
2122 #ifdef SHIB_APACHE_24
2123 ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "shibboleth", AUTHZ_PROVIDER_VERSION, &shib_authz_shibboleth_provider, AP_AUTH_INTERNAL_PER_CONF);
2124 ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "valid-user", AUTHZ_PROVIDER_VERSION, &shib_authz_validuser_provider, AP_AUTH_INTERNAL_PER_CONF);
2125 ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "user", AUTHZ_PROVIDER_VERSION, &shib_authz_user_provider, AP_AUTH_INTERNAL_PER_CONF);
2126 ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "authnContextClassRef", AUTHZ_PROVIDER_VERSION, &shib_authz_acclass_provider, AP_AUTH_INTERNAL_PER_CONF);
2127 ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "authnContextDeclRef", AUTHZ_PROVIDER_VERSION, &shib_authz_acdecl_provider, AP_AUTH_INTERNAL_PER_CONF);
2128 ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "shib-attr", AUTHZ_PROVIDER_VERSION, &shib_authz_attr_provider, AP_AUTH_INTERNAL_PER_CONF);
2129 ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "shib-plugin", AUTHZ_PROVIDER_VERSION, &shib_authz_plugin_provider, AP_AUTH_INTERNAL_PER_CONF);
2133 // SHIB Module commands
2136 static command_rec shib_cmds[] = {
2137 AP_INIT_TAKE1("ShibPrefix", (config_fn_t)ap_set_global_string_slot, &g_szPrefix,
2138 RSRC_CONF, "Shibboleth installation directory"),
2139 AP_INIT_TAKE1("ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
2140 RSRC_CONF, "Path to shibboleth2.xml config file"),
2141 AP_INIT_TAKE1("ShibCatalogs", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
2142 RSRC_CONF, "Paths of XML schema catalogs"),
2143 AP_INIT_TAKE1("ShibGSSKey", (config_fn_t)ap_set_global_string_slot, &g_szGSSContextKey,
2144 RSRC_CONF, "Name of user data key containing GSS context established by GSS module"),
2146 AP_INIT_TAKE1("ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
2147 (void *) offsetof (shib_server_config, szScheme),
2148 RSRC_CONF, "URL scheme to force into generated URLs for a vhost"),
2150 AP_INIT_TAKE2("ShibRequestSetting", (config_fn_t)shib_table_set, nullptr,
2151 OR_AUTHCFG, "Set arbitrary Shibboleth request property for content"),
2153 AP_INIT_FLAG("ShibDisable", (config_fn_t)ap_set_flag_slot,
2154 (void *) offsetof (shib_dir_config, bOff),
2155 OR_AUTHCFG, "Disable all Shib module activity here to save processing effort"),
2156 AP_INIT_TAKE1("ShibApplicationId", (config_fn_t)ap_set_string_slot,
2157 (void *) offsetof (shib_dir_config, szApplicationId),
2158 OR_AUTHCFG, "Set Shibboleth applicationId property for content"),
2159 AP_INIT_FLAG("ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
2160 (void *) offsetof (shib_dir_config, bBasicHijack),
2161 OR_AUTHCFG, "(DEPRECATED) Respond to AuthType Basic and convert to shibboleth"),
2162 AP_INIT_FLAG("ShibRequireSession", (config_fn_t)ap_set_flag_slot,
2163 (void *) offsetof (shib_dir_config, bRequireSession),
2164 OR_AUTHCFG, "Initiates a new session if one does not exist"),
2165 AP_INIT_TAKE1("ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
2166 (void *) offsetof (shib_dir_config, szRequireWith),
2167 OR_AUTHCFG, "Initiates a new session if one does not exist using a specific SessionInitiator"),
2168 AP_INIT_FLAG("ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
2169 (void *) offsetof (shib_dir_config, bExportAssertion),
2170 OR_AUTHCFG, "Export SAML attribute assertion(s) to Shib-Attributes header"),
2171 AP_INIT_TAKE1("ShibRedirectToSSL", (config_fn_t)ap_set_string_slot,
2172 (void *) offsetof (shib_dir_config, szRedirectToSSL),
2173 OR_AUTHCFG, "Redirect non-SSL requests to designated port"),
2174 #ifdef SHIB_APACHE_24
2175 AP_INIT_FLAG("ShibRequestMapperAuthz", (config_fn_t)ap_set_flag_slot,
2176 (void *) offsetof (shib_dir_config, bRequestMapperAuthz),
2177 OR_AUTHCFG, "Support access control via shibboleth2.xml / RequestMapper"),
2179 AP_INIT_TAKE1("AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
2180 (void *) offsetof (shib_dir_config, szAuthGrpFile),
2181 OR_AUTHCFG, "Text file containing group names and member user IDs"),
2182 AP_INIT_TAKE1("ShibAccessControl", (config_fn_t)shib_set_acl_slot, nullptr,
2183 OR_AUTHCFG, "Set arbitrary Shibboleth access control plugin for content"),
2184 AP_INIT_FLAG("ShibRequireAll", (config_fn_t)ap_set_flag_slot,
2185 (void *) offsetof (shib_dir_config, bRequireAll),
2186 OR_AUTHCFG, "All require directives must match"),
2187 AP_INIT_FLAG("AuthzShibAuthoritative", (config_fn_t)ap_set_flag_slot,
2188 (void *) offsetof (shib_dir_config, bAuthoritative),
2189 OR_AUTHCFG, "Allow failed mod_shib htaccess authorization to fall through to other modules"),
2190 AP_INIT_FLAG("ShibCompatWith24", (config_fn_t)ap_set_flag_slot,
2191 (void *) offsetof (shib_dir_config, bCompatWith24),
2192 OR_AUTHCFG, "Support Apache 2.4-style require rules"),
2194 AP_INIT_FLAG("ShibUseEnvironment", (config_fn_t)ap_set_flag_slot,
2195 (void *) offsetof (shib_dir_config, bUseEnvVars),
2196 OR_AUTHCFG, "Export attributes using environment variables (default)"),
2197 AP_INIT_FLAG("ShibUseHeaders", (config_fn_t)ap_set_flag_slot,
2198 (void *) offsetof (shib_dir_config, bUseHeaders),
2199 OR_AUTHCFG, "Export attributes using custom HTTP headers"),
2200 AP_INIT_FLAG("ShibExpireRedirects", (config_fn_t)ap_set_flag_slot,
2201 (void *) offsetof (shib_dir_config, bExpireRedirects),
2202 OR_AUTHCFG, "Expire SP-generated redirects"),
2207 module AP_MODULE_DECLARE_DATA mod_shib = {
2208 STANDARD20_MODULE_STUFF,
2209 create_shib_dir_config, /* create dir config */
2210 merge_shib_dir_config, /* merge dir config --- default is to override */
2211 create_shib_server_config, /* create server config */
2212 merge_shib_server_config, /* merge server config */
2213 shib_cmds, /* command table */
2214 shib_register_hooks /* register hooks */