2 * Copyright 2001-2007 Internet2
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
20 * Apache module implementation
26 #undef _XOPEN_SOURCE // causes gethostname conflict in unistd.h
30 # define _CRT_NONSTDC_NO_DEPRECATE 1
31 # define _CRT_SECURE_NO_DEPRECATE 1
34 #include <shibsp/AbstractSPRequest.h>
35 #include <shibsp/AccessControl.h>
36 #include <shibsp/exceptions.h>
37 #include <shibsp/RequestMapper.h>
38 #include <shibsp/SPConfig.h>
39 #include <shibsp/ServiceProvider.h>
40 #include <shibsp/SessionCache.h>
41 #include <shibsp/attribute/Attribute.h>
42 #include <xercesc/util/XMLUniDefs.hpp>
43 #include <xercesc/util/regx/RegularExpression.hpp>
44 #include <xmltooling/XMLToolingConfig.h>
45 #include <xmltooling/util/NDC.h>
46 #include <xmltooling/util/Threads.h>
47 #include <xmltooling/util/XMLConstants.h>
48 #include <xmltooling/util/XMLHelper.h>
56 // Apache specific header files
58 #include <http_config.h>
59 #include <http_protocol.h>
60 #include <http_main.h>
62 #include <http_core.h>
64 #include <http_request.h>
66 #ifndef SHIB_APACHE_13
67 #include <apr_buckets.h>
68 #include <apr_strings.h>
69 #include <apr_pools.h>
78 #include <unistd.h> // for getpid()
81 using namespace shibsp;
82 using namespace xmltooling;
84 using xercesc::RegularExpression;
85 using xercesc::XMLException;
87 extern "C" module MODULE_VAR_EXPORT mod_shib;
90 char* g_szSHIBConfig = NULL;
91 char* g_szSchemaDir = NULL;
92 char* g_szPrefix = NULL;
93 SPConfig* g_Config = NULL;
94 string g_unsetHeaderValue,g_spoofKey;
95 bool g_checkSpoofing = true;
96 bool g_catchAll = false;
97 static const char* g_UserDataKey = "_shib_check_user_";
98 static const XMLCh path[] = UNICODE_LITERAL_4(p,a,t,h);
99 static const XMLCh validate[] = UNICODE_LITERAL_8(v,a,l,i,d,a,t,e);
102 /* Apache 2.2.x headers must be accumulated and set in the output filter.
103 Apache 2.0.49+ supports the filter method.
104 Apache 1.3.x and lesser 2.0.x must write the headers directly. */
106 #if (defined(SHIB_APACHE_20) || defined(SHIB_APACHE_22)) && AP_MODULE_MAGIC_AT_LEAST(20020903,6)
107 #define SHIB_DEFERRED_HEADERS
110 /********************************************************************************/
111 // Basic Apache Configuration code.
114 // per-server module configuration structure
115 struct shib_server_config
120 // creates the per-server configuration
121 extern "C" void* create_shib_server_config(SH_AP_POOL* p, server_rec* s)
123 shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
128 // overrides server configuration in virtual servers
129 extern "C" void* merge_shib_server_config (SH_AP_POOL* p, void* base, void* sub)
131 shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
132 shib_server_config* parent=(shib_server_config*)base;
133 shib_server_config* child=(shib_server_config*)sub;
136 sc->szScheme=ap_pstrdup(p,child->szScheme);
137 else if (parent->szScheme)
138 sc->szScheme=ap_pstrdup(p,parent->szScheme);
145 // per-dir module configuration structure
146 struct shib_dir_config
148 SH_AP_TABLE* tSettings; // generic table of extensible settings
151 char* szAuthGrpFile; // Auth GroupFile name
152 int bRequireAll; // all "known" require directives must match, otherwise OR logic
153 int bAuthoritative; // allow htaccess plugin to DECLINE when authz fails
155 // Content Configuration
156 char* szApplicationId; // Shib applicationId value
157 char* szRequireWith; // require a session using a specific initiator?
158 char* szRedirectToSSL; // redirect non-SSL requests to SSL port
159 int bOff; // flat-out disable all Shib processing
160 int bBasicHijack; // activate for AuthType Basic?
161 int bRequireSession; // require a session?
162 int bExportAssertion; // export SAML assertion to the environment?
163 int bUseEnvVars; // use environment?
164 int bUseHeaders; // use headers?
167 // creates per-directory config structure
168 extern "C" void* create_shib_dir_config (SH_AP_POOL* p, char* d)
170 shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
171 dc->tSettings = NULL;
172 dc->szAuthGrpFile = NULL;
173 dc->bRequireAll = -1;
174 dc->bAuthoritative = -1;
175 dc->szApplicationId = NULL;
176 dc->szRequireWith = NULL;
177 dc->szRedirectToSSL = NULL;
179 dc->bBasicHijack = -1;
180 dc->bRequireSession = -1;
181 dc->bExportAssertion = -1;
182 dc->bUseEnvVars = -1;
183 dc->bUseHeaders = -1;
187 // overrides server configuration in directories
188 extern "C" void* merge_shib_dir_config (SH_AP_POOL* p, void* base, void* sub)
190 shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
191 shib_dir_config* parent=(shib_dir_config*)base;
192 shib_dir_config* child=(shib_dir_config*)sub;
194 // The child supersedes any matching table settings in the parent.
195 dc->tSettings = NULL;
196 if (parent->tSettings)
197 dc->tSettings = ap_copy_table(p, parent->tSettings);
198 if (child->tSettings) {
200 ap_overlap_tables(dc->tSettings, child->tSettings, AP_OVERLAP_TABLES_SET);
202 dc->tSettings = ap_copy_table(p, child->tSettings);
205 if (child->szAuthGrpFile)
206 dc->szAuthGrpFile=ap_pstrdup(p,child->szAuthGrpFile);
207 else if (parent->szAuthGrpFile)
208 dc->szAuthGrpFile=ap_pstrdup(p,parent->szAuthGrpFile);
210 dc->szAuthGrpFile=NULL;
212 if (child->szApplicationId)
213 dc->szApplicationId=ap_pstrdup(p,child->szApplicationId);
214 else if (parent->szApplicationId)
215 dc->szApplicationId=ap_pstrdup(p,parent->szApplicationId);
217 dc->szApplicationId=NULL;
219 if (child->szRequireWith)
220 dc->szRequireWith=ap_pstrdup(p,child->szRequireWith);
221 else if (parent->szRequireWith)
222 dc->szRequireWith=ap_pstrdup(p,parent->szRequireWith);
224 dc->szRequireWith=NULL;
226 if (child->szRedirectToSSL)
227 dc->szRedirectToSSL=ap_pstrdup(p,child->szRedirectToSSL);
228 else if (parent->szRedirectToSSL)
229 dc->szRedirectToSSL=ap_pstrdup(p,parent->szRedirectToSSL);
231 dc->szRedirectToSSL=NULL;
233 dc->bOff=((child->bOff==-1) ? parent->bOff : child->bOff);
234 dc->bBasicHijack=((child->bBasicHijack==-1) ? parent->bBasicHijack : child->bBasicHijack);
235 dc->bRequireSession=((child->bRequireSession==-1) ? parent->bRequireSession : child->bRequireSession);
236 dc->bExportAssertion=((child->bExportAssertion==-1) ? parent->bExportAssertion : child->bExportAssertion);
237 dc->bRequireAll=((child->bRequireAll==-1) ? parent->bRequireAll : child->bRequireAll);
238 dc->bAuthoritative=((child->bAuthoritative==-1) ? parent->bAuthoritative : child->bAuthoritative);
239 dc->bUseEnvVars=((child->bUseEnvVars==-1) ? parent->bUseEnvVars : child->bUseEnvVars);
240 dc->bUseHeaders=((child->bUseHeaders==-1) ? parent->bUseHeaders : child->bUseHeaders);
244 // per-request module structure
245 struct shib_request_config
247 SH_AP_TABLE *env; // environment vars
248 #ifdef SHIB_DEFERRED_HEADERS
249 SH_AP_TABLE *hdr_out; // headers to browser
253 // create a request record
254 static shib_request_config *init_request_config(request_rec *r)
256 shib_request_config* rc=(shib_request_config*)ap_pcalloc(r->pool,sizeof(shib_request_config));
257 ap_set_module_config (r->request_config, &mod_shib, rc);
258 memset(rc, 0, sizeof(shib_request_config));
259 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_init_rc");
263 // generic global slot handlers
264 extern "C" const char* ap_set_global_string_slot(cmd_parms* parms, void*, const char* arg)
266 *((char**)(parms->info))=ap_pstrdup(parms->pool,arg);
270 extern "C" const char* shib_set_server_string_slot(cmd_parms* parms, void*, const char* arg)
272 char* base=(char*)ap_get_module_config(parms->server->module_config,&mod_shib);
273 size_t offset=(size_t)parms->info;
274 *((char**)(base + offset))=ap_pstrdup(parms->pool,arg);
278 extern "C" const char* shib_ap_set_file_slot(cmd_parms* parms,
279 #ifdef SHIB_APACHE_13
280 char* arg1, char* arg2
282 void* arg1, const char* arg2
286 ap_set_file_slot(parms, arg1, arg2);
290 extern "C" const char* shib_table_set(cmd_parms* parms, shib_dir_config* dc, const char* arg1, const char* arg2)
293 dc->tSettings = ap_make_table(parms->pool, 4);
294 ap_table_set(dc->tSettings, arg1, arg2);
298 /********************************************************************************/
299 // Apache ShibTarget subclass(es) here.
301 class ShibTargetApache : public AbstractSPRequest
304 mutable string m_body;
305 mutable bool m_gotBody,m_firsttime;
306 mutable vector<string> m_certs;
307 set<string> m_allhttp;
311 shib_dir_config* m_dc;
312 shib_server_config* m_sc;
313 shib_request_config* m_rc;
315 ShibTargetApache(request_rec* req, bool handler, bool shib_check_user)
316 : AbstractSPRequest(SHIBSP_LOGCAT".Apache"), m_handler(handler), m_gotBody(false),m_firsttime(true) {
317 m_sc = (shib_server_config*)ap_get_module_config(req->server->module_config, &mod_shib);
318 m_dc = (shib_dir_config*)ap_get_module_config(req->per_dir_config, &mod_shib);
319 m_rc = (shib_request_config*)ap_get_module_config(req->request_config, &mod_shib);
322 setRequestURI(m_req->unparsed_uri);
324 if (shib_check_user && m_dc->bUseHeaders == 1) {
325 // Try and see if this request was already processed, to skip spoof checking.
326 if (!ap_is_initial_req(m_req)) {
329 else if (!g_spoofKey.empty()) {
330 const char* hdr = ap_table_get(m_req->headers_in, "Shib-Spoof-Check");
331 if (hdr && g_spoofKey == hdr)
336 log(SPDebug, "shib_check_user running more than once");
339 virtual ~ShibTargetApache() {}
341 const char* getScheme() const {
342 return m_sc->szScheme ? m_sc->szScheme : ap_http_method(m_req);
344 const char* getHostname() const {
345 return ap_get_server_name(m_req);
347 int getPort() const {
348 return ap_get_server_port(m_req);
350 const char* getMethod() const {
351 return m_req->method;
353 string getContentType() const {
354 const char* type = ap_table_get(m_req->headers_in, "Content-Type");
355 return type ? type : "";
357 long getContentLength() const {
358 return m_gotBody ? m_body.length() : m_req->remaining;
360 string getRemoteAddr() const {
361 return m_req->connection->remote_ip;
363 void log(SPLogLevel level, const string& msg) const {
364 AbstractSPRequest::log(level,msg);
367 (level == SPDebug ? APLOG_DEBUG :
368 (level == SPInfo ? APLOG_INFO :
369 (level == SPWarn ? APLOG_WARNING :
370 (level == SPError ? APLOG_ERR : APLOG_CRIT))))|APLOG_NOERRNO,
375 const char* getQueryString() const { return m_req->args; }
376 const char* getRequestBody() const {
377 if (m_gotBody || m_req->method_number==M_GET)
378 return m_body.c_str();
379 #ifdef SHIB_APACHE_13
380 // Read the posted data
381 if (ap_setup_client_block(m_req, REQUEST_CHUNKED_DECHUNK) != OK) {
383 log(SPError, "Apache function (setup_client_block) failed while reading request body.");
384 return m_body.c_str();
386 if (!ap_should_client_block(m_req)) {
388 log(SPError, "Apache function (should_client_block) failed while reading request body.");
389 return m_body.c_str();
391 if (m_req->remaining > 1024*1024)
392 throw opensaml::SecurityPolicyException("Blocked request body larger than 1M size limit.");
395 char buff[HUGE_STRING_LEN];
396 ap_hard_timeout("[mod_shib] getRequestBody", m_req);
397 while ((len=ap_get_client_block(m_req, buff, sizeof(buff))) > 0) {
398 ap_reset_timeout(m_req);
399 m_body.append(buff, len);
401 ap_kill_timeout(m_req);
406 apr_bucket_brigade* bb = apr_brigade_create(m_req->pool, m_req->connection->bucket_alloc);
409 apr_status_t rv = ap_get_brigade(m_req->input_filters, bb, AP_MODE_READBYTES, APR_BLOCK_READ, HUGE_STRING_LEN);
410 if (rv != APR_SUCCESS) {
411 log(SPError, "Apache function (ap_get_brigade) failed while reading request body.");
415 for (bucket = APR_BRIGADE_FIRST(bb); bucket != APR_BRIGADE_SENTINEL(bb); bucket = APR_BUCKET_NEXT(bucket)) {
416 if (APR_BUCKET_IS_EOS(bucket)) {
421 /* We can't do much with this. */
422 if (APR_BUCKET_IS_FLUSH(bucket))
426 apr_bucket_read(bucket, &data, &len, APR_BLOCK_READ);
428 m_body.append(data, len);
430 apr_brigade_cleanup(bb);
432 apr_brigade_destroy(bb);
435 return m_body.c_str();
437 void clearHeader(const char* rawname, const char* cginame) {
438 if (m_dc->bUseHeaders == 1) {
439 // ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_clear_header: hdr\n");
440 if (g_checkSpoofing && m_firsttime) {
441 if (m_allhttp.empty()) {
442 // First time, so populate set with "CGI" versions of client-supplied headers.
443 #ifdef SHIB_APACHE_13
444 array_header *hdrs_arr = ap_table_elts(m_req->headers_in);
445 table_entry *hdrs = (table_entry *) hdrs_arr->elts;
447 const apr_array_header_t *hdrs_arr = apr_table_elts(m_req->headers_in);
448 const apr_table_entry_t *hdrs = (const apr_table_entry_t *) hdrs_arr->elts;
450 for (int i = 0; i < hdrs_arr->nelts; ++i) {
453 string cgiversion("HTTP_");
454 const char* pch = hdrs[i].key;
456 cgiversion += (isalnum(*pch) ? toupper(*pch) : '_');
459 m_allhttp.insert(cgiversion);
463 if (m_allhttp.count(cginame) > 0)
464 throw opensaml::SecurityPolicyException("Attempt to spoof header ($1) was detected.", params(1, rawname));
466 ap_table_unset(m_req->headers_in, rawname);
467 ap_table_set(m_req->headers_in, rawname, g_unsetHeaderValue.c_str());
470 void setHeader(const char* name, const char* value) {
471 if (m_dc->bUseEnvVars != 0) {
473 // this happens on subrequests
474 // ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_setheader: no_m_rc\n");
475 m_rc = init_request_config(m_req);
478 m_rc->env = ap_make_table(m_req->pool, 10);
479 // ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_set_env: %s=%s\n", name, value?value:"Null");
480 ap_table_set(m_rc->env, name, value ? value : "");
482 if (m_dc->bUseHeaders == 1)
483 ap_table_set(m_req->headers_in, name, value);
485 string getHeader(const char* name) const {
486 const char* hdr = ap_table_get(m_req->headers_in, name);
487 return string(hdr ? hdr : "");
489 string getSecureHeader(const char* name) const {
490 if (m_dc->bUseEnvVars != 0) {
492 if (m_rc && m_rc->env)
493 hdr = ap_table_get(m_rc->env, name);
496 return string(hdr ? hdr : "");
498 return getHeader(name);
500 void setRemoteUser(const char* user) {
501 SH_AP_USER(m_req) = user ? ap_pstrdup(m_req->pool, user) : NULL;
503 string getRemoteUser() const {
504 return string(SH_AP_USER(m_req) ? SH_AP_USER(m_req) : "");
506 void setContentType(const char* type) {
507 m_req->content_type = ap_psprintf(m_req->pool, type);
509 void setResponseHeader(const char* name, const char* value) {
510 #ifdef SHIB_DEFERRED_HEADERS
512 // this happens on subrequests
513 m_rc = init_request_config(m_req);
515 ap_table_add(m_rc->hdr_out, name, value);
518 ap_table_add(m_req->err_headers_out, name, value);
520 long sendResponse(istream& in, long status) {
521 if (status != XMLTOOLING_HTTP_STATUS_OK)
522 m_req->status = status;
523 ap_send_http_header(m_req);
527 ap_rwrite(buf,in.gcount(),m_req);
529 #if (defined(SHIB_APACHE_20) || defined(SHIB_APACHE_22))
530 if (status != XMLTOOLING_HTTP_STATUS_OK && status != XMLTOOLING_HTTP_STATUS_ERROR)
535 long sendRedirect(const char* url) {
536 ap_table_set(m_req->headers_out, "Location", url);
539 const vector<string>& getClientCertificates() const {
540 if (m_certs.empty()) {
541 const char* cert = ap_table_get(m_req->subprocess_env, "SSL_CLIENT_CERT");
543 m_certs.push_back(cert);
546 cert = ap_table_get(m_req->subprocess_env, ap_psprintf(m_req->pool, "SSL_CLIENT_CERT_CHAIN_%d", i++));
548 m_certs.push_back(cert);
553 long returnDecline(void) { return DECLINED; }
554 long returnOK(void) { return OK; }
557 /********************************************************************************/
560 extern "C" int shib_check_user(request_rec* r)
562 // Short-circuit entirely?
563 if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
566 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_check_user(%d): ENTER", (int)getpid());
568 ostringstream threadid;
569 threadid << "[" << getpid() << "] shib_check_user" << '\0';
570 xmltooling::NDC ndc(threadid.str().c_str());
573 ShibTargetApache sta(r,false,true);
575 // Check user authentication and export information, then set the handler bypass
576 pair<bool,long> res = sta.getServiceProvider().doAuthentication(sta,true);
577 apr_pool_userdata_setn((const void*)42,g_UserDataKey,NULL,r->pool);
578 // If directed, install a spoof key to recognize when we've already cleared headers.
579 if (!g_spoofKey.empty() && (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bUseHeaders==1))
580 ap_table_set(r->headers_in, "Shib-Spoof-Check", g_spoofKey.c_str());
581 if (res.first) return res.second;
583 // user auth was okay -- export the assertions now
584 res = sta.getServiceProvider().doExport(sta);
585 if (res.first) return res.second;
587 // export happened successfully.. this user is ok.
590 catch (exception& e) {
591 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user threw an exception: %s", e.what());
595 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user threw an unknown exception!");
602 extern "C" int shib_handler(request_rec* r)
604 // Short-circuit entirely?
605 if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
608 ostringstream threadid;
609 threadid << "[" << getpid() << "] shib_handler" << '\0';
610 xmltooling::NDC ndc(threadid.str().c_str());
612 #ifndef SHIB_APACHE_13
613 // With 2.x, this handler always runs, though last.
614 // We check if shib_check_user ran, because it will detect a handler request
615 // and dispatch it directly.
617 apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
618 if (data==(const void*)42) {
619 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler skipped since check_user ran");
624 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler(%d): ENTER: %s", (int)getpid(), r->handler);
627 ShibTargetApache sta(r,true,false);
629 pair<bool,long> res = sta.getServiceProvider().doHandler(sta);
630 if (res.first) return res.second;
632 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "doHandler() did not do anything.");
635 catch (exception& e) {
636 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler threw an exception: %s", e.what());
640 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler threw an unknown exception!");
648 * shib_auth_checker() -- a simple resource manager to
649 * process the .htaccess settings
651 extern "C" int shib_auth_checker(request_rec* r)
653 // Short-circuit entirely?
654 if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
657 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_auth_checker(%d): ENTER", (int)getpid());
659 ostringstream threadid;
660 threadid << "[" << getpid() << "] shib_auth_checker" << '\0';
661 xmltooling::NDC ndc(threadid.str().c_str());
664 ShibTargetApache sta(r,false,false);
666 pair<bool,long> res = sta.getServiceProvider().doAuthorization(sta);
667 if (res.first) return res.second;
669 // The SP method should always return true, so if we get this far, something unusual happened.
670 // Just let Apache (or some other module) decide what to do.
673 catch (exception& e) {
674 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an exception: %s", e.what());
678 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an unknown exception!");
685 // Access control plugin that enforces htaccess rules
686 class htAccessControl : virtual public AccessControl
690 ~htAccessControl() {}
691 Lockable* lock() {return this;}
693 aclresult_t authorized(const SPRequest& request, const Session* session) const;
695 bool checkAttribute(const SPRequest& request, const Attribute* attr, const char* toMatch, RegularExpression* re) const;
698 AccessControl* htAccessFactory(const xercesc::DOMElement* const & e)
700 return new htAccessControl();
703 class ApacheRequestMapper : public virtual RequestMapper, public virtual PropertySet
706 ApacheRequestMapper(const xercesc::DOMElement* e);
707 ~ApacheRequestMapper() { delete m_mapper; delete m_htaccess; delete m_staKey; delete m_propsKey; }
708 Lockable* lock() { return m_mapper->lock(); }
709 void unlock() { m_staKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
710 Settings getSettings(const HTTPRequest& request) const;
712 const PropertySet* getParent() const { return NULL; }
713 void setParent(const PropertySet*) {}
714 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
715 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
716 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
717 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
718 pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
719 void getAll(map<string,const char*>& properties) const;
720 const PropertySet* getPropertySet(const char* name, const char* ns=shibspconstants::ASCII_SHIB2SPCONFIG_NS) const;
721 const xercesc::DOMElement* getElement() const;
724 RequestMapper* m_mapper;
726 ThreadKey* m_propsKey;
727 AccessControl* m_htaccess;
730 RequestMapper* ApacheRequestMapFactory(const xercesc::DOMElement* const & e)
732 return new ApacheRequestMapper(e);
735 ApacheRequestMapper::ApacheRequestMapper(const xercesc::DOMElement* e) : m_mapper(NULL), m_staKey(NULL), m_propsKey(NULL), m_htaccess(NULL)
737 m_mapper=SPConfig::getConfig().RequestMapperManager.newPlugin(XML_REQUEST_MAPPER,e);
738 m_htaccess=new htAccessControl();
739 m_staKey=ThreadKey::create(NULL);
740 m_propsKey=ThreadKey::create(NULL);
743 RequestMapper::Settings ApacheRequestMapper::getSettings(const HTTPRequest& request) const
745 Settings s=m_mapper->getSettings(request);
746 m_staKey->setData((void*)dynamic_cast<const ShibTargetApache*>(&request));
747 m_propsKey->setData((void*)s.first);
748 return pair<const PropertySet*,AccessControl*>(this,s.second ? s.second : m_htaccess);
751 pair<bool,bool> ApacheRequestMapper::getBool(const char* name, const char* ns) const
753 const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
754 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
756 // Override Apache-settable boolean properties.
757 if (name && !strcmp(name,"requireSession") && sta->m_dc->bRequireSession != -1)
758 return make_pair(true, sta->m_dc->bRequireSession==1);
759 else if (name && !strcmp(name,"exportAssertion") && sta->m_dc->bExportAssertion != -1)
760 return make_pair(true, sta->m_dc->bExportAssertion==1);
761 else if (sta->m_dc->tSettings) {
762 const char* prop = ap_table_get(sta->m_dc->tSettings, name);
764 return make_pair(true, !strcmp(prop, "true") || !strcmp(prop, "1") || !strcmp(prop, "On"));
767 return s ? s->getBool(name,ns) : make_pair(false,false);
770 pair<bool,const char*> ApacheRequestMapper::getString(const char* name, const char* ns) const
772 const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
773 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
775 // Override Apache-settable string properties.
776 if (name && !strcmp(name,"authType")) {
777 const char *auth_type=ap_auth_type(sta->m_req);
779 // Check for Basic Hijack
780 if (!strcasecmp(auth_type, "basic") && sta->m_dc->bBasicHijack == 1)
781 auth_type = "shibboleth";
782 return make_pair(true,auth_type);
785 else if (name && !strcmp(name,"applicationId") && sta->m_dc->szApplicationId)
786 return pair<bool,const char*>(true,sta->m_dc->szApplicationId);
787 else if (name && !strcmp(name,"requireSessionWith") && sta->m_dc->szRequireWith)
788 return pair<bool,const char*>(true,sta->m_dc->szRequireWith);
789 else if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
790 return pair<bool,const char*>(true,sta->m_dc->szRedirectToSSL);
791 else if (sta->m_dc->tSettings) {
792 const char* prop = ap_table_get(sta->m_dc->tSettings, name);
794 return make_pair(true, prop);
797 return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
800 pair<bool,const XMLCh*> ApacheRequestMapper::getXMLString(const char* name, const char* ns) const
802 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
803 return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
806 pair<bool,unsigned int> ApacheRequestMapper::getUnsignedInt(const char* name, const char* ns) const
808 const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
809 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
811 // Override Apache-settable int properties.
812 if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
813 return pair<bool,unsigned int>(true, strtol(sta->m_dc->szRedirectToSSL, NULL, 10));
814 else if (sta->m_dc->tSettings) {
815 const char* prop = ap_table_get(sta->m_dc->tSettings, name);
817 return pair<bool,unsigned int>(true, atoi(prop));
820 return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
823 pair<bool,int> ApacheRequestMapper::getInt(const char* name, const char* ns) const
825 const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
826 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
828 // Override Apache-settable int properties.
829 if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
830 return pair<bool,int>(true,atoi(sta->m_dc->szRedirectToSSL));
831 else if (sta->m_dc->tSettings) {
832 const char* prop = ap_table_get(sta->m_dc->tSettings, name);
834 return make_pair(true, atoi(prop));
837 return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
840 void ApacheRequestMapper::getAll(map<string,const char*>& properties) const
842 const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
843 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
846 s->getAll(properties);
850 const char* auth_type=ap_auth_type(sta->m_req);
852 // Check for Basic Hijack
853 if (!strcasecmp(auth_type, "basic") && sta->m_dc->bBasicHijack == 1)
854 auth_type = "shibboleth";
855 properties["authType"] = auth_type;
858 if (sta->m_dc->szApplicationId)
859 properties["applicationId"] = sta->m_dc->szApplicationId;
860 if (sta->m_dc->szRequireWith)
861 properties["requireSessionWith"] = sta->m_dc->szRequireWith;
862 if (sta->m_dc->szRedirectToSSL)
863 properties["redirectToSSL"] = sta->m_dc->szRedirectToSSL;
864 if (sta->m_dc->bRequireSession != 0)
865 properties["requireSession"] = (sta->m_dc->bRequireSession==1) ? "true" : "false";
866 if (sta->m_dc->bExportAssertion != 0)
867 properties["exportAssertion"] = (sta->m_dc->bExportAssertion==1) ? "true" : "false";
870 const PropertySet* ApacheRequestMapper::getPropertySet(const char* name, const char* ns) const
872 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
873 return s ? s->getPropertySet(name,ns) : NULL;
876 const xercesc::DOMElement* ApacheRequestMapper::getElement() const
878 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
879 return s ? s->getElement() : NULL;
882 static SH_AP_TABLE* groups_for_user(request_rec* r, const char* user, char* grpfile)
885 SH_AP_TABLE* grps=ap_make_table(r->pool,15);
886 char l[MAX_STRING_LEN];
887 const char *group_name, *ll, *w;
889 #ifdef SHIB_APACHE_13
890 if (!(f=ap_pcfg_openfile(r->pool,grpfile))) {
892 if (ap_pcfg_openfile(&f,r->pool,grpfile) != APR_SUCCESS) {
894 ap_log_rerror(APLOG_MARK,APLOG_DEBUG,SH_AP_R(r),"groups_for_user() could not open group file: %s\n",grpfile);
899 #ifdef SHIB_APACHE_13
900 sp=ap_make_sub_pool(r->pool);
902 if (apr_pool_create(&sp,r->pool) != APR_SUCCESS) {
903 ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,
904 "groups_for_user() could not create a subpool");
909 while (!(ap_cfg_getline(l,MAX_STRING_LEN,f))) {
910 if ((*l=='#') || (!*l))
915 group_name=ap_getword(sp,&ll,':');
918 w=ap_getword_conf(sp,&ll);
919 if (!strcmp(w,user)) {
920 ap_table_setn(grps,ap_pstrdup(r->pool,group_name),"in");
930 bool htAccessControl::checkAttribute(const SPRequest& request, const Attribute* attr, const char* toMatch, RegularExpression* re) const
932 bool caseSensitive = attr->isCaseSensitive();
933 const vector<string>& vals = attr->getSerializedValues();
934 for (vector<string>::const_iterator v=vals.begin(); v!=vals.end(); ++v) {
936 auto_arrayptr<XMLCh> trans(fromUTF8(v->c_str()));
937 if (re->matches(trans.get())) {
938 if (request.isPriorityEnabled(SPRequest::SPDebug))
939 request.log(SPRequest::SPDebug, string("htaccess: expecting regexp ") + toMatch + ", got " + *v + ": acccepted");
943 else if ((caseSensitive && *v == toMatch) || (!caseSensitive && !strcasecmp(v->c_str(), toMatch))) {
944 if (request.isPriorityEnabled(SPRequest::SPDebug))
945 request.log(SPRequest::SPDebug, string("htaccess: expecting ") + toMatch + ", got " + *v + ": accepted");
948 else if (request.isPriorityEnabled(SPRequest::SPDebug)) {
949 request.log(SPRequest::SPDebug, string("htaccess: expecting ") + toMatch + ", got " + *v + ": rejected");
955 AccessControl::aclresult_t htAccessControl::authorized(const SPRequest& request, const Session* session) const
957 // Make sure the object is our type.
958 const ShibTargetApache* sta=dynamic_cast<const ShibTargetApache*>(&request);
960 throw ConfigurationException("Request wrapper object was not of correct type.");
964 int m=sta->m_req->method_number;
965 bool method_restricted=false;
968 const array_header* reqs_arr=ap_requires(sta->m_req);
970 return shib_acl_indeterminate; // should never happen
972 require_line* reqs=(require_line*)reqs_arr->elts;
974 for (int x=0; x<reqs_arr->nelts; x++) {
975 // This rule should be completely ignored, the method doesn't fit.
976 // The rule just doesn't exist for our purposes.
977 if (!(reqs[x].method_mask & (1 << m)))
980 method_restricted=true; // this lets us know at the end that at least one rule was potentially enforcable.
982 // Tracks status of this rule's evaluation.
985 string remote_user = request.getRemoteUser();
987 t = reqs[x].requirement;
988 w = ap_getword_white(sta->m_req->pool, &t);
990 if (!strcasecmp(w,"shibboleth")) {
991 // This is a dummy rule needed because Apache conflates authn and authz.
992 // Without some require rule, AuthType is ignored and no check_user hooks run.
993 status = true; // treat it as an "accepted" rule
995 else if (!strcmp(w,"valid-user") && session) {
996 request.log(SPRequest::SPDebug, "htaccess: accepting valid-user based on active session");
999 else if (!strcmp(w,"user") && !remote_user.empty()) {
1000 bool regexp=false,negate=false;
1002 w=ap_getword_conf(sta->m_req->pool,&t);
1014 // Figure out if there's a match.
1018 // To do regex matching, we have to convert from UTF-8.
1019 auto_arrayptr<XMLCh> trans(fromUTF8(w));
1020 RegularExpression re(trans.get());
1021 auto_arrayptr<XMLCh> trans2(fromUTF8(remote_user.c_str()));
1022 match = re.matches(trans2.get());
1024 catch (XMLException& ex) {
1025 auto_ptr_char tmp(ex.getMessage());
1026 request.log(SPRequest::SPError,
1027 string("htaccess plugin caught exception while parsing regular expression (") + w + "): " + tmp.get());
1030 else if (remote_user==w) {
1035 // If we matched, then we're done with this rule either way and status is set to reflect the outcome.
1037 if (request.isPriorityEnabled(SPRequest::SPDebug))
1038 request.log(SPRequest::SPDebug,
1039 string("htaccess: require user ") + (negate ? "rejecting (" : "accepting (") + remote_user + ")");
1044 else if (!strcmp(w,"group") && !remote_user.empty()) {
1045 SH_AP_TABLE* grpstatus=NULL;
1046 if (sta->m_dc->szAuthGrpFile) {
1047 if (request.isPriorityEnabled(SPRequest::SPDebug))
1048 request.log(SPRequest::SPDebug,string("htaccess plugin using groups file: ") + sta->m_dc->szAuthGrpFile);
1049 grpstatus=groups_for_user(sta->m_req,remote_user.c_str(),sta->m_dc->szAuthGrpFile);
1054 w=ap_getword_conf(sta->m_req->pool,&t);
1060 if (grpstatus && ap_table_get(grpstatus,w)) {
1061 // If we matched, then we're done with this rule either way and status is set to reflect the outcome.
1063 request.log(SPRequest::SPDebug, string("htaccess: require group ") + (negate ? "rejecting (" : "accepting (") + w + ")");
1068 else if (!strcmp(w,"authnContextClassRef") || !strcmp(w,"authnContextDeclRef")) {
1069 const char* ref = !strcmp(w,"authnContextClassRef") ? session->getAuthnContextClassRef() : session->getAuthnContextDeclRef();
1070 bool regexp=false,negate=false;
1072 w=ap_getword_conf(sta->m_req->pool,&t);
1084 // Figure out if there's a match.
1088 // To do regex matching, we have to convert from UTF-8.
1089 RegularExpression re(w);
1090 match = re.matches(ref);
1092 catch (XMLException& ex) {
1093 auto_ptr_char tmp(ex.getMessage());
1094 request.log(SPRequest::SPError,
1095 string("htaccess plugin caught exception while parsing regular expression (") + w + "): " + tmp.get());
1098 else if (!strcmp(w,ref)) {
1103 // If we matched, then we're done with this rule either way and status is set to reflect the outcome.
1105 if (request.isPriorityEnabled(SPRequest::SPDebug))
1106 request.log(SPRequest::SPDebug,
1107 string("htaccess: require authnContext ") + (negate ? "rejecting (" : "accepting (") + ref + ")");
1112 else if (!session) {
1113 request.log(SPRequest::SPError, string("htaccess: require ") + w + " not given a valid session, are you using lazy sessions?");
1116 // Find the attribute(s) matching the require rule.
1117 pair<multimap<string,const Attribute*>::const_iterator,multimap<string,const Attribute*>::const_iterator> attrs =
1118 session->getIndexedAttributes().equal_range(w);
1121 while (!status && attrs.first!=attrs.second && *t) {
1122 w=ap_getword_conf(sta->m_req->pool,&t);
1129 auto_ptr<RegularExpression> re;
1131 delete re.release();
1132 auto_arrayptr<XMLCh> trans(fromUTF8(w));
1133 auto_ptr<xercesc::RegularExpression> temp(new xercesc::RegularExpression(trans.get()));
1137 for (; !status && attrs.first!=attrs.second; ++attrs.first) {
1138 if (checkAttribute(request, attrs.first->second, w, regexp ? re.get() : NULL)) {
1143 catch (XMLException& ex) {
1144 auto_ptr_char tmp(ex.getMessage());
1145 request.log(SPRequest::SPError,
1146 string("htaccess plugin caught exception while parsing regular expression (") + w + "): " + tmp.get()
1152 // If status is false, we found a rule we couldn't satisfy.
1153 // Could be an unknown rule to us, or it just didn't match.
1155 if (status && sta->m_dc->bRequireAll != 1) {
1156 // If we're not insisting that all rules be met, then we're done.
1157 request.log(SPRequest::SPDebug, "htaccess: a rule was successful, granting access");
1158 return shib_acl_true;
1160 else if (!status && sta->m_dc->bRequireAll == 1) {
1161 // If we're insisting that all rules be met, which is not something Apache really handles well,
1162 // then we either return false or indeterminate based on the authoritative option, which defaults on.
1163 if (sta->m_dc->bAuthoritative != 0) {
1164 request.log(SPRequest::SPDebug, "htaccess: a rule was unsuccessful, denying access");
1165 return shib_acl_false;
1168 request.log(SPRequest::SPDebug, "htaccess: a rule was unsuccessful but not authoritative, leaving it up to Apache");
1169 return shib_acl_indeterminate;
1172 // Otherwise, we keep going. If we're requring all, then we have to check every rule.
1173 // If not we just didn't find a successful rule yet, so we keep going anyway.
1176 // If we get here, we either "failed" or we're in require all mode (but not both).
1177 // If no rules possibly apply or we insisted that all rules check out, then we're good.
1178 if (!method_restricted) {
1179 request.log(SPRequest::SPDebug, "htaccess: no rules applied to this request method, granting access");
1180 return shib_acl_true;
1182 else if (sta->m_dc->bRequireAll == 1) {
1183 request.log(SPRequest::SPDebug, "htaccess: all rules successful, granting access");
1184 return shib_acl_true;
1186 else if (sta->m_dc->bAuthoritative != 0) {
1187 request.log(SPRequest::SPDebug, "htaccess: no rules were successful, denying access");
1188 return shib_acl_false;
1191 request.log(SPRequest::SPDebug, "htaccess: no rules were successful but not authoritative, leaving it up to Apache");
1192 return shib_acl_indeterminate;
1196 // Initial look at a request - create the per-request structure
1197 static int shib_post_read(request_rec *r)
1199 shib_request_config* rc = init_request_config(r);
1201 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_post_read");
1203 #ifdef SHIB_DEFERRED_HEADERS
1204 rc->hdr_out = ap_make_table(r->pool, 5);
1209 // fixups: set environment vars
1211 extern "C" int shib_fixups(request_rec* r)
1213 shib_request_config *rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
1214 shib_dir_config *dc = (shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib);
1215 if (dc->bOff==1 || dc->bUseEnvVars==0)
1218 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_fixup(%d): ENTER", (int)getpid());
1220 if (rc==NULL || rc->env==NULL || ap_is_empty_table(rc->env))
1223 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_fixup adding %d vars", ap_table_elts(rc->env)->nelts);
1224 r->subprocess_env = ap_overlay_tables(r->pool, r->subprocess_env, rc->env);
1229 #ifdef SHIB_APACHE_13
1232 * Cleanup the (per-process) pool info.
1234 extern "C" void shib_child_exit(server_rec* s, SH_AP_POOL* p)
1237 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit(%d) dealing with g_Config..", (int)getpid());
1240 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit() done");
1246 * Apache 2.x doesn't allow for per-child cleanup, causes CGI forks to hang.
1248 extern "C" apr_status_t shib_exit(void* data)
1254 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,0,NULL,"shib_exit() done");
1260 * shire_child_init()
1261 * Things to do when the child process is initialized.
1262 * (or after the configs are read in apache-2)
1264 #ifdef SHIB_APACHE_13
1265 extern "C" void shib_child_init(server_rec* s, SH_AP_POOL* p)
1267 extern "C" void shib_child_init(apr_pool_t* p, server_rec* s)
1270 // Initialize runtime components.
1272 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init(%d) starting", (int)getpid());
1275 ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() already initialized!");
1279 g_Config=&SPConfig::getConfig();
1280 g_Config->setFeatures(
1281 SPConfig::Listener |
1283 SPConfig::RequestMapping |
1284 SPConfig::InProcess |
1288 if (!g_Config->init(g_szSchemaDir, g_szPrefix)) {
1289 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize libraries");
1292 g_Config->AccessControlManager.registerFactory(HT_ACCESS_CONTROL,&htAccessFactory);
1293 g_Config->RequestMapperManager.registerFactory(NATIVE_REQUEST_MAPPER,&ApacheRequestMapFactory);
1296 if (!g_Config->instantiate(g_szSHIBConfig, true))
1297 throw runtime_error("unknown error");
1299 catch (exception& ex) {
1300 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),ex.what());
1301 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to load configuration");
1305 ServiceProvider* sp=g_Config->getServiceProvider();
1306 xmltooling::Locker locker(sp);
1307 const PropertySet* props=sp->getPropertySet("Local");
1309 pair<bool,const char*> unsetValue=props->getString("unsetHeaderValue");
1310 if (unsetValue.first)
1311 g_unsetHeaderValue = unsetValue.second;
1312 pair<bool,bool> flag=props->getBool("checkSpoofing");
1313 g_checkSpoofing = !flag.first || flag.second;
1314 if (g_checkSpoofing) {
1315 unsetValue=props->getString("spoofKey");
1316 if (unsetValue.first)
1317 g_spoofKey = unsetValue.second;
1319 flag=props->getBool("catchAll");
1320 g_catchAll = flag.first && flag.second;
1323 // Set the cleanup handler
1324 apr_pool_cleanup_register(p, NULL, &shib_exit, apr_pool_cleanup_null);
1326 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() done");
1330 #ifdef SHIB_DEFERRED_HEADERS
1331 static void set_output_filter(request_rec *r)
1333 ap_add_output_filter("SHIB_HEADERS_OUT", NULL, r, r->connection);
1336 static void set_error_filter(request_rec *r)
1338 ap_add_output_filter("SHIB_HEADERS_ERR", NULL, r, r->connection);
1341 static int _table_add(void *v, const char *key, const char *value)
1343 apr_table_addn((apr_table_t*)v, key, value);
1347 static apr_status_t do_output_filter(ap_filter_t *f, apr_bucket_brigade *in)
1349 request_rec *r = f->r;
1350 shib_request_config *rc = (shib_request_config*) ap_get_module_config(r->request_config, &mod_shib);
1353 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_out_filter: merging %d headers", apr_table_elts(rc->hdr_out)->nelts);
1354 apr_table_do(_table_add,r->headers_out, rc->hdr_out,NULL);
1355 // can't use overlap call because it will collapse Set-Cookie headers
1356 //apr_table_overlap(r->headers_out, rc->hdr_out, APR_OVERLAP_TABLES_MERGE);
1359 /* remove ourselves from the filter chain */
1360 ap_remove_output_filter(f);
1362 /* send the data up the stack */
1363 return ap_pass_brigade(f->next,in);
1366 static apr_status_t do_error_filter(ap_filter_t *f, apr_bucket_brigade *in)
1368 request_rec *r = f->r;
1369 shib_request_config *rc = (shib_request_config*) ap_get_module_config(r->request_config, &mod_shib);
1372 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_err_filter: merging %d headers", apr_table_elts(rc->hdr_out)->nelts);
1373 apr_table_do(_table_add,r->err_headers_out, rc->hdr_out,NULL);
1374 // can't use overlap call because it will collapse Set-Cookie headers
1375 //apr_table_overlap(r->err_headers_out, rc->hdr_out, APR_OVERLAP_TABLES_MERGE);
1378 /* remove ourselves from the filter chain */
1379 ap_remove_output_filter(f);
1381 /* send the data up the stack */
1382 return ap_pass_brigade(f->next,in);
1384 #endif // SHIB_DEFERRED_HEADERS
1386 typedef const char* (*config_fn_t)(void);
1388 #ifdef SHIB_APACHE_13
1390 // SHIB Module commands
1392 static command_rec shire_cmds[] = {
1393 {"ShibPrefix", (config_fn_t)ap_set_global_string_slot, &g_szPrefix,
1394 RSRC_CONF, TAKE1, "Shibboleth installation directory"},
1395 {"ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1396 RSRC_CONF, TAKE1, "Path to shibboleth.xml config file"},
1397 {"ShibCatalogs", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1398 RSRC_CONF, TAKE1, "Paths of XML schema catalogs"},
1400 {"ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
1401 (void *) XtOffsetOf (shib_server_config, szScheme),
1402 RSRC_CONF, TAKE1, "URL scheme to force into generated URLs for a vhost"},
1404 {"ShibRequestSetting", (config_fn_t)shib_table_set, NULL,
1405 OR_AUTHCFG, TAKE2, "Set arbitrary Shibboleth request property for content"},
1407 {"ShibDisable", (config_fn_t)ap_set_flag_slot,
1408 (void *) XtOffsetOf (shib_dir_config, bOff),
1409 OR_AUTHCFG, FLAG, "Disable all Shib module activity here to save processing effort"},
1410 {"ShibApplicationId", (config_fn_t)ap_set_string_slot,
1411 (void *) XtOffsetOf (shib_dir_config, szApplicationId),
1412 OR_AUTHCFG, TAKE1, "Set Shibboleth applicationId property for content"},
1413 {"ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1414 (void *) XtOffsetOf (shib_dir_config, bBasicHijack),
1415 OR_AUTHCFG, FLAG, "Respond to AuthType Basic and convert to shibboleth"},
1416 {"ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1417 (void *) XtOffsetOf (shib_dir_config, bRequireSession),
1418 OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist"},
1419 {"ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
1420 (void *) XtOffsetOf (shib_dir_config, szRequireWith),
1421 OR_AUTHCFG, TAKE1, "Initiates a new session if one does not exist using a specific SessionInitiator"},
1422 {"ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1423 (void *) XtOffsetOf (shib_dir_config, bExportAssertion),
1424 OR_AUTHCFG, FLAG, "Export SAML attribute assertion(s) to Shib-Attributes header"},
1425 {"ShibRedirectToSSL", (config_fn_t)ap_set_string_slot,
1426 (void *) XtOffsetOf (shib_dir_config, szRedirectToSSL),
1427 OR_AUTHCFG, TAKE1, "Redirect non-SSL requests to designated port" },
1428 {"AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
1429 (void *) XtOffsetOf (shib_dir_config, szAuthGrpFile),
1430 OR_AUTHCFG, TAKE1, "text file containing group names and member user IDs"},
1431 {"ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1432 (void *) XtOffsetOf (shib_dir_config, bRequireAll),
1433 OR_AUTHCFG, FLAG, "All require directives must match"},
1434 {"AuthzShibAuthoritative", (config_fn_t)ap_set_flag_slot,
1435 (void *) XtOffsetOf (shib_dir_config, bAuthoritative),
1436 OR_AUTHCFG, FLAG, "Allow failed mod_shib htaccess authorization to fall through to other modules"},
1437 {"ShibUseEnvironment", (config_fn_t)ap_set_flag_slot,
1438 (void *) XtOffsetOf (shib_dir_config, bUseEnvVars),
1439 OR_AUTHCFG, FLAG, "Export attributes using environment variables (default)"},
1440 {"ShibUseHeaders", (config_fn_t)ap_set_flag_slot,
1441 (void *) XtOffsetOf (shib_dir_config, bUseHeaders),
1442 OR_AUTHCFG, FLAG, "Export attributes using custom HTTP headers"},
1448 handler_rec shib_handlers[] = {
1449 { "shib-handler", shib_handler },
1453 module MODULE_VAR_EXPORT mod_shib = {
1454 STANDARD_MODULE_STUFF,
1455 NULL, /* initializer */
1456 create_shib_dir_config, /* dir config creater */
1457 merge_shib_dir_config, /* dir merger --- default is to override */
1458 create_shib_server_config, /* server config */
1459 merge_shib_server_config, /* merge server config */
1460 shire_cmds, /* command table */
1461 shib_handlers, /* handlers */
1462 NULL, /* filename translation */
1463 shib_check_user, /* check_user_id */
1464 shib_auth_checker, /* check auth */
1465 NULL, /* check access */
1466 NULL, /* type_checker */
1467 shib_fixups, /* fixups */
1469 NULL, /* header parser */
1470 shib_child_init, /* child_init */
1471 shib_child_exit, /* child_exit */
1472 shib_post_read /* post read-request */
1475 #elif defined(SHIB_APACHE_20) || defined(SHIB_APACHE_22)
1477 extern "C" void shib_register_hooks (apr_pool_t *p)
1479 #ifdef SHIB_DEFERRED_HEADERS
1480 ap_register_output_filter("SHIB_HEADERS_OUT", do_output_filter, NULL, AP_FTYPE_CONTENT_SET);
1481 ap_hook_insert_filter(set_output_filter, NULL, NULL, APR_HOOK_LAST);
1482 ap_register_output_filter("SHIB_HEADERS_ERR", do_error_filter, NULL, AP_FTYPE_CONTENT_SET);
1483 ap_hook_insert_error_filter(set_error_filter, NULL, NULL, APR_HOOK_LAST);
1484 ap_hook_post_read_request(shib_post_read, NULL, NULL, APR_HOOK_MIDDLE);
1486 ap_hook_child_init(shib_child_init, NULL, NULL, APR_HOOK_MIDDLE);
1487 ap_hook_check_user_id(shib_check_user, NULL, NULL, APR_HOOK_MIDDLE);
1488 ap_hook_auth_checker(shib_auth_checker, NULL, NULL, APR_HOOK_FIRST);
1489 ap_hook_handler(shib_handler, NULL, NULL, APR_HOOK_LAST);
1490 ap_hook_fixups(shib_fixups, NULL, NULL, APR_HOOK_MIDDLE);
1493 // SHIB Module commands
1496 static command_rec shib_cmds[] = {
1497 AP_INIT_TAKE1("ShibPrefix", (config_fn_t)ap_set_global_string_slot, &g_szPrefix,
1498 RSRC_CONF, "Shibboleth installation directory"),
1499 AP_INIT_TAKE1("ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1500 RSRC_CONF, "Path to shibboleth.xml config file"),
1501 AP_INIT_TAKE1("ShibCatalogs", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1502 RSRC_CONF, "Paths of XML schema catalogs"),
1504 AP_INIT_TAKE1("ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
1505 (void *) offsetof (shib_server_config, szScheme),
1506 RSRC_CONF, "URL scheme to force into generated URLs for a vhost"),
1508 AP_INIT_TAKE2("ShibRequestSetting", (config_fn_t)shib_table_set, NULL,
1509 OR_AUTHCFG, "Set arbitrary Shibboleth request property for content"),
1511 AP_INIT_FLAG("ShibDisable", (config_fn_t)ap_set_flag_slot,
1512 (void *) offsetof (shib_dir_config, bOff),
1513 OR_AUTHCFG, "Disable all Shib module activity here to save processing effort"),
1514 AP_INIT_TAKE1("ShibApplicationId", (config_fn_t)ap_set_string_slot,
1515 (void *) offsetof (shib_dir_config, szApplicationId),
1516 OR_AUTHCFG, "Set Shibboleth applicationId property for content"),
1517 AP_INIT_FLAG("ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1518 (void *) offsetof (shib_dir_config, bBasicHijack),
1519 OR_AUTHCFG, "Respond to AuthType Basic and convert to shibboleth"),
1520 AP_INIT_FLAG("ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1521 (void *) offsetof (shib_dir_config, bRequireSession),
1522 OR_AUTHCFG, "Initiates a new session if one does not exist"),
1523 AP_INIT_TAKE1("ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
1524 (void *) offsetof (shib_dir_config, szRequireWith),
1525 OR_AUTHCFG, "Initiates a new session if one does not exist using a specific SessionInitiator"),
1526 AP_INIT_FLAG("ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1527 (void *) offsetof (shib_dir_config, bExportAssertion),
1528 OR_AUTHCFG, "Export SAML attribute assertion(s) to Shib-Attributes header"),
1529 AP_INIT_TAKE1("ShibRedirectToSSL", (config_fn_t)ap_set_string_slot,
1530 (void *) offsetof (shib_dir_config, szRedirectToSSL),
1531 OR_AUTHCFG, "Redirect non-SSL requests to designated port"),
1532 AP_INIT_TAKE1("AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
1533 (void *) offsetof (shib_dir_config, szAuthGrpFile),
1534 OR_AUTHCFG, "Text file containing group names and member user IDs"),
1535 AP_INIT_FLAG("ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1536 (void *) offsetof (shib_dir_config, bRequireAll),
1537 OR_AUTHCFG, "All require directives must match"),
1538 AP_INIT_FLAG("AuthzShibAuthoritative", (config_fn_t)ap_set_flag_slot,
1539 (void *) offsetof (shib_dir_config, bAuthoritative),
1540 OR_AUTHCFG, "Allow failed mod_shib htaccess authorization to fall through to other modules"),
1541 AP_INIT_FLAG("ShibUseEnvironment", (config_fn_t)ap_set_flag_slot,
1542 (void *) offsetof (shib_dir_config, bUseEnvVars),
1543 OR_AUTHCFG, "Export attributes using environment variables (default)"),
1544 AP_INIT_FLAG("ShibUseHeaders", (config_fn_t)ap_set_flag_slot,
1545 (void *) offsetof (shib_dir_config, bUseHeaders),
1546 OR_AUTHCFG, "Export attributes using custom HTTP headers"),
1551 module AP_MODULE_DECLARE_DATA mod_shib = {
1552 STANDARD20_MODULE_STUFF,
1553 create_shib_dir_config, /* create dir config */
1554 merge_shib_dir_config, /* merge dir config --- default is to override */
1555 create_shib_server_config, /* create server config */
1556 merge_shib_server_config, /* merge server config */
1557 shib_cmds, /* command table */
1558 shib_register_hooks /* register hooks */
1562 #error "unsupported Apache version"