2 * Copyright 2001-2005 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.
18 * mod_apache.cpp -- the core Apache Module code
20 * Created by: Derek Atkins <derek@ihtfp.com>
26 #undef _XOPEN_SOURCE // causes gethostname conflict in unistd.h
30 #include <saml/saml.h>
31 #include <shib/shib.h>
32 #include <shib/shib-threads.h>
33 #include <shib-target/shib-target.h>
34 #include <xercesc/util/regx/RegularExpression.hpp>
38 // Apache specific header files
40 #include <http_config.h>
41 #include <http_protocol.h>
42 #include <http_main.h>
44 #include <http_core.h>
47 #ifndef SHIB_APACHE_13
48 #include <http_request.h>
49 #include <apr_strings.h>
50 #include <apr_pools.h>
57 #include <unistd.h> // for getpid()
62 using namespace shibboleth;
63 using namespace shibtarget;
65 extern "C" module MODULE_VAR_EXPORT mod_shib;
68 char* g_szSHIBConfig = NULL;
69 char* g_szSchemaDir = NULL;
70 ShibTargetConfig* g_Config = NULL;
71 static const char* g_UserDataKey = "_shib_check_user_";
74 /********************************************************************************/
75 // Basic Apache Configuration code.
78 // per-server module configuration structure
79 struct shib_server_config
84 // creates the per-server configuration
85 extern "C" void* create_shib_server_config(SH_AP_POOL* p, server_rec* s)
87 shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
92 // overrides server configuration in virtual servers
93 extern "C" void* merge_shib_server_config (SH_AP_POOL* p, void* base, void* sub)
95 shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
96 shib_server_config* parent=(shib_server_config*)base;
97 shib_server_config* child=(shib_server_config*)sub;
100 sc->szScheme=ap_pstrdup(p,child->szScheme);
101 else if (parent->szScheme)
102 sc->szScheme=ap_pstrdup(p,parent->szScheme);
109 // per-dir module configuration structure
110 struct shib_dir_config
113 char* szAuthGrpFile; // Auth GroupFile name
114 int bRequireAll; // all require directives must match, otherwise OR logic
116 // Content Configuration
117 char* szApplicationId; // Shib applicationId value
118 char* szRequireWith; // require a session using a specific initiator?
119 int bOff; // flat-out disable all Shib processing
120 int bBasicHijack; // activate for AuthType Basic?
121 int bRequireSession; // require a session?
122 int bExportAssertion; // export SAML assertion to the environment?
125 // creates per-directory config structure
126 extern "C" void* create_shib_dir_config (SH_AP_POOL* p, char* d)
128 shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
130 dc->bBasicHijack = -1;
131 dc->bRequireSession = -1;
132 dc->bExportAssertion = -1;
133 dc->bRequireAll = -1;
134 dc->szAuthGrpFile = NULL;
135 dc->szApplicationId = NULL;
136 dc->szRequireWith = NULL;
140 // overrides server configuration in directories
141 extern "C" void* merge_shib_dir_config (SH_AP_POOL* p, void* base, void* sub)
143 shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
144 shib_dir_config* parent=(shib_dir_config*)base;
145 shib_dir_config* child=(shib_dir_config*)sub;
147 if (child->szAuthGrpFile)
148 dc->szAuthGrpFile=ap_pstrdup(p,child->szAuthGrpFile);
149 else if (parent->szAuthGrpFile)
150 dc->szAuthGrpFile=ap_pstrdup(p,parent->szAuthGrpFile);
152 dc->szAuthGrpFile=NULL;
154 if (child->szApplicationId)
155 dc->szApplicationId=ap_pstrdup(p,child->szApplicationId);
156 else if (parent->szApplicationId)
157 dc->szApplicationId=ap_pstrdup(p,parent->szApplicationId);
159 dc->szApplicationId=NULL;
161 if (child->szRequireWith)
162 dc->szRequireWith=ap_pstrdup(p,child->szRequireWith);
163 else if (parent->szRequireWith)
164 dc->szRequireWith=ap_pstrdup(p,parent->szRequireWith);
166 dc->szRequireWith=NULL;
168 dc->bOff=((child->bOff==-1) ? parent->bOff : child->bOff);
169 dc->bBasicHijack=((child->bBasicHijack==-1) ? parent->bBasicHijack : child->bBasicHijack);
170 dc->bRequireSession=((child->bRequireSession==-1) ? parent->bRequireSession : child->bRequireSession);
171 dc->bExportAssertion=((child->bExportAssertion==-1) ? parent->bExportAssertion : child->bExportAssertion);
172 dc->bRequireAll=((child->bRequireAll==-1) ? parent->bRequireAll : child->bRequireAll);
176 // generic global slot handlers
177 extern "C" const char* ap_set_global_string_slot(cmd_parms* parms, void*, const char* arg)
179 *((char**)(parms->info))=ap_pstrdup(parms->pool,arg);
183 extern "C" const char* shib_set_server_string_slot(cmd_parms* parms, void*, const char* arg)
185 char* base=(char*)ap_get_module_config(parms->server->module_config,&mod_shib);
186 size_t offset=(size_t)parms->info;
187 *((char**)(base + offset))=ap_pstrdup(parms->pool,arg);
191 extern "C" const char* shib_ap_set_file_slot(cmd_parms* parms,
192 #ifdef SHIB_APACHE_13
193 char* arg1, char* arg2
195 void* arg1, const char* arg2
199 ap_set_file_slot(parms, arg1, arg2);
203 /********************************************************************************/
204 // Apache ShibTarget subclass(es) here.
206 class ShibTargetApache : public ShibTarget
209 ShibTargetApache(request_rec* req) {
210 m_sc = (shib_server_config*)ap_get_module_config(req->server->module_config, &mod_shib);
211 m_dc = (shib_dir_config*)ap_get_module_config(req->per_dir_config, &mod_shib);
214 m_sc->szScheme ? m_sc->szScheme : ap_http_method(req),
215 ap_get_server_name(req),
216 (int)ap_get_server_port(req),
218 ap_table_get(req->headers_in, "Content-type"),
219 req->connection->remote_ip,
225 ~ShibTargetApache() { }
227 virtual void log(ShibLogLevel level, const string &msg) {
228 ShibTarget::log(level,msg);
229 #ifdef SHIB_APACHE_13
230 ap_log_rerror(APLOG_MARK,
231 (level == LogLevelDebug ? APLOG_DEBUG :
232 (level == LogLevelInfo ? APLOG_INFO :
233 (level == LogLevelWarn ? APLOG_WARNING : APLOG_ERR)))|APLOG_NOERRNO, SH_AP_R(m_req), msg.c_str());
235 if (level == LogLevelError)
236 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(m_req), msg.c_str());
239 virtual string getCookies(void) const {
240 const char *c = ap_table_get(m_req->headers_in, "Cookie");
241 return string(c ? c : "");
243 virtual void setCookie(const string &name, const string &value) {
244 char* val = ap_psprintf(m_req->pool, "%s=%s", name.c_str(), value.c_str());
245 ap_table_addn(m_req->err_headers_out, "Set-Cookie", val);
247 virtual string getArgs(void) { return string(m_req->args ? m_req->args : ""); }
248 virtual string getPostData(void) {
249 // Read the posted data
250 if (ap_setup_client_block(m_req, REQUEST_CHUNKED_ERROR))
251 throw FatalProfileException("Apache function (setup_client_block) failed while reading profile submission.");
252 if (!ap_should_client_block(m_req))
253 throw FatalProfileException("Apache function (should_client_block) failed while reading profile submission.");
254 if (m_req->remaining > 1024*1024)
255 throw FatalProfileException("Blocked too-large a submission to profile endpoint.");
257 char buff[HUGE_STRING_LEN];
258 ap_hard_timeout("[mod_shib] getPostData", m_req);
259 memset(buff, 0, sizeof(buff));
260 while (ap_get_client_block(m_req, buff, sizeof(buff)-1) > 0) {
261 ap_reset_timeout(m_req);
263 memset(buff, 0, sizeof(buff));
265 ap_kill_timeout(m_req);
269 virtual void clearHeader(const string &name) {
270 ap_table_unset(m_req->headers_in, name.c_str());
272 virtual void setHeader(const string &name, const string &value) {
273 ap_table_set(m_req->headers_in, name.c_str(), value.c_str());
275 virtual string getHeader(const string &name) {
276 const char *hdr = ap_table_get(m_req->headers_in, name.c_str());
277 return string(hdr ? hdr : "");
279 virtual void setRemoteUser(const string &user) {
280 SH_AP_USER(m_req) = ap_pstrdup(m_req->pool, user.c_str());
282 virtual string getRemoteUser(void) {
283 return string(SH_AP_USER(m_req) ? SH_AP_USER(m_req) : "");
285 virtual void* sendPage(
288 const string& content_type="text/html",
289 const Iterator<header_t>& headers=EMPTY(header_t)
291 m_req->content_type = ap_psprintf(m_req->pool, content_type.c_str());
292 while (headers.hasNext()) {
293 const header_t& h=headers.next();
294 ap_table_set(m_req->headers_out, h.first.c_str(), h.second.c_str());
296 ap_send_http_header(m_req);
297 ap_rprintf(m_req, msg.c_str());
298 return (void*)((code==200) ? DONE : code);
300 virtual void* sendRedirect(const string& url) {
301 ap_table_set(m_req->headers_out, "Location", url.c_str());
302 return (void*)REDIRECT;
304 virtual void* returnDecline(void) { return (void*)DECLINED; }
305 virtual void* returnOK(void) { return (void*)OK; }
308 shib_dir_config* m_dc;
309 shib_server_config* m_sc;
312 /********************************************************************************/
315 extern "C" int shib_check_user(request_rec* r)
317 // Short-circuit entirely?
318 if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
321 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_check_user(%d): ENTER\n", (int)getpid());
323 ostringstream threadid;
324 threadid << "[" << getpid() << "] shib_check_user" << '\0';
325 saml::NDC ndc(threadid.str().c_str());
328 ShibTargetApache sta(r);
330 // Check user authentication and export information, then set the handler bypass
331 pair<bool,void*> res = sta.doCheckAuthN(true);
332 apr_pool_userdata_setn((const void*)42,g_UserDataKey,NULL,r->pool);
333 if (res.first) return (int)res.second;
335 // user auth was okay -- export the assertions now
336 res = sta.doExportAssertions();
337 if (res.first) return (int)res.second;
339 // export happened successfully.. this user is ok.
342 catch (SAMLException& e) {
343 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user threw an exception: %s", e.what());
348 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user threw an uncaught exception!");
354 extern "C" int shib_handler(request_rec* r)
356 // Short-circuit entirely?
357 if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
360 ostringstream threadid;
361 threadid << "[" << getpid() << "] shib_handler" << '\0';
362 saml::NDC ndc(threadid.str().c_str());
364 #ifndef SHIB_APACHE_13
365 // With 2.x, this handler always runs, though last.
366 // We check if shib_check_user ran, because it will detect a handler request
367 // and dispatch it directly.
369 apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
370 if (data==(const void*)42) {
371 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler skipped since check_user ran");
376 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler(%d): ENTER: %s", (int)getpid(), r->handler);
379 ShibTargetApache sta(r);
381 pair<bool,void*> res = sta.doHandler();
382 if (res.first) return (int)res.second;
384 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "doHandler() did not do anything.");
387 catch (SAMLException& e) {
388 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler threw an exception: %s", e.what());
393 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler threw an uncaught exception!");
400 * shib_auth_checker() -- a simple resource manager to
401 * process the .htaccess settings
403 extern "C" int shib_auth_checker(request_rec* r)
405 // Short-circuit entirely?
406 if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
409 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_auth_checker(%d): ENTER", (int)getpid());
411 ostringstream threadid;
412 threadid << "[" << getpid() << "] shib_auth_checker" << '\0';
413 saml::NDC ndc(threadid.str().c_str());
416 ShibTargetApache sta(r);
418 pair<bool,void*> res = sta.doCheckAuthZ();
419 if (res.first) return (int)res.second;
424 catch (SAMLException& e) {
425 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an exception: %s", e.what());
430 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an uncaught exception!");
436 // Access control plugin that enforces htaccess rules
437 class htAccessControl : virtual public IAccessControl
441 ~htAccessControl() {}
446 ISessionCacheEntry* entry
450 IPlugIn* htAccessFactory(const DOMElement* e)
452 return new htAccessControl();
455 class ApacheRequestMapper : public virtual IRequestMapper, public virtual IPropertySet
458 ApacheRequestMapper(const DOMElement* e);
459 ~ApacheRequestMapper() { delete m_mapper; delete m_htaccess; delete m_staKey; delete m_propsKey; }
460 void lock() { m_mapper->lock(); }
461 void unlock() { m_staKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
462 Settings getSettings(ShibTarget* st) const;
464 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
465 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
466 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
467 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
468 pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
469 const IPropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
470 const DOMElement* getElement() const;
473 IRequestMapper* m_mapper;
475 ThreadKey* m_propsKey;
476 IAccessControl* m_htaccess;
479 IPlugIn* ApacheRequestMapFactory(const DOMElement* e)
481 return new ApacheRequestMapper(e);
484 ApacheRequestMapper::ApacheRequestMapper(const DOMElement* e) : m_mapper(NULL), m_htaccess(NULL), m_staKey(NULL), m_propsKey(NULL)
486 IPlugIn* p=SAMLConfig::getConfig().getPlugMgr().newPlugin(shibtarget::XML::XMLRequestMapType,e);
487 m_mapper=dynamic_cast<IRequestMapper*>(p);
490 throw UnsupportedExtensionException("Embedded request mapper plugin was not of correct type.");
492 m_htaccess=new htAccessControl();
493 m_staKey=ThreadKey::create(NULL);
494 m_propsKey=ThreadKey::create(NULL);
497 IRequestMapper::Settings ApacheRequestMapper::getSettings(ShibTarget* st) const
499 Settings s=m_mapper->getSettings(st);
500 m_staKey->setData(dynamic_cast<ShibTargetApache*>(st));
501 m_propsKey->setData((void*)s.first);
502 return pair<const IPropertySet*,IAccessControl*>(this,s.second ? s.second : m_htaccess);
505 pair<bool,bool> ApacheRequestMapper::getBool(const char* name, const char* ns) const
507 ShibTargetApache* sta=reinterpret_cast<ShibTargetApache*>(m_staKey->getData());
508 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
510 // Override Apache-settable boolean properties.
511 if (name && !strcmp(name,"requireSession") && sta->m_dc->bRequireSession==1)
512 return make_pair(true,true);
513 else if (name && !strcmp(name,"exportAssertion") && sta->m_dc->bExportAssertion==1)
514 return make_pair(true,true);
516 return s ? s->getBool(name,ns) : make_pair(false,false);
519 pair<bool,const char*> ApacheRequestMapper::getString(const char* name, const char* ns) const
521 ShibTargetApache* sta=reinterpret_cast<ShibTargetApache*>(m_staKey->getData());
522 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
524 // Override Apache-settable string properties.
525 if (name && !strcmp(name,"authType")) {
526 const char *auth_type=ap_auth_type(sta->m_req);
528 // Check for Basic Hijack
529 if (!strcasecmp(auth_type, "basic") && sta->m_dc->bBasicHijack == 1)
530 auth_type = "shibboleth";
531 return make_pair(true,auth_type);
534 else if (name && !strcmp(name,"applicationId") && sta->m_dc->szApplicationId)
535 return pair<bool,const char*>(true,sta->m_dc->szApplicationId);
536 else if (name && !strcmp(name,"requireSessionWith") && sta->m_dc->szRequireWith)
537 return pair<bool,const char*>(true,sta->m_dc->szRequireWith);
539 return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
542 pair<bool,const XMLCh*> ApacheRequestMapper::getXMLString(const char* name, const char* ns) const
544 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
545 return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
548 pair<bool,unsigned int> ApacheRequestMapper::getUnsignedInt(const char* name, const char* ns) const
550 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
551 return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
554 pair<bool,int> ApacheRequestMapper::getInt(const char* name, const char* ns) const
556 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
557 return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
560 const IPropertySet* ApacheRequestMapper::getPropertySet(const char* name, const char* ns) const
562 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
563 return s ? s->getPropertySet(name,ns) : NULL;
566 const DOMElement* ApacheRequestMapper::getElement() const
568 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
569 return s ? s->getElement() : NULL;
572 static SH_AP_TABLE* groups_for_user(request_rec* r, const char* user, char* grpfile)
575 SH_AP_TABLE* grps=ap_make_table(r->pool,15);
576 char l[MAX_STRING_LEN];
577 const char *group_name, *ll, *w;
579 #ifdef SHIB_APACHE_13
580 if (!(f=ap_pcfg_openfile(r->pool,grpfile))) {
582 if (ap_pcfg_openfile(&f,r->pool,grpfile) != APR_SUCCESS) {
584 ap_log_rerror(APLOG_MARK,APLOG_DEBUG,SH_AP_R(r),"groups_for_user() could not open group file: %s\n",grpfile);
589 #ifdef SHIB_APACHE_13
590 sp=ap_make_sub_pool(r->pool);
592 if (apr_pool_create(&sp,r->pool) != APR_SUCCESS) {
593 ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,
594 "groups_for_user() could not create a subpool");
599 while (!(ap_cfg_getline(l,MAX_STRING_LEN,f))) {
600 if ((*l=='#') || (!*l))
605 group_name=ap_getword(sp,&ll,':');
608 w=ap_getword_conf(sp,&ll);
609 if (!strcmp(w,user)) {
610 ap_table_setn(grps,ap_pstrdup(r->pool,group_name),"in");
620 bool htAccessControl::authorized(
622 ISessionCacheEntry* entry
625 // Make sure the object is our type.
626 ShibTargetApache* sta=dynamic_cast<ShibTargetApache*>(st);
628 throw ConfigurationException("Request wrapper object was not of correct type.");
632 int m=sta->m_req->method_number;
633 bool method_restricted=false;
636 const array_header* reqs_arr=ap_requires(sta->m_req);
640 require_line* reqs=(require_line*)reqs_arr->elts;
642 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(sta->m_req),"REQUIRE nelts: %d", reqs_arr->nelts);
643 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(sta->m_req),"REQUIRE all: %d", sta->m_dc->bRequireAll);
645 vector<bool> auth_OK(reqs_arr->nelts,false);
647 #define SHIB_AP_CHECK_IS_OK { \
648 if (sta->m_dc->bRequireAll < 1) \
654 for (int x=0; x<reqs_arr->nelts; x++) {
656 if (!(reqs[x].method_mask & (1 << m)))
658 method_restricted=true;
659 string remote_user = st->getRemoteUser();
661 t = reqs[x].requirement;
662 w = ap_getword_white(sta->m_req->pool, &t);
664 if (!strcasecmp(w,"shibboleth")) {
665 // This is a dummy rule needed because Apache conflates authn and authz.
666 // Without some require rule, AuthType is ignored and no check_user hooks run.
669 else if (!strcmp(w,"valid-user")) {
671 st->log(ShibTarget::LogLevelDebug,"htAccessControl plugin accepting valid-user based on active session");
675 st->log(ShibTarget::LogLevelError,"htAccessControl plugin rejecting access for valid-user rule, no session is active");
677 else if (!strcmp(w,"user") && !remote_user.empty()) {
680 w=ap_getword_conf(sta->m_req->pool,&t);
688 // To do regex matching, we have to convert from UTF-8.
689 auto_ptr<XMLCh> trans(fromUTF8(w));
690 RegularExpression re(trans.get());
691 auto_ptr<XMLCh> trans2(fromUTF8(remote_user.c_str()));
692 if (re.matches(trans2.get())) {
693 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin accepting user (") + w + ")");
697 catch (XMLException& ex) {
698 auto_ptr_char tmp(ex.getMessage());
699 st->log(ShibTarget::LogLevelError,
700 string("htAccessControl plugin caught exception while parsing regular expression (") + w + "): " + tmp.get());
703 else if (remote_user==w) {
704 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin accepting user (") + w + ")");
709 else if (!strcmp(w,"group")) {
710 SH_AP_TABLE* grpstatus=NULL;
711 if (sta->m_dc->szAuthGrpFile && !remote_user.empty()) {
712 st->log(ShibTarget::LogLevelDebug,string("htAccessControl plugin using groups file: ") + sta->m_dc->szAuthGrpFile);
713 grpstatus=groups_for_user(sta->m_req,remote_user.c_str(),sta->m_dc->szAuthGrpFile);
719 w=ap_getword_conf(sta->m_req->pool,&t);
720 if (ap_table_get(grpstatus,w)) {
721 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin accepting group (") + w + ")");
727 Iterator<IAAP*> provs=st->getApplication()->getAAPProviders();
728 AAP wrapper(provs,w);
729 if (wrapper.fail()) {
730 st->log(ShibTarget::LogLevelWarn, string("htAccessControl plugin didn't recognize require rule: ") + w);
735 const char* vals=ap_table_get(sta->m_req->headers_in,wrapper->getHeader());
737 w=ap_getword_conf(sta->m_req->pool,&t);
744 auto_ptr<RegularExpression> re;
747 auto_ptr<XMLCh> trans(fromUTF8(w));
748 auto_ptr<RegularExpression> temp(new RegularExpression(trans.get()));
752 string vals_str(vals);
754 for (unsigned int i = 0; i < vals_str.length(); i++) {
755 if (vals_str.at(i) == ';') {
757 st->log(ShibTarget::LogLevelError, string("htAccessControl plugin found invalid header encoding (") +
758 vals + "): starts with a semicolon");
759 throw SAMLException("Invalid information supplied to authorization plugin.");
762 if (vals_str.at(i-1) == '\\') {
763 vals_str.erase(i-1, 1);
768 string val = vals_str.substr(j, i-j);
771 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
772 if (re->matches(trans.get())) {
773 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
774 ", got " + val + ": authorization granted");
778 else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
779 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
780 ", got " + val + ": authorization granted.");
784 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
785 ", got " + val + ": authoritzation not granted.");
790 string val = vals_str.substr(j, vals_str.length()-j);
792 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
793 if (re->matches(trans.get())) {
794 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
795 ", got " + val + ": authorization granted.");
799 else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
800 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
801 ", got " + val + ": authorization granted");
805 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
806 ", got " + val + ": authorization not granted");
809 catch (XMLException& ex) {
810 auto_ptr_char tmp(ex.getMessage());
811 st->log(ShibTarget::LogLevelError, string("htAccessControl plugin caught exception while parsing regular expression (")
812 + w + "): " + tmp.get());
818 // check if all require directives are true
819 bool auth_all_OK = true;
820 for (int i= 0; i<reqs_arr->nelts; i++) {
821 auth_all_OK &= auth_OK[i];
823 if (auth_all_OK || !method_restricted)
829 #ifndef SHIB_APACHE_13
832 * Empty cleanup hook, Apache 2.x doesn't check NULL very well...
834 extern "C" apr_status_t shib_exit(void* data)
837 g_Config->shutdown();
840 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,0,NULL,"shib_exit() done\n");
848 * Cleanup the (per-process) pool info.
850 #ifdef SHIB_APACHE_13
851 extern "C" void shib_child_exit(server_rec* s, SH_AP_POOL* p)
854 extern "C" apr_status_t shib_child_exit(void* data)
856 server_rec* s = NULL;
859 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit(%d) dealing with g_Config..", (int)getpid());
860 g_Config->shutdown();
862 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit() done\n");
864 #ifndef SHIB_APACHE_13
871 * Things to do when the child process is initialized.
872 * (or after the configs are read in apache-2)
874 #ifdef SHIB_APACHE_13
875 extern "C" void shib_child_init(server_rec* s, SH_AP_POOL* p)
877 extern "C" void shib_child_init(apr_pool_t* p, server_rec* s)
880 // Initialize runtime components.
882 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init(%d) starting", (int)getpid());
885 ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() already initialized!");
890 g_Config=&ShibTargetConfig::getConfig();
891 g_Config->setFeatures(
892 ShibTargetConfig::Listener |
893 ShibTargetConfig::Metadata |
894 ShibTargetConfig::AAP |
895 ShibTargetConfig::RequestMapper |
896 ShibTargetConfig::LocalExtensions |
897 ShibTargetConfig::Logging
899 if (!g_Config->init(g_szSchemaDir)) {
900 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize libraries");
903 SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::htAccessControlType,&htAccessFactory);
904 SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::NativeRequestMapType,&ApacheRequestMapFactory);
905 // We hijack the legacy type so that 1.2 config files will load this plugin
906 SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::LegacyRequestMapType,&ApacheRequestMapFactory);
908 if (!g_Config->load(g_szSHIBConfig)) {
909 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to load configuration");
914 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize system");
918 // Set the cleanup handler
919 apr_pool_cleanup_register(p, NULL, &shib_exit, &shib_child_exit);
921 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() done");
924 typedef const char* (*config_fn_t)(void);
926 #ifdef SHIB_APACHE_13
928 // SHIB Module commands
930 static command_rec shire_cmds[] = {
931 {"SHIREConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
932 RSRC_CONF, TAKE1, "Path to shibboleth.xml config file."},
933 {"ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
934 RSRC_CONF, TAKE1, "Path to shibboleth.xml config file."},
935 {"ShibSchemaDir", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
936 RSRC_CONF, TAKE1, "Path to Shibboleth XML schema directory."},
938 {"ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
939 (void *) XtOffsetOf (shib_server_config, szScheme),
940 RSRC_CONF, TAKE1, "URL scheme to force into generated URLs for a vhost."},
942 {"ShibDisable", (config_fn_t)ap_set_flag_slot,
943 (void *) XtOffsetOf (shib_dir_config, bOff),
944 OR_AUTHCFG, FLAG, "Disable all Shib module activity here to save processing effort"},
945 {"ShibApplicationId", (config_fn_t)ap_set_string_slot,
946 (void *) XtOffsetOf (shib_dir_config, szApplicationId),
947 OR_AUTHCFG, TAKE1, "Set Shibboleth applicationId property for content"},
948 {"ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
949 (void *) XtOffsetOf (shib_dir_config, bBasicHijack),
950 OR_AUTHCFG, FLAG, "Respond to AuthType Basic and convert to shib?"},
951 {"ShibRequireSession", (config_fn_t)ap_set_flag_slot,
952 (void *) XtOffsetOf (shib_dir_config, bRequireSession),
953 OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist."},
954 {"ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
955 (void *) XtOffsetOf (shib_dir_config, szRequireWith),
956 OR_AUTHCFG, TAKE1, "Initiates a new session if one does not exist using a specific SessionInitiator"},
957 {"ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
958 (void *) XtOffsetOf (shib_dir_config, bExportAssertion),
959 OR_AUTHCFG, FLAG, "Export SAML attribute assertion(s) to Shib-Attributes header?"},
960 {"AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
961 (void *) XtOffsetOf (shib_dir_config, szAuthGrpFile),
962 OR_AUTHCFG, TAKE1, "text file containing group names and member user IDs"},
963 {"ShibRequireAll", (config_fn_t)ap_set_flag_slot,
964 (void *) XtOffsetOf (shib_dir_config, bRequireAll),
965 OR_AUTHCFG, FLAG, "All require directives must match!"},
971 handler_rec shib_handlers[] = {
972 { "shib-handler", shib_handler },
976 module MODULE_VAR_EXPORT mod_shib = {
977 STANDARD_MODULE_STUFF,
978 NULL, /* initializer */
979 create_shib_dir_config, /* dir config creater */
980 merge_shib_dir_config, /* dir merger --- default is to override */
981 create_shib_server_config, /* server config */
982 merge_shib_server_config, /* merge server config */
983 shire_cmds, /* command table */
984 shib_handlers, /* handlers */
985 NULL, /* filename translation */
986 shib_check_user, /* check_user_id */
987 shib_auth_checker, /* check auth */
988 NULL, /* check access */
989 NULL, /* type_checker */
992 NULL, /* header parser */
993 shib_child_init, /* child_init */
994 shib_child_exit, /* child_exit */
995 NULL /* post read-request */
998 #elif defined(SHIB_APACHE_20)
1000 extern "C" void shib_register_hooks (apr_pool_t *p)
1002 ap_hook_child_init(shib_child_init, NULL, NULL, APR_HOOK_MIDDLE);
1003 ap_hook_check_user_id(shib_check_user, NULL, NULL, APR_HOOK_MIDDLE);
1004 ap_hook_auth_checker(shib_auth_checker, NULL, NULL, APR_HOOK_FIRST);
1005 ap_hook_handler(shib_handler, NULL, NULL, APR_HOOK_LAST);
1008 // SHIB Module commands
1011 static command_rec shib_cmds[] = {
1012 AP_INIT_TAKE1("ShibConfig",
1013 (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1014 RSRC_CONF, "Path to shibboleth.xml config file."),
1015 AP_INIT_TAKE1("ShibSchemaDir",
1016 (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1017 RSRC_CONF, "Path to Shibboleth XML schema directory."),
1019 AP_INIT_TAKE1("ShibURLScheme",
1020 (config_fn_t)shib_set_server_string_slot,
1021 (void *) offsetof (shib_server_config, szScheme),
1022 RSRC_CONF, "URL scheme to force into generated URLs for a vhost."),
1024 AP_INIT_FLAG("ShibDisable", (config_fn_t)ap_set_flag_slot,
1025 (void *) offsetof (shib_dir_config, bOff),
1026 OR_AUTHCFG, "Disable all Shib module activity here to save processing effort"),
1027 AP_INIT_TAKE1("ShibApplicationId", (config_fn_t)ap_set_string_slot,
1028 (void *) offsetof (shib_dir_config, szApplicationId),
1029 OR_AUTHCFG, "Set Shibboleth applicationId property for content"),
1030 AP_INIT_FLAG("ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1031 (void *) offsetof (shib_dir_config, bBasicHijack),
1032 OR_AUTHCFG, "Respond to AuthType Basic and convert to shib?"),
1033 AP_INIT_FLAG("ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1034 (void *) offsetof (shib_dir_config, bRequireSession),
1035 OR_AUTHCFG, "Initiates a new session if one does not exist."),
1036 AP_INIT_TAKE1("ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
1037 (void *) offsetof (shib_dir_config, szRequireWith),
1038 OR_AUTHCFG, "Initiates a new session if one does not exist using a specific SessionInitiator"),
1039 AP_INIT_FLAG("ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1040 (void *) offsetof (shib_dir_config, bExportAssertion),
1041 OR_AUTHCFG, "Export SAML attribute assertion(s) to Shib-Attributes header?"),
1042 AP_INIT_TAKE1("AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
1043 (void *) offsetof (shib_dir_config, szAuthGrpFile),
1044 OR_AUTHCFG, "Text file containing group names and member user IDs"),
1045 AP_INIT_FLAG("ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1046 (void *) offsetof (shib_dir_config, bRequireAll),
1047 OR_AUTHCFG, "All require directives must match!"),
1052 module AP_MODULE_DECLARE_DATA mod_shib = {
1053 STANDARD20_MODULE_STUFF,
1054 create_shib_dir_config, /* create dir config */
1055 merge_shib_dir_config, /* merge dir config --- default is to override */
1056 create_shib_server_config, /* create server config */
1057 merge_shib_server_config, /* merge server config */
1058 shib_cmds, /* command table */
1059 shib_register_hooks /* register hooks */
1063 #error "undefined APACHE version"