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 int offset=(int)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") && entry) {
670 st->log(ShibTarget::LogLevelDebug,"htAccessControl plugin accepting valid-user based on active session");
673 else if (!strcmp(w,"user") && !remote_user.empty()) {
676 w=ap_getword_conf(sta->m_req->pool,&t);
684 // To do regex matching, we have to convert from UTF-8.
685 auto_ptr<XMLCh> trans(fromUTF8(w));
686 RegularExpression re(trans.get());
687 auto_ptr<XMLCh> trans2(fromUTF8(remote_user.c_str()));
688 if (re.matches(trans2.get())) {
689 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin accepting user (") + w + ")");
693 catch (XMLException& ex) {
694 auto_ptr_char tmp(ex.getMessage());
695 st->log(ShibTarget::LogLevelError,
696 string("htAccessControl plugin caught exception while parsing regular expression (") + w + "): " + tmp.get());
699 else if (remote_user==w) {
700 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin accepting user (") + w + ")");
705 else if (!strcmp(w,"group")) {
706 SH_AP_TABLE* grpstatus=NULL;
707 if (sta->m_dc->szAuthGrpFile && !remote_user.empty()) {
708 st->log(ShibTarget::LogLevelDebug,string("htAccessControl plugin using groups file: ") + sta->m_dc->szAuthGrpFile);
709 grpstatus=groups_for_user(sta->m_req,remote_user.c_str(),sta->m_dc->szAuthGrpFile);
715 w=ap_getword_conf(sta->m_req->pool,&t);
716 if (ap_table_get(grpstatus,w)) {
717 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin accepting group (") + w + ")");
723 Iterator<IAAP*> provs=st->getApplication()->getAAPProviders();
724 AAP wrapper(provs,w);
725 if (wrapper.fail()) {
726 st->log(ShibTarget::LogLevelWarn, string("htAccessControl plugin didn't recognize require rule: ") + w);
731 const char* vals=ap_table_get(sta->m_req->headers_in,wrapper->getHeader());
733 w=ap_getword_conf(sta->m_req->pool,&t);
740 auto_ptr<RegularExpression> re;
743 auto_ptr<XMLCh> trans(fromUTF8(w));
744 auto_ptr<RegularExpression> temp(new RegularExpression(trans.get()));
748 string vals_str(vals);
750 for (int i = 0; i < vals_str.length(); i++) {
751 if (vals_str.at(i) == ';') {
753 st->log(ShibTarget::LogLevelError, string("htAccessControl plugin found invalid header encoding (") +
754 vals + "): starts with a semicolon");
755 throw SAMLException("Invalid information supplied to authorization plugin.");
758 if (vals_str.at(i-1) == '\\') {
759 vals_str.erase(i-1, 1);
764 string val = vals_str.substr(j, i-j);
767 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
768 if (re->matches(trans.get())) {
769 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
770 ", got " + val + ": authorization granted");
774 else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
775 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
776 ", got " + val + ": authorization granted.");
780 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
781 ", got " + val + ": authoritzation not granted.");
786 string val = vals_str.substr(j, vals_str.length()-j);
788 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
789 if (re->matches(trans.get())) {
790 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
791 ", got " + val + ": authorization granted.");
795 else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
796 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
797 ", got " + val + ": authorization granted");
801 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
802 ", got " + val + ": authorization not granted");
805 catch (XMLException& ex) {
806 auto_ptr_char tmp(ex.getMessage());
807 st->log(ShibTarget::LogLevelError, string("htAccessControl plugin caught exception while parsing regular expression (")
808 + w + "): " + tmp.get());
814 // check if all require directives are true
815 bool auth_all_OK = true;
816 for (int i= 0; i<reqs_arr->nelts; i++) {
817 auth_all_OK &= auth_OK[i];
819 if (auth_all_OK || !method_restricted)
825 #ifndef SHIB_APACHE_13
828 * Empty cleanup hook, Apache 2.x doesn't check NULL very well...
830 extern "C" apr_status_t shib_exit(void* data)
833 g_Config->shutdown();
836 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,0,NULL,"shib_exit() done\n");
844 * Cleanup the (per-process) pool info.
846 #ifdef SHIB_APACHE_13
847 extern "C" void shib_child_exit(server_rec* s, SH_AP_POOL* p)
850 extern "C" apr_status_t shib_child_exit(void* data)
852 server_rec* s = NULL;
855 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit(%d) dealing with g_Config..", (int)getpid());
856 g_Config->shutdown();
858 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit() done\n");
860 #ifndef SHIB_APACHE_13
867 * Things to do when the child process is initialized.
868 * (or after the configs are read in apache-2)
870 #ifdef SHIB_APACHE_13
871 extern "C" void shib_child_init(server_rec* s, SH_AP_POOL* p)
873 extern "C" void shib_child_init(apr_pool_t* p, server_rec* s)
876 // Initialize runtime components.
878 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init(%d) starting", (int)getpid());
881 ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() already initialized!");
886 g_Config=&ShibTargetConfig::getConfig();
887 g_Config->setFeatures(
888 ShibTargetConfig::Listener |
889 ShibTargetConfig::Metadata |
890 ShibTargetConfig::AAP |
891 ShibTargetConfig::RequestMapper |
892 ShibTargetConfig::LocalExtensions |
893 ShibTargetConfig::Logging
895 if (!g_Config->init(g_szSchemaDir)) {
896 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize libraries");
899 SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::htAccessControlType,&htAccessFactory);
900 SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::NativeRequestMapType,&ApacheRequestMapFactory);
901 // We hijack the legacy type so that 1.2 config files will load this plugin
902 SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::LegacyRequestMapType,&ApacheRequestMapFactory);
904 if (!g_Config->load(g_szSHIBConfig)) {
905 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to load configuration");
910 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize system");
914 // Set the cleanup handler
915 apr_pool_cleanup_register(p, NULL, &shib_exit, &shib_child_exit);
917 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() done");
920 typedef const char* (*config_fn_t)(void);
922 #ifdef SHIB_APACHE_13
924 // SHIB Module commands
926 static command_rec shire_cmds[] = {
927 {"SHIREConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
928 RSRC_CONF, TAKE1, "Path to shibboleth.xml config file."},
929 {"ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
930 RSRC_CONF, TAKE1, "Path to shibboleth.xml config file."},
931 {"ShibSchemaDir", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
932 RSRC_CONF, TAKE1, "Path to Shibboleth XML schema directory."},
934 {"ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
935 (void *) XtOffsetOf (shib_server_config, szScheme),
936 RSRC_CONF, TAKE1, "URL scheme to force into generated URLs for a vhost."},
938 {"ShibDisable", (config_fn_t)ap_set_flag_slot,
939 (void *) XtOffsetOf (shib_dir_config, bOff),
940 OR_AUTHCFG, FLAG, "Disable all Shib module activity here to save processing effort"},
941 {"ShibApplicationId", (config_fn_t)ap_set_string_slot,
942 (void *) XtOffsetOf (shib_dir_config, szApplicationId),
943 OR_AUTHCFG, FLAG, "Set Shibboleth applicationId property for content"},
944 {"ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
945 (void *) XtOffsetOf (shib_dir_config, bBasicHijack),
946 OR_AUTHCFG, FLAG, "Respond to AuthType Basic and convert to shib?"},
947 {"ShibRequireSession", (config_fn_t)ap_set_flag_slot,
948 (void *) XtOffsetOf (shib_dir_config, bRequireSession),
949 OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist."},
950 {"ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
951 (void *) XtOffsetOf (shib_dir_config, szRequireWith),
952 OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist using a specific SessionInitiator"},
953 {"ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
954 (void *) XtOffsetOf (shib_dir_config, bExportAssertion),
955 OR_AUTHCFG, FLAG, "Export SAML attribute assertion(s) to Shib-Attributes header?"},
956 {"AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
957 (void *) XtOffsetOf (shib_dir_config, szAuthGrpFile),
958 OR_AUTHCFG, TAKE1, "text file containing group names and member user IDs"},
959 {"ShibRequireAll", (config_fn_t)ap_set_flag_slot,
960 (void *) XtOffsetOf (shib_dir_config, bRequireAll),
961 OR_AUTHCFG, FLAG, "All require directives must match!"},
967 handler_rec shib_handlers[] = {
968 { "shib-handler", shib_handler },
972 module MODULE_VAR_EXPORT mod_shib = {
973 STANDARD_MODULE_STUFF,
974 NULL, /* initializer */
975 create_shib_dir_config, /* dir config creater */
976 merge_shib_dir_config, /* dir merger --- default is to override */
977 create_shib_server_config, /* server config */
978 merge_shib_server_config, /* merge server config */
979 shire_cmds, /* command table */
980 shib_handlers, /* handlers */
981 NULL, /* filename translation */
982 shib_check_user, /* check_user_id */
983 shib_auth_checker, /* check auth */
984 NULL, /* check access */
985 NULL, /* type_checker */
988 NULL, /* header parser */
989 shib_child_init, /* child_init */
990 shib_child_exit, /* child_exit */
991 NULL /* post read-request */
994 #elif defined(SHIB_APACHE_20)
996 extern "C" void shib_register_hooks (apr_pool_t *p)
998 ap_hook_child_init(shib_child_init, NULL, NULL, APR_HOOK_MIDDLE);
999 ap_hook_check_user_id(shib_check_user, NULL, NULL, APR_HOOK_MIDDLE);
1000 ap_hook_auth_checker(shib_auth_checker, NULL, NULL, APR_HOOK_FIRST);
1001 ap_hook_handler(shib_handler, NULL, NULL, APR_HOOK_LAST);
1004 // SHIB Module commands
1007 static command_rec shib_cmds[] = {
1008 AP_INIT_TAKE1("ShibConfig",
1009 (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1010 RSRC_CONF, "Path to shibboleth.xml config file."),
1011 AP_INIT_TAKE1("ShibSchemaDir",
1012 (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1013 RSRC_CONF, "Path to Shibboleth XML schema directory."),
1015 AP_INIT_TAKE1("ShibURLScheme",
1016 (config_fn_t)shib_set_server_string_slot,
1017 (void *) offsetof (shib_server_config, szScheme),
1018 RSRC_CONF, "URL scheme to force into generated URLs for a vhost."),
1020 AP_INIT_FLAG("ShibDisable", (config_fn_t)ap_set_flag_slot,
1021 (void *) offsetof (shib_dir_config, bOff),
1022 OR_AUTHCFG, "Disable all Shib module activity here to save processing effort"),
1023 AP_INIT_TAKE1("ShibApplicationId", (config_fn_t)ap_set_string_slot,
1024 (void *) offsetof (shib_dir_config, szApplicationId),
1025 OR_AUTHCFG, "Set Shibboleth applicationId property for content"),
1026 AP_INIT_FLAG("ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1027 (void *) offsetof (shib_dir_config, bBasicHijack),
1028 OR_AUTHCFG, "Respond to AuthType Basic and convert to shib?"),
1029 AP_INIT_FLAG("ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1030 (void *) offsetof (shib_dir_config, bRequireSession),
1031 OR_AUTHCFG, "Initiates a new session if one does not exist."),
1032 AP_INIT_TAKE1("ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
1033 (void *) offsetof (shib_dir_config, szRequireWith),
1034 OR_AUTHCFG, "Initiates a new session if one does not exist using a specific SessionInitiator"),
1035 AP_INIT_FLAG("ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1036 (void *) offsetof (shib_dir_config, bExportAssertion),
1037 OR_AUTHCFG, "Export SAML attribute assertion(s) to Shib-Attributes header?"),
1038 AP_INIT_TAKE1("AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
1039 (void *) offsetof (shib_dir_config, szAuthGrpFile),
1040 OR_AUTHCFG, "Text file containing group names and member user IDs"),
1041 AP_INIT_FLAG("ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1042 (void *) offsetof (shib_dir_config, bRequireAll),
1043 OR_AUTHCFG, "All require directives must match!"),
1048 module AP_MODULE_DECLARE_DATA mod_shib = {
1049 STANDARD20_MODULE_STUFF,
1050 create_shib_dir_config, /* create dir config */
1051 merge_shib_dir_config, /* merge dir config --- default is to override */
1052 create_shib_server_config, /* create server config */
1053 merge_shib_server_config, /* merge server config */
1054 shib_cmds, /* command table */
1055 shib_register_hooks /* register hooks */
1059 #error "undefined APACHE version"