2 * mod_apache.cpp -- the core Apache Module code
4 * Created by: Derek Atkins <derek@ihtfp.com>
10 #undef _XOPEN_SOURCE // causes gethostname conflict in unistd.h
14 #include <saml/saml.h>
15 #include <shib/shib.h>
16 #include <shib/shib-threads.h>
17 #include <shib-target/shib-target.h>
18 #include <xercesc/util/regx/RegularExpression.hpp>
22 // Apache specific header files
24 #include <http_config.h>
25 #include <http_protocol.h>
26 #include <http_main.h>
28 #include <http_core.h>
31 #ifndef SHIB_APACHE_13
32 #include <http_request.h>
33 #include <apr_strings.h>
34 #include <apr_pools.h>
41 #include <unistd.h> // for getpid()
46 using namespace shibboleth;
47 using namespace shibtarget;
49 extern "C" module MODULE_VAR_EXPORT mod_shib;
52 char* g_szSHIBConfig = NULL;
53 char* g_szSchemaDir = NULL;
54 ShibTargetConfig* g_Config = NULL;
55 static const char* g_UserDataKey = "_shib_check_user_";
58 /********************************************************************************/
59 // Basic Apache Configuration code.
62 // per-server module configuration structure
63 struct shib_server_config
68 // creates the per-server configuration
69 extern "C" void* create_shib_server_config(SH_AP_POOL* p, server_rec* s)
71 shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
76 // overrides server configuration in virtual servers
77 extern "C" void* merge_shib_server_config (SH_AP_POOL* p, void* base, void* sub)
79 shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
80 shib_server_config* parent=(shib_server_config*)base;
81 shib_server_config* child=(shib_server_config*)sub;
84 sc->szScheme=ap_pstrdup(p,child->szScheme);
85 else if (parent->szScheme)
86 sc->szScheme=ap_pstrdup(p,parent->szScheme);
93 // per-dir module configuration structure
94 struct shib_dir_config
97 char* szAuthGrpFile; // Auth GroupFile name
98 int bRequireAll; // all require directives must match, otherwise OR logic
100 // Content Configuration
101 char* szApplicationId; // Shib applicationId value
102 char* szRequireWith; // require a session using a specific initiator?
103 int bOff; // flat-out disable all Shib processing
104 int bBasicHijack; // activate for AuthType Basic?
105 int bRequireSession; // require a session?
106 int bExportAssertion; // export SAML assertion to the environment?
109 // creates per-directory config structure
110 extern "C" void* create_shib_dir_config (SH_AP_POOL* p, char* d)
112 shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
114 dc->bBasicHijack = -1;
115 dc->bRequireSession = -1;
116 dc->bExportAssertion = -1;
117 dc->bRequireAll = -1;
118 dc->szAuthGrpFile = NULL;
119 dc->szApplicationId = NULL;
120 dc->szRequireWith = NULL;
124 // overrides server configuration in directories
125 extern "C" void* merge_shib_dir_config (SH_AP_POOL* p, void* base, void* sub)
127 shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
128 shib_dir_config* parent=(shib_dir_config*)base;
129 shib_dir_config* child=(shib_dir_config*)sub;
131 if (child->szAuthGrpFile)
132 dc->szAuthGrpFile=ap_pstrdup(p,child->szAuthGrpFile);
133 else if (parent->szAuthGrpFile)
134 dc->szAuthGrpFile=ap_pstrdup(p,parent->szAuthGrpFile);
136 dc->szAuthGrpFile=NULL;
138 if (child->szApplicationId)
139 dc->szApplicationId=ap_pstrdup(p,child->szApplicationId);
140 else if (parent->szApplicationId)
141 dc->szApplicationId=ap_pstrdup(p,parent->szApplicationId);
143 dc->szApplicationId=NULL;
145 if (child->szRequireWith)
146 dc->szRequireWith=ap_pstrdup(p,child->szRequireWith);
147 else if (parent->szRequireWith)
148 dc->szRequireWith=ap_pstrdup(p,parent->szRequireWith);
150 dc->szRequireWith=NULL;
152 dc->bOff=((child->bOff==-1) ? parent->bOff : child->bOff);
153 dc->bBasicHijack=((child->bBasicHijack==-1) ? parent->bBasicHijack : child->bBasicHijack);
154 dc->bRequireSession=((child->bRequireSession==-1) ? parent->bRequireSession : child->bRequireSession);
155 dc->bExportAssertion=((child->bExportAssertion==-1) ? parent->bExportAssertion : child->bExportAssertion);
156 dc->bRequireAll=((child->bRequireAll==-1) ? parent->bRequireAll : child->bRequireAll);
160 // generic global slot handlers
161 extern "C" const char* ap_set_global_string_slot(cmd_parms* parms, void*, const char* arg)
163 *((char**)(parms->info))=ap_pstrdup(parms->pool,arg);
167 extern "C" const char* shib_set_server_string_slot(cmd_parms* parms, void*, const char* arg)
169 char* base=(char*)ap_get_module_config(parms->server->module_config,&mod_shib);
170 int offset=(int)parms->info;
171 *((char**)(base + offset))=ap_pstrdup(parms->pool,arg);
175 extern "C" const char* shib_ap_set_file_slot(cmd_parms* parms,
176 #ifdef SHIB_APACHE_13
177 char* arg1, char* arg2
179 void* arg1, const char* arg2
183 ap_set_file_slot(parms, arg1, arg2);
187 /********************************************************************************/
188 // Apache ShibTarget subclass(es) here.
190 class ShibTargetApache : public ShibTarget
193 ShibTargetApache(request_rec* req) {
194 m_sc = (shib_server_config*)ap_get_module_config(req->server->module_config, &mod_shib);
195 m_dc = (shib_dir_config*)ap_get_module_config(req->per_dir_config, &mod_shib);
198 m_sc->szScheme ? m_sc->szScheme : ap_http_method(req),
199 ap_get_server_name(req),
200 (int)ap_get_server_port(req),
202 ap_table_get(req->headers_in, "Content-type"),
203 req->connection->remote_ip,
209 ~ShibTargetApache() { }
211 virtual void log(ShibLogLevel level, const string &msg) {
212 ShibTarget::log(level,msg);
213 #ifdef SHIB_APACHE_13
214 ap_log_rerror(APLOG_MARK,
215 (level == LogLevelDebug ? APLOG_DEBUG :
216 (level == LogLevelInfo ? APLOG_INFO :
217 (level == LogLevelWarn ? APLOG_WARNING : APLOG_ERR)))|APLOG_NOERRNO, SH_AP_R(m_req), msg.c_str());
219 if (level == LogLevelError)
220 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(m_req), msg.c_str());
223 virtual string getCookies(void) const {
224 const char *c = ap_table_get(m_req->headers_in, "Cookie");
225 return string(c ? c : "");
227 virtual void setCookie(const string &name, const string &value) {
228 char* val = ap_psprintf(m_req->pool, "%s=%s", name.c_str(), value.c_str());
229 ap_table_addn(m_req->err_headers_out, "Set-Cookie", val);
231 virtual string getArgs(void) { return string(m_req->args ? m_req->args : ""); }
232 virtual string getPostData(void) {
233 // Read the posted data
234 if (ap_setup_client_block(m_req, REQUEST_CHUNKED_ERROR))
235 throw FatalProfileException("Apache function (setup_client_block) failed while reading profile submission.");
236 if (!ap_should_client_block(m_req))
237 throw FatalProfileException("Apache function (should_client_block) failed while reading profile submission.");
238 if (m_req->remaining > 1024*1024)
239 throw FatalProfileException("Blocked too-large a submission to profile endpoint.");
241 char buff[HUGE_STRING_LEN];
242 ap_hard_timeout("[mod_shib] getPostData", m_req);
243 memset(buff, 0, sizeof(buff));
244 while (ap_get_client_block(m_req, buff, sizeof(buff)-1) > 0) {
245 ap_reset_timeout(m_req);
247 memset(buff, 0, sizeof(buff));
249 ap_kill_timeout(m_req);
253 virtual void clearHeader(const string &name) {
254 ap_table_unset(m_req->headers_in, name.c_str());
256 virtual void setHeader(const string &name, const string &value) {
257 ap_table_set(m_req->headers_in, name.c_str(), value.c_str());
259 virtual string getHeader(const string &name) {
260 const char *hdr = ap_table_get(m_req->headers_in, name.c_str());
261 return string(hdr ? hdr : "");
263 virtual void setRemoteUser(const string &user) {
264 SH_AP_USER(m_req) = ap_pstrdup(m_req->pool, user.c_str());
266 virtual string getRemoteUser(void) {
267 return string(SH_AP_USER(m_req) ? SH_AP_USER(m_req) : "");
269 virtual void* sendPage(
272 const string& content_type="text/html",
273 const Iterator<header_t>& headers=EMPTY(header_t)
275 m_req->content_type = ap_psprintf(m_req->pool, content_type.c_str());
276 while (headers.hasNext()) {
277 const header_t& h=headers.next();
278 ap_table_set(m_req->headers_out, h.first.c_str(), h.second.c_str());
280 ap_send_http_header(m_req);
281 ap_rprintf(m_req, msg.c_str());
282 return (void*)((code==200) ? DONE : code);
284 virtual void* sendRedirect(const string& url) {
285 ap_table_set(m_req->headers_out, "Location", url.c_str());
286 return (void*)REDIRECT;
288 virtual void* returnDecline(void) { return (void*)DECLINED; }
289 virtual void* returnOK(void) { return (void*)OK; }
292 shib_dir_config* m_dc;
293 shib_server_config* m_sc;
296 /********************************************************************************/
299 extern "C" int shib_check_user(request_rec* r)
301 // Short-circuit entirely?
302 if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
305 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_check_user(%d): ENTER\n", (int)getpid());
307 ostringstream threadid;
308 threadid << "[" << getpid() << "] shib_check_user" << '\0';
309 saml::NDC ndc(threadid.str().c_str());
314 ShibTargetApache sta(r);
316 // Check user authentication and export information, then set the handler bypass
317 pair<bool,void*> res = sta.doCheckAuthN(true);
318 apr_pool_userdata_setn((const void*)42,g_UserDataKey,NULL,r->pool);
319 if (res.first) return (int)res.second;
321 // user auth was okay -- export the assertions now
322 res = sta.doExportAssertions();
323 if (res.first) return (int)res.second;
325 // export happened successfully.. this user is ok.
330 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user threw an uncaught exception!");
336 extern "C" int shib_handler(request_rec* r)
338 // Short-circuit entirely?
339 if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
342 ostringstream threadid;
343 threadid << "[" << getpid() << "] shib_handler" << '\0';
344 saml::NDC ndc(threadid.str().c_str());
346 #ifndef SHIB_APACHE_13
347 // With 2.x, this handler always runs, though last.
348 // We check if shib_check_user ran, because it will detect a handler request
349 // and dispatch it directly.
351 apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
352 if (data==(const void*)42) {
353 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler skipped since check_user ran");
358 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler(%d): ENTER: %s", (int)getpid(), r->handler);
363 ShibTargetApache sta(r);
365 pair<bool,void*> res = sta.doHandler();
366 if (res.first) return (int)res.second;
368 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "doHandler() did not do anything.");
373 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler threw an uncaught exception!");
380 * shib_auth_checker() -- a simple resource manager to
381 * process the .htaccess settings
383 extern "C" int shib_auth_checker(request_rec* r)
385 // Short-circuit entirely?
386 if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
389 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_auth_checker(%d): ENTER", (int)getpid());
391 ostringstream threadid;
392 threadid << "[" << getpid() << "] shib_auth_checker" << '\0';
393 saml::NDC ndc(threadid.str().c_str());
398 ShibTargetApache sta(r);
400 pair<bool,void*> res = sta.doCheckAuthZ();
401 if (res.first) return (int)res.second;
408 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an uncaught exception!");
414 // Access control plugin that enforces htaccess rules
415 class htAccessControl : virtual public IAccessControl
419 ~htAccessControl() {}
424 ISessionCacheEntry* entry
428 IPlugIn* htAccessFactory(const DOMElement* e)
430 return new htAccessControl();
433 class ApacheRequestMapper : public virtual IRequestMapper, public virtual IPropertySet
436 ApacheRequestMapper(const DOMElement* e);
437 ~ApacheRequestMapper() { delete m_mapper; delete m_htaccess; delete m_staKey; delete m_propsKey; }
438 void lock() { m_mapper->lock(); }
439 void unlock() { m_staKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
440 Settings getSettings(ShibTarget* st) const;
442 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
443 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
444 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
445 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
446 pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
447 const IPropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
448 const DOMElement* getElement() const;
451 IRequestMapper* m_mapper;
453 ThreadKey* m_propsKey;
454 IAccessControl* m_htaccess;
457 IPlugIn* ApacheRequestMapFactory(const DOMElement* e)
459 return new ApacheRequestMapper(e);
462 ApacheRequestMapper::ApacheRequestMapper(const DOMElement* e) : m_mapper(NULL), m_htaccess(NULL), m_staKey(NULL), m_propsKey(NULL)
464 IPlugIn* p=SAMLConfig::getConfig().getPlugMgr().newPlugin(shibtarget::XML::XMLRequestMapType,e);
465 m_mapper=dynamic_cast<IRequestMapper*>(p);
468 throw UnsupportedExtensionException("Embedded request mapper plugin was not of correct type.");
470 m_htaccess=new htAccessControl();
471 m_staKey=ThreadKey::create(NULL);
472 m_propsKey=ThreadKey::create(NULL);
475 IRequestMapper::Settings ApacheRequestMapper::getSettings(ShibTarget* st) const
477 Settings s=m_mapper->getSettings(st);
478 m_staKey->setData(dynamic_cast<ShibTargetApache*>(st));
479 m_propsKey->setData((void*)s.first);
480 return pair<const IPropertySet*,IAccessControl*>(this,s.second ? s.second : m_htaccess);
483 pair<bool,bool> ApacheRequestMapper::getBool(const char* name, const char* ns) const
485 ShibTargetApache* sta=reinterpret_cast<ShibTargetApache*>(m_staKey->getData());
486 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
488 // Override Apache-settable boolean properties.
489 if (name && !strcmp(name,"requireSession") && sta->m_dc->bRequireSession==1)
490 return make_pair(true,true);
491 else if (name && !strcmp(name,"exportAssertion") && sta->m_dc->bExportAssertion==1)
492 return make_pair(true,true);
494 return s ? s->getBool(name,ns) : make_pair(false,false);
497 pair<bool,const char*> ApacheRequestMapper::getString(const char* name, const char* ns) const
499 ShibTargetApache* sta=reinterpret_cast<ShibTargetApache*>(m_staKey->getData());
500 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
502 // Override Apache-settable string properties.
503 if (name && !strcmp(name,"authType")) {
504 const char *auth_type=ap_auth_type(sta->m_req);
506 // Check for Basic Hijack
507 if (!strcasecmp(auth_type, "basic") && sta->m_dc->bBasicHijack == 1)
508 auth_type = "shibboleth";
509 return make_pair(true,auth_type);
512 else if (name && !strcmp(name,"applicationId") && sta->m_dc->szApplicationId)
513 return pair<bool,const char*>(true,sta->m_dc->szApplicationId);
514 else if (name && !strcmp(name,"requireSessionWith") && sta->m_dc->szRequireWith)
515 return pair<bool,const char*>(true,sta->m_dc->szRequireWith);
517 return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
520 pair<bool,const XMLCh*> ApacheRequestMapper::getXMLString(const char* name, const char* ns) const
522 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
523 return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
526 pair<bool,unsigned int> ApacheRequestMapper::getUnsignedInt(const char* name, const char* ns) const
528 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
529 return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
532 pair<bool,int> ApacheRequestMapper::getInt(const char* name, const char* ns) const
534 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
535 return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
538 const IPropertySet* ApacheRequestMapper::getPropertySet(const char* name, const char* ns) const
540 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
541 return s ? s->getPropertySet(name,ns) : NULL;
544 const DOMElement* ApacheRequestMapper::getElement() const
546 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
547 return s ? s->getElement() : NULL;
550 static SH_AP_TABLE* groups_for_user(request_rec* r, const char* user, char* grpfile)
553 SH_AP_TABLE* grps=ap_make_table(r->pool,15);
554 char l[MAX_STRING_LEN];
555 const char *group_name, *ll, *w;
557 #ifdef SHIB_APACHE_13
558 if (!(f=ap_pcfg_openfile(r->pool,grpfile))) {
560 if (ap_pcfg_openfile(&f,r->pool,grpfile) != APR_SUCCESS) {
562 ap_log_rerror(APLOG_MARK,APLOG_DEBUG,SH_AP_R(r),"groups_for_user() could not open group file: %s\n",grpfile);
567 #ifdef SHIB_APACHE_13
568 sp=ap_make_sub_pool(r->pool);
570 if (apr_pool_create(&sp,r->pool) != APR_SUCCESS) {
571 ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,
572 "groups_for_user() could not create a subpool");
577 while (!(ap_cfg_getline(l,MAX_STRING_LEN,f))) {
578 if ((*l=='#') || (!*l))
583 group_name=ap_getword(sp,&ll,':');
586 w=ap_getword_conf(sp,&ll);
587 if (!strcmp(w,user)) {
588 ap_table_setn(grps,ap_pstrdup(r->pool,group_name),"in");
598 bool htAccessControl::authorized(
600 ISessionCacheEntry* entry
603 // Make sure the object is our type.
604 ShibTargetApache* sta=dynamic_cast<ShibTargetApache*>(st);
606 throw ConfigurationException("Request wrapper object was not of correct type.");
610 int m=sta->m_req->method_number;
611 bool method_restricted=false;
614 const array_header* reqs_arr=ap_requires(sta->m_req);
618 require_line* reqs=(require_line*)reqs_arr->elts;
620 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(sta->m_req),"REQUIRE nelts: %d", reqs_arr->nelts);
621 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(sta->m_req),"REQUIRE all: %d", sta->m_dc->bRequireAll);
623 vector<bool> auth_OK(reqs_arr->nelts,false);
625 #define SHIB_AP_CHECK_IS_OK { \
626 if (sta->m_dc->bRequireAll < 1) \
632 for (int x=0; x<reqs_arr->nelts; x++) {
634 if (!(reqs[x].method_mask & (1 << m)))
636 method_restricted=true;
637 string remote_user = st->getRemoteUser();
639 t = reqs[x].requirement;
640 w = ap_getword_white(sta->m_req->pool, &t);
642 if (!strcasecmp(w,"shibboleth")) {
643 // This is a dummy rule needed because Apache conflates authn and authz.
644 // Without some require rule, AuthType is ignored and no check_user hooks run.
647 else if (!strcmp(w,"valid-user") && entry) {
648 st->log(ShibTarget::LogLevelDebug,"htAccessControl plugin accepting valid-user based on active session");
651 else if (!strcmp(w,"user") && !remote_user.empty()) {
654 w=ap_getword_conf(sta->m_req->pool,&t);
662 // To do regex matching, we have to convert from UTF-8.
663 auto_ptr<XMLCh> trans(fromUTF8(w));
664 RegularExpression re(trans.get());
665 auto_ptr<XMLCh> trans2(fromUTF8(remote_user.c_str()));
666 if (re.matches(trans2.get())) {
667 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin accepting user (") + w + ")");
671 catch (XMLException& ex) {
672 auto_ptr_char tmp(ex.getMessage());
673 st->log(ShibTarget::LogLevelError,
674 string("htAccessControl plugin caught exception while parsing regular expression (") + w + "): " + tmp.get());
677 else if (remote_user==w) {
678 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin accepting user (") + w + ")");
683 else if (!strcmp(w,"group")) {
684 SH_AP_TABLE* grpstatus=NULL;
685 if (sta->m_dc->szAuthGrpFile && !remote_user.empty()) {
686 st->log(ShibTarget::LogLevelDebug,string("htAccessControl plugin using groups file: ") + sta->m_dc->szAuthGrpFile);
687 grpstatus=groups_for_user(sta->m_req,remote_user.c_str(),sta->m_dc->szAuthGrpFile);
693 w=ap_getword_conf(sta->m_req->pool,&t);
694 if (ap_table_get(grpstatus,w)) {
695 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin accepting group (") + w + ")");
701 Iterator<IAAP*> provs=st->getApplication()->getAAPProviders();
702 AAP wrapper(provs,w);
703 if (wrapper.fail()) {
704 st->log(ShibTarget::LogLevelWarn, string("htAccessControl plugin didn't recognize require rule: ") + w);
709 const char* vals=ap_table_get(sta->m_req->headers_in,wrapper->getHeader());
711 w=ap_getword_conf(sta->m_req->pool,&t);
718 auto_ptr<RegularExpression> re;
721 auto_ptr<XMLCh> trans(fromUTF8(w));
722 auto_ptr<RegularExpression> temp(new RegularExpression(trans.get()));
726 string vals_str(vals);
728 for (int i = 0; i < vals_str.length(); i++) {
729 if (vals_str.at(i) == ';') {
731 st->log(ShibTarget::LogLevelError, string("htAccessControl plugin found invalid header encoding (") +
732 vals + "): starts with a semicolon");
733 throw SAMLException("Invalid information supplied to authorization plugin.");
736 if (vals_str.at(i-1) == '\\') {
737 vals_str.erase(i-1, 1);
742 string val = vals_str.substr(j, i-j);
745 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
746 if (re->matches(trans.get())) {
747 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
748 ", got " + val + ": authorization granted");
752 else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
753 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
754 ", got " + val + ": authorization granted.");
758 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
759 ", got " + val + ": authoritzation not granted.");
764 string val = vals_str.substr(j, vals_str.length()-j);
766 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
767 if (re->matches(trans.get())) {
768 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
769 ", got " + val + ": authorization granted.");
773 else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
774 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
775 ", got " + val + ": authorization granted");
779 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
780 ", got " + val + ": authorization not granted");
783 catch (XMLException& ex) {
784 auto_ptr_char tmp(ex.getMessage());
785 st->log(ShibTarget::LogLevelError, string("htAccessControl plugin caught exception while parsing regular expression (")
786 + w + "): " + tmp.get());
792 // check if all require directives are true
793 bool auth_all_OK = true;
794 for (int i= 0; i<reqs_arr->nelts; i++) {
795 auth_all_OK &= auth_OK[i];
797 if (auth_all_OK || !method_restricted)
803 #ifndef SHIB_APACHE_13
806 * Empty cleanup hook, Apache 2.x doesn't check NULL very well...
808 extern "C" apr_status_t shib_exit(void* data)
811 g_Config->shutdown();
814 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,0,NULL,"shib_exit() done\n");
822 * Cleanup the (per-process) pool info.
824 #ifdef SHIB_APACHE_13
825 extern "C" void shib_child_exit(server_rec* s, SH_AP_POOL* p)
828 extern "C" apr_status_t shib_child_exit(void* data)
830 server_rec* s = NULL;
833 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit(%d) dealing with g_Config..", (int)getpid());
834 g_Config->shutdown();
836 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit() done\n");
838 #ifndef SHIB_APACHE_13
845 * Things to do when the child process is initialized.
846 * (or after the configs are read in apache-2)
848 #ifdef SHIB_APACHE_13
849 extern "C" void shib_child_init(server_rec* s, SH_AP_POOL* p)
851 extern "C" void shib_child_init(apr_pool_t* p, server_rec* s)
854 // Initialize runtime components.
856 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init(%d) starting", (int)getpid());
859 ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() already initialized!");
864 g_Config=&ShibTargetConfig::getConfig();
865 g_Config->setFeatures(
866 ShibTargetConfig::Listener |
867 ShibTargetConfig::Metadata |
868 ShibTargetConfig::AAP |
869 ShibTargetConfig::RequestMapper |
870 ShibTargetConfig::LocalExtensions |
871 ShibTargetConfig::Logging
873 if (!g_Config->init(g_szSchemaDir)) {
874 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize libraries");
877 SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::htAccessControlType,&htAccessFactory);
878 SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::NativeRequestMapType,&ApacheRequestMapFactory);
879 // We hijack the legacy type so that 1.2 config files will load this plugin
880 SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::LegacyRequestMapType,&ApacheRequestMapFactory);
882 if (!g_Config->load(g_szSHIBConfig)) {
883 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to load configuration");
888 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize system");
892 // Set the cleanup handler
893 apr_pool_cleanup_register(p, NULL, &shib_exit, &shib_child_exit);
895 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() done");
898 typedef const char* (*config_fn_t)(void);
900 #ifdef SHIB_APACHE_13
902 // SHIB Module commands
904 static command_rec shire_cmds[] = {
905 {"SHIREConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
906 RSRC_CONF, TAKE1, "Path to shibboleth.xml config file."},
907 {"ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
908 RSRC_CONF, TAKE1, "Path to shibboleth.xml config file."},
909 {"ShibSchemaDir", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
910 RSRC_CONF, TAKE1, "Path to Shibboleth XML schema directory."},
912 {"ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
913 (void *) XtOffsetOf (shib_server_config, szScheme),
914 RSRC_CONF, TAKE1, "URL scheme to force into generated URLs for a vhost."},
916 {"ShibDisable", (config_fn_t)ap_set_flag_slot,
917 (void *) XtOffsetOf (shib_dir_config, bOff),
918 OR_AUTHCFG, FLAG, "Disable all Shib module activity here to save processing effort"},
919 {"ShibApplicationId", (config_fn_t)ap_set_string_slot,
920 (void *) XtOffsetOf (shib_dir_config, szApplicationId),
921 OR_AUTHCFG, FLAG, "Set Shibboleth applicationId property for content"},
922 {"ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
923 (void *) XtOffsetOf (shib_dir_config, bBasicHijack),
924 OR_AUTHCFG, FLAG, "Respond to AuthType Basic and convert to shib?"},
925 {"ShibRequireSession", (config_fn_t)ap_set_flag_slot,
926 (void *) XtOffsetOf (shib_dir_config, bRequireSession),
927 OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist."},
928 {"ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
929 (void *) XtOffsetOf (shib_dir_config, szRequireWith),
930 OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist using a specific SessionInitiator"},
931 {"ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
932 (void *) XtOffsetOf (shib_dir_config, bExportAssertion),
933 OR_AUTHCFG, FLAG, "Export SAML attribute assertion(s) to Shib-Attributes header?"},
934 {"AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
935 (void *) XtOffsetOf (shib_dir_config, szAuthGrpFile),
936 OR_AUTHCFG, TAKE1, "text file containing group names and member user IDs"},
937 {"ShibRequireAll", (config_fn_t)ap_set_flag_slot,
938 (void *) XtOffsetOf (shib_dir_config, bRequireAll),
939 OR_AUTHCFG, FLAG, "All require directives must match!"},
945 handler_rec shib_handlers[] = {
946 { "shib-handler", shib_handler },
950 module MODULE_VAR_EXPORT mod_shib = {
951 STANDARD_MODULE_STUFF,
952 NULL, /* initializer */
953 create_shib_dir_config, /* dir config creater */
954 merge_shib_dir_config, /* dir merger --- default is to override */
955 create_shib_server_config, /* server config */
956 merge_shib_server_config, /* merge server config */
957 shire_cmds, /* command table */
958 shib_handlers, /* handlers */
959 NULL, /* filename translation */
960 shib_check_user, /* check_user_id */
961 shib_auth_checker, /* check auth */
962 NULL, /* check access */
963 NULL, /* type_checker */
966 NULL, /* header parser */
967 shib_child_init, /* child_init */
968 shib_child_exit, /* child_exit */
969 NULL /* post read-request */
972 #elif defined(SHIB_APACHE_20)
974 extern "C" void shib_register_hooks (apr_pool_t *p)
976 ap_hook_child_init(shib_child_init, NULL, NULL, APR_HOOK_MIDDLE);
977 ap_hook_check_user_id(shib_check_user, NULL, NULL, APR_HOOK_MIDDLE);
978 ap_hook_auth_checker(shib_auth_checker, NULL, NULL, APR_HOOK_FIRST);
979 ap_hook_handler(shib_handler, NULL, NULL, APR_HOOK_LAST);
982 // SHIB Module commands
985 static command_rec shib_cmds[] = {
986 AP_INIT_TAKE1("ShibConfig",
987 (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
988 RSRC_CONF, "Path to shibboleth.xml config file."),
989 AP_INIT_TAKE1("ShibSchemaDir",
990 (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
991 RSRC_CONF, "Path to Shibboleth XML schema directory."),
993 AP_INIT_TAKE1("ShibURLScheme",
994 (config_fn_t)shib_set_server_string_slot,
995 (void *) offsetof (shib_server_config, szScheme),
996 RSRC_CONF, "URL scheme to force into generated URLs for a vhost."),
998 AP_INIT_FLAG("ShibDisable", (config_fn_t)ap_set_flag_slot,
999 (void *) offsetof (shib_dir_config, bOff),
1000 OR_AUTHCFG, "Disable all Shib module activity here to save processing effort"),
1001 AP_INIT_TAKE1("ShibApplicationId", (config_fn_t)ap_set_string_slot,
1002 (void *) offsetof (shib_dir_config, szApplicationId),
1003 OR_AUTHCFG, "Set Shibboleth applicationId property for content"),
1004 AP_INIT_FLAG("ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1005 (void *) offsetof (shib_dir_config, bBasicHijack),
1006 OR_AUTHCFG, "Respond to AuthType Basic and convert to shib?"),
1007 AP_INIT_FLAG("ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1008 (void *) offsetof (shib_dir_config, bRequireSession),
1009 OR_AUTHCFG, "Initiates a new session if one does not exist."),
1010 AP_INIT_TAKE1("ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
1011 (void *) offsetof (shib_dir_config, szRequireWith),
1012 OR_AUTHCFG, "Initiates a new session if one does not exist using a specific SessionInitiator"),
1013 AP_INIT_FLAG("ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1014 (void *) offsetof (shib_dir_config, bExportAssertion),
1015 OR_AUTHCFG, "Export SAML attribute assertion(s) to Shib-Attributes header?"),
1016 AP_INIT_TAKE1("AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
1017 (void *) offsetof (shib_dir_config, szAuthGrpFile),
1018 OR_AUTHCFG, "Text file containing group names and member user IDs"),
1019 AP_INIT_FLAG("ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1020 (void *) offsetof (shib_dir_config, bRequireAll),
1021 OR_AUTHCFG, "All require directives must match!"),
1026 module AP_MODULE_DECLARE_DATA mod_shib = {
1027 STANDARD20_MODULE_STUFF,
1028 create_shib_dir_config, /* create dir config */
1029 merge_shib_dir_config, /* merge dir config --- default is to override */
1030 create_shib_server_config, /* create server config */
1031 merge_shib_server_config, /* merge server config */
1032 shib_cmds, /* command table */
1033 shib_register_hooks /* register hooks */
1037 #error "undefined APACHE version"