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, the 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 const char* providerId,
425 const saml::SAMLAuthenticationStatement* authn,
426 const saml::SAMLResponse* attrs
430 IPlugIn* htAccessFactory(const DOMElement* e)
432 return new htAccessControl();
435 class ApacheRequestMapper : public virtual IRequestMapper, public virtual IPropertySet
438 ApacheRequestMapper(const DOMElement* e);
439 ~ApacheRequestMapper() { delete m_mapper; delete m_htaccess; delete m_staKey; delete m_propsKey; }
440 void lock() { m_mapper->lock(); }
441 void unlock() { m_staKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
442 Settings getSettings(ShibTarget* st) const;
444 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
445 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
446 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
447 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
448 pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
449 const IPropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
450 const DOMElement* getElement() const;
453 IRequestMapper* m_mapper;
455 ThreadKey* m_propsKey;
456 IAccessControl* m_htaccess;
459 IPlugIn* ApacheRequestMapFactory(const DOMElement* e)
461 return new ApacheRequestMapper(e);
464 ApacheRequestMapper::ApacheRequestMapper(const DOMElement* e) : m_mapper(NULL), m_htaccess(NULL), m_staKey(NULL), m_propsKey(NULL)
466 IPlugIn* p=SAMLConfig::getConfig().getPlugMgr().newPlugin(shibtarget::XML::XMLRequestMapType,e);
467 m_mapper=dynamic_cast<IRequestMapper*>(p);
470 throw UnsupportedExtensionException("Embedded request mapper plugin was not of correct type.");
472 m_htaccess=new htAccessControl();
473 m_staKey=ThreadKey::create(NULL);
474 m_propsKey=ThreadKey::create(NULL);
477 IRequestMapper::Settings ApacheRequestMapper::getSettings(ShibTarget* st) const
479 Settings s=m_mapper->getSettings(st);
480 m_staKey->setData(dynamic_cast<ShibTargetApache*>(st));
481 m_propsKey->setData((void*)s.first);
482 return pair<const IPropertySet*,IAccessControl*>(this,s.second ? s.second : m_htaccess);
485 pair<bool,bool> ApacheRequestMapper::getBool(const char* name, const char* ns) const
487 ShibTargetApache* sta=reinterpret_cast<ShibTargetApache*>(m_staKey->getData());
488 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
490 // Override Apache-settable boolean properties.
491 if (name && !strcmp(name,"requireSession") && sta->m_dc->bRequireSession==1)
492 return make_pair(true,true);
493 else if (name && !strcmp(name,"exportAssertion") && sta->m_dc->bExportAssertion==1)
494 return make_pair(true,true);
496 return s ? s->getBool(name,ns) : make_pair(false,false);
499 pair<bool,const char*> ApacheRequestMapper::getString(const char* name, const char* ns) const
501 ShibTargetApache* sta=reinterpret_cast<ShibTargetApache*>(m_staKey->getData());
502 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
504 // Override Apache-settable string properties.
505 if (name && !strcmp(name,"authType")) {
506 const char *auth_type=ap_auth_type(sta->m_req);
508 // Check for Basic Hijack
509 if (!strcasecmp(auth_type, "basic") && sta->m_dc->bBasicHijack == 1)
510 auth_type = "shibboleth";
511 return make_pair(true,auth_type);
514 else if (name && !strcmp(name,"applicationId") && sta->m_dc->szApplicationId)
515 return make_pair(true,sta->m_dc->szApplicationId);
516 else if (name && !strcmp(name,"requireSessionWith") && sta->m_dc->szRequireWith)
517 return make_pair(true,sta->m_dc->szRequireWith);
519 return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
522 pair<bool,const XMLCh*> ApacheRequestMapper::getXMLString(const char* name, const char* ns) const
524 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
525 return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
528 pair<bool,unsigned int> ApacheRequestMapper::getUnsignedInt(const char* name, const char* ns) const
530 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
531 return s ? s->getUnsignedInt(name,ns) : make_pair(false,0);
534 pair<bool,int> ApacheRequestMapper::getInt(const char* name, const char* ns) const
536 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
537 return s ? s->getInt(name,ns) : make_pair(false,0);
540 const IPropertySet* ApacheRequestMapper::getPropertySet(const char* name, const char* ns) const
542 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
543 return s ? s->getPropertySet(name,ns) : NULL;
546 const DOMElement* ApacheRequestMapper::getElement() const
548 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
549 return s ? s->getElement() : NULL;
552 static SH_AP_TABLE* groups_for_user(request_rec* r, const char* user, char* grpfile)
555 SH_AP_TABLE* grps=ap_make_table(r->pool,15);
556 char l[MAX_STRING_LEN];
557 const char *group_name, *ll, *w;
559 #ifdef SHIB_APACHE_13
560 if (!(f=ap_pcfg_openfile(r->pool,grpfile))) {
562 if (ap_pcfg_openfile(&f,r->pool,grpfile) != APR_SUCCESS) {
564 ap_log_rerror(APLOG_MARK,APLOG_DEBUG,SH_AP_R(r),"groups_for_user() could not open group file: %s\n",grpfile);
569 #ifdef SHIB_APACHE_13
570 sp=ap_make_sub_pool(r->pool);
572 if (apr_pool_create(&sp,r->pool) != APR_SUCCESS) {
573 ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,
574 "groups_for_user() could not create a subpool");
579 while (!(ap_cfg_getline(l,MAX_STRING_LEN,f))) {
580 if ((*l=='#') || (!*l))
585 group_name=ap_getword(sp,&ll,':');
588 w=ap_getword_conf(sp,&ll);
589 if (!strcmp(w,user)) {
590 ap_table_setn(grps,ap_pstrdup(r->pool,group_name),"in");
600 bool htAccessControl::authorized(
602 const char* providerId,
603 const saml::SAMLAuthenticationStatement* authn,
604 const saml::SAMLResponse* attrs
607 // Make sure the object is our type.
608 ShibTargetApache* sta=dynamic_cast<ShibTargetApache*>(st);
610 throw ConfigurationException("Request wrapper object was not of correct type.");
614 int m=sta->m_req->method_number;
615 bool method_restricted=false;
618 const array_header* reqs_arr=ap_requires(sta->m_req);
622 require_line* reqs=(require_line*)reqs_arr->elts;
624 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(sta->m_req),"REQUIRE nelts: %d", reqs_arr->nelts);
625 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(sta->m_req),"REQUIRE all: %d", sta->m_dc->bRequireAll);
627 vector<bool> auth_OK(reqs_arr->nelts,false);
629 #define SHIB_AP_CHECK_IS_OK { \
630 if (sta->m_dc->bRequireAll < 1) \
636 for (int x=0; x<reqs_arr->nelts; x++) {
638 if (!(reqs[x].method_mask & (1 << m)))
640 method_restricted=true;
641 string remote_user = st->getRemoteUser();
643 t = reqs[x].requirement;
644 w = ap_getword_white(sta->m_req->pool, &t);
646 if (!strcasecmp(w,"Shibboleth")) {
647 // This is a dummy rule needed because Apache conflates authn and authz.
648 // Without some require rule, AuthType is ignored and no check_user hooks run.
651 else if (!strcmp(w,"valid-user")) {
652 st->log(ShibTarget::LogLevelDebug,"htAccessControl plugin accepting valid-user");
655 else if (!strcmp(w,"user") && !remote_user.empty()) {
658 w=ap_getword_conf(sta->m_req->pool,&t);
666 // To do regex matching, we have to convert from UTF-8.
667 auto_ptr<XMLCh> trans(fromUTF8(w));
668 RegularExpression re(trans.get());
669 auto_ptr<XMLCh> trans2(fromUTF8(remote_user.c_str()));
670 if (re.matches(trans2.get())) {
671 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin accepting user (") + w + ")");
675 catch (XMLException& ex) {
676 auto_ptr_char tmp(ex.getMessage());
677 st->log(ShibTarget::LogLevelError,
678 string("htAccessControl plugin caught exception while parsing regular expression (") + w + "): " + tmp.get());
681 else if (remote_user==w) {
682 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin accepting user (") + w + ")");
687 else if (!strcmp(w,"group")) {
688 SH_AP_TABLE* grpstatus=NULL;
689 if (sta->m_dc->szAuthGrpFile && !remote_user.empty()) {
690 st->log(ShibTarget::LogLevelDebug,string("htAccessControl plugin using groups file: ") + sta->m_dc->szAuthGrpFile);
691 grpstatus=groups_for_user(sta->m_req,remote_user.c_str(),sta->m_dc->szAuthGrpFile);
697 w=ap_getword_conf(sta->m_req->pool,&t);
698 if (ap_table_get(grpstatus,w)) {
699 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin accepting group (") + w + ")");
705 Iterator<IAAP*> provs=st->getApplication()->getAAPProviders();
706 AAP wrapper(provs,w);
707 if (wrapper.fail()) {
708 st->log(ShibTarget::LogLevelWarn, string("htAccessControl plugin didn't recognize require rule: ") + w);
713 const char* vals=ap_table_get(sta->m_req->headers_in,wrapper->getHeader());
715 w=ap_getword_conf(sta->m_req->pool,&t);
722 auto_ptr<RegularExpression> re;
725 auto_ptr<XMLCh> trans(fromUTF8(w));
726 auto_ptr<RegularExpression> temp(new RegularExpression(trans.get()));
730 string vals_str(vals);
732 for (int i = 0; i < vals_str.length(); i++) {
733 if (vals_str.at(i) == ';') {
735 st->log(ShibTarget::LogLevelError, string("htAccessControl plugin found invalid header encoding (") +
736 vals + "): starts with a semicolon");
737 throw SAMLException("Invalid information supplied to authorization plugin.");
740 if (vals_str.at(i-1) == '\\') {
741 vals_str.erase(i-1, 1);
746 string val = vals_str.substr(j, i-j);
749 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
750 if (re->matches(trans.get())) {
751 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
752 ", got " + val + ": authorization granted");
756 else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
757 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
758 ", got " + val + ": authorization granted.");
762 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
763 ", got " + val + ": authoritzation not granted.");
768 string val = vals_str.substr(j, vals_str.length()-j);
770 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
771 if (re->matches(trans.get())) {
772 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
773 ", got " + val + ": authorization granted.");
777 else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
778 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
779 ", got " + val + ": authorization granted");
783 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
784 ", got " + val + ": authorization not granted");
787 catch (XMLException& ex) {
788 auto_ptr_char tmp(ex.getMessage());
789 st->log(ShibTarget::LogLevelError, string("htAccessControl plugin caught exception while parsing regular expression (")
790 + w + "): " + tmp.get());
796 // check if all require directives are true
797 bool auth_all_OK = true;
798 for (int i= 0; i<reqs_arr->nelts; i++) {
799 auth_all_OK &= auth_OK[i];
801 if (auth_all_OK || !method_restricted)
807 #ifndef SHIB_APACHE_13
810 * Empty cleanup hook, Apache 2.x doesn't check NULL very well...
812 extern "C" apr_status_t shib_exit(void* data)
815 g_Config->shutdown();
818 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,0,NULL,"shib_exit() done\n");
826 * Cleanup the (per-process) pool info.
828 #ifdef SHIB_APACHE_13
829 extern "C" void shib_child_exit(server_rec* s, SH_AP_POOL* p)
832 extern "C" apr_status_t shib_child_exit(void* data)
834 server_rec* s = NULL;
837 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit(%d) dealing with g_Config..", (int)getpid());
838 g_Config->shutdown();
840 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit() done\n");
842 #ifndef SHIB_APACHE_13
849 * Things to do when the child process is initialized.
850 * (or after the configs are read in apache-2)
852 #ifdef SHIB_APACHE_13
853 extern "C" void shib_child_init(server_rec* s, SH_AP_POOL* p)
855 extern "C" void shib_child_init(apr_pool_t* p, server_rec* s)
858 // Initialize runtime components.
860 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init(%d) starting", (int)getpid());
863 ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() already initialized!");
868 g_Config=&ShibTargetConfig::getConfig();
869 g_Config->setFeatures(
870 ShibTargetConfig::Listener |
871 ShibTargetConfig::Metadata |
872 ShibTargetConfig::AAP |
873 ShibTargetConfig::RequestMapper |
874 ShibTargetConfig::LocalExtensions |
875 ShibTargetConfig::Logging
877 if (!g_Config->init(g_szSchemaDir)) {
878 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize libraries");
881 SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::htAccessControlType,&htAccessFactory);
882 SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::ApacheRequestMapType,&ApacheRequestMapFactory);
884 // We hijack the legacy type so that 1.2 config files will load this plugin instead of the basic plugin.
885 SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::LegacyRequestMapType,&ApacheRequestMapFactory);
887 if (!g_Config->load(g_szSHIBConfig)) {
888 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to load configuration");
893 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize system");
897 // Set the cleanup handler
898 apr_pool_cleanup_register(p, NULL, &shib_exit, &shib_child_exit);
900 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() done");
903 typedef const char* (*config_fn_t)(void);
905 #ifdef SHIB_APACHE_13
907 // SHIB Module commands
909 static command_rec shire_cmds[] = {
910 {"SHIREConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
911 RSRC_CONF, TAKE1, "Path to shibboleth.xml config file."},
912 {"ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
913 RSRC_CONF, TAKE1, "Path to shibboleth.xml config file."},
914 {"ShibSchemaDir", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
915 RSRC_CONF, TAKE1, "Path to Shibboleth XML schema directory."},
917 {"ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
918 (void *) XtOffsetOf (shib_server_config, szScheme),
919 RSRC_CONF, TAKE1, "URL scheme to force into generated URLs for a vhost."},
921 {"ShibDisable", (config_fn_t)ap_set_flag_slot,
922 (void *) XtOffsetOf (shib_dir_config, bOff),
923 OR_AUTHCFG, FLAG, "Disable all Shib module activity here to save processing effort"},
924 {"ShibApplicationId", (config_fn_t)ap_set_string_slot,
925 (void *) XtOffsetOf (shib_dir_config, szApplicationId),
926 OR_AUTHCFG, FLAG, "Set Shibboleth applicationId property for content"},
927 {"ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
928 (void *) XtOffsetOf (shib_dir_config, bBasicHijack),
929 OR_AUTHCFG, FLAG, "Respond to AuthType Basic and convert to shib?"},
930 {"ShibRequireSession", (config_fn_t)ap_set_flag_slot,
931 (void *) XtOffsetOf (shib_dir_config, bRequireSession),
932 OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist."},
933 {"ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
934 (void *) XtOffsetOf (shib_dir_config, szRequireWith),
935 OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist using a specific SessionInitiator"},
936 {"ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
937 (void *) XtOffsetOf (shib_dir_config, bExportAssertion),
938 OR_AUTHCFG, FLAG, "Export SAML attribute assertion(s) to Shib-Attributes header?"},
939 {"AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
940 (void *) XtOffsetOf (shib_dir_config, szAuthGrpFile),
941 OR_AUTHCFG, TAKE1, "text file containing group names and member user IDs"},
942 {"ShibRequireAll", (config_fn_t)ap_set_flag_slot,
943 (void *) XtOffsetOf (shib_dir_config, bRequireAll),
944 OR_AUTHCFG, FLAG, "All require directives must match!"},
950 handler_rec shib_handlers[] = {
951 { "shib-handler", shib_handler },
955 module MODULE_VAR_EXPORT mod_shib = {
956 STANDARD_MODULE_STUFF,
957 NULL, /* initializer */
958 create_shib_dir_config, /* dir config creater */
959 merge_shib_dir_config, /* dir merger --- default is to override */
960 create_shib_server_config, /* server config */
961 merge_shib_server_config, /* merge server config */
962 shire_cmds, /* command table */
963 shib_handlers, /* handlers */
964 NULL, /* filename translation */
965 shib_check_user, /* check_user_id */
966 shib_auth_checker, /* check auth */
967 NULL, /* check access */
968 NULL, /* type_checker */
971 NULL, /* header parser */
972 shib_child_init, /* child_init */
973 shib_child_exit, /* child_exit */
974 NULL /* post read-request */
977 #elif defined(SHIB_APACHE_20)
979 extern "C" void shib_register_hooks (apr_pool_t *p)
981 ap_hook_child_init(shib_child_init, NULL, NULL, APR_HOOK_MIDDLE);
982 ap_hook_check_user_id(shib_check_user, NULL, NULL, APR_HOOK_MIDDLE);
983 ap_hook_auth_checker(shib_auth_checker, NULL, NULL, APR_HOOK_FIRST);
984 ap_hook_handler(shib_handler, NULL, NULL, APR_HOOK_LAST);
987 // SHIB Module commands
990 static command_rec shib_cmds[] = {
991 AP_INIT_TAKE1("ShibConfig",
992 (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
993 RSRC_CONF, "Path to shibboleth.xml config file."),
994 AP_INIT_TAKE1("ShibSchemaDir",
995 (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
996 RSRC_CONF, "Path to Shibboleth XML schema directory."),
998 AP_INIT_TAKE1("ShibURLScheme",
999 (config_fn_t)shib_set_server_string_slot,
1000 (void *) offsetof (shib_server_config, szScheme),
1001 RSRC_CONF, "URL scheme to force into generated URLs for a vhost."),
1003 AP_INIT_FLAG("ShibDisable", (config_fn_t)ap_set_flag_slot,
1004 (void *) offsetof (shib_dir_config, bOff),
1005 OR_AUTHCFG, "Disable all Shib module activity here to save processing effort"),
1006 AP_INIT_FLAG("ShibApplicationId", (config_fn_t)ap_set_string_slot,
1007 (void *) offsetof (shib_dir_config, szApplicationId),
1008 OR_AUTHCFG, "Set Shibboleth applicationId property for content"),
1009 AP_INIT_FLAG("ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1010 (void *) offsetof (shib_dir_config, bBasicHijack),
1011 OR_AUTHCFG, "Respond to AuthType Basic and convert to shib?"),
1012 AP_INIT_FLAG("ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1013 (void *) offsetof (shib_dir_config, bRequireSession),
1014 OR_AUTHCFG, "Initiates a new session if one does not exist."),
1015 AP_INIT_FLAG("ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
1016 (void *) offsetof (shib_dir_config, szRequireWith),
1017 OR_AUTHCFG, "Initiates a new session if one does not exist using a specific SessionInitiator"),
1018 AP_INIT_FLAG("ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1019 (void *) offsetof (shib_dir_config, bExportAssertion),
1020 OR_AUTHCFG, "Export SAML attribute assertion(s) to Shib-Attributes header?"),
1021 AP_INIT_TAKE1("AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
1022 (void *) offsetof (shib_dir_config, szAuthGrpFile),
1023 OR_AUTHCFG, "Text file containing group names and member user IDs"),
1024 AP_INIT_FLAG("ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1025 (void *) offsetof (shib_dir_config, bRequireAll),
1026 OR_AUTHCFG, "All require directives must match!"),
1031 module AP_MODULE_DECLARE_DATA mod_shib = {
1032 STANDARD20_MODULE_STUFF,
1033 create_shib_dir_config, /* create dir config */
1034 merge_shib_dir_config, /* merge dir config --- default is to override */
1035 create_shib_server_config, /* create server config */
1036 merge_shib_server_config, /* merge server config */
1037 shib_cmds, /* command table */
1038 shib_register_hooks /* register hooks */
1042 #error "undefined APACHE version"