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());
330 ShibTargetApache sta(r);
332 // Check user authentication and export information, then set the handler bypass
333 pair<bool,void*> res = sta.doCheckAuthN(true);
334 apr_pool_userdata_setn((const void*)42,g_UserDataKey,NULL,r->pool);
335 if (res.first) return (int)res.second;
337 // user auth was okay -- export the assertions now
338 res = sta.doExportAssertions();
339 if (res.first) return (int)res.second;
341 // export happened successfully.. this user is ok.
346 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user threw an uncaught exception!");
352 extern "C" int shib_handler(request_rec* r)
354 // Short-circuit entirely?
355 if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
358 ostringstream threadid;
359 threadid << "[" << getpid() << "] shib_handler" << '\0';
360 saml::NDC ndc(threadid.str().c_str());
362 #ifndef SHIB_APACHE_13
363 // With 2.x, this handler always runs, though last.
364 // We check if shib_check_user ran, because it will detect a handler request
365 // and dispatch it directly.
367 apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
368 if (data==(const void*)42) {
369 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler skipped since check_user ran");
374 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.");
389 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler threw an uncaught exception!");
396 * shib_auth_checker() -- a simple resource manager to
397 * process the .htaccess settings
399 extern "C" int shib_auth_checker(request_rec* r)
401 // Short-circuit entirely?
402 if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
405 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_auth_checker(%d): ENTER", (int)getpid());
407 ostringstream threadid;
408 threadid << "[" << getpid() << "] shib_auth_checker" << '\0';
409 saml::NDC ndc(threadid.str().c_str());
414 ShibTargetApache sta(r);
416 pair<bool,void*> res = sta.doCheckAuthZ();
417 if (res.first) return (int)res.second;
424 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an uncaught exception!");
430 // Access control plugin that enforces htaccess rules
431 class htAccessControl : virtual public IAccessControl
435 ~htAccessControl() {}
440 ISessionCacheEntry* entry
444 IPlugIn* htAccessFactory(const DOMElement* e)
446 return new htAccessControl();
449 class ApacheRequestMapper : public virtual IRequestMapper, public virtual IPropertySet
452 ApacheRequestMapper(const DOMElement* e);
453 ~ApacheRequestMapper() { delete m_mapper; delete m_htaccess; delete m_staKey; delete m_propsKey; }
454 void lock() { m_mapper->lock(); }
455 void unlock() { m_staKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
456 Settings getSettings(ShibTarget* st) const;
458 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
459 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
460 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
461 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
462 pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
463 const IPropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
464 const DOMElement* getElement() const;
467 IRequestMapper* m_mapper;
469 ThreadKey* m_propsKey;
470 IAccessControl* m_htaccess;
473 IPlugIn* ApacheRequestMapFactory(const DOMElement* e)
475 return new ApacheRequestMapper(e);
478 ApacheRequestMapper::ApacheRequestMapper(const DOMElement* e) : m_mapper(NULL), m_htaccess(NULL), m_staKey(NULL), m_propsKey(NULL)
480 IPlugIn* p=SAMLConfig::getConfig().getPlugMgr().newPlugin(shibtarget::XML::XMLRequestMapType,e);
481 m_mapper=dynamic_cast<IRequestMapper*>(p);
484 throw UnsupportedExtensionException("Embedded request mapper plugin was not of correct type.");
486 m_htaccess=new htAccessControl();
487 m_staKey=ThreadKey::create(NULL);
488 m_propsKey=ThreadKey::create(NULL);
491 IRequestMapper::Settings ApacheRequestMapper::getSettings(ShibTarget* st) const
493 Settings s=m_mapper->getSettings(st);
494 m_staKey->setData(dynamic_cast<ShibTargetApache*>(st));
495 m_propsKey->setData((void*)s.first);
496 return pair<const IPropertySet*,IAccessControl*>(this,s.second ? s.second : m_htaccess);
499 pair<bool,bool> ApacheRequestMapper::getBool(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 boolean properties.
505 if (name && !strcmp(name,"requireSession") && sta->m_dc->bRequireSession==1)
506 return make_pair(true,true);
507 else if (name && !strcmp(name,"exportAssertion") && sta->m_dc->bExportAssertion==1)
508 return make_pair(true,true);
510 return s ? s->getBool(name,ns) : make_pair(false,false);
513 pair<bool,const char*> ApacheRequestMapper::getString(const char* name, const char* ns) const
515 ShibTargetApache* sta=reinterpret_cast<ShibTargetApache*>(m_staKey->getData());
516 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
518 // Override Apache-settable string properties.
519 if (name && !strcmp(name,"authType")) {
520 const char *auth_type=ap_auth_type(sta->m_req);
522 // Check for Basic Hijack
523 if (!strcasecmp(auth_type, "basic") && sta->m_dc->bBasicHijack == 1)
524 auth_type = "shibboleth";
525 return make_pair(true,auth_type);
528 else if (name && !strcmp(name,"applicationId") && sta->m_dc->szApplicationId)
529 return pair<bool,const char*>(true,sta->m_dc->szApplicationId);
530 else if (name && !strcmp(name,"requireSessionWith") && sta->m_dc->szRequireWith)
531 return pair<bool,const char*>(true,sta->m_dc->szRequireWith);
533 return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
536 pair<bool,const XMLCh*> ApacheRequestMapper::getXMLString(const char* name, const char* ns) const
538 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
539 return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
542 pair<bool,unsigned int> ApacheRequestMapper::getUnsignedInt(const char* name, const char* ns) const
544 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
545 return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
548 pair<bool,int> ApacheRequestMapper::getInt(const char* name, const char* ns) const
550 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
551 return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
554 const IPropertySet* ApacheRequestMapper::getPropertySet(const char* name, const char* ns) const
556 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
557 return s ? s->getPropertySet(name,ns) : NULL;
560 const DOMElement* ApacheRequestMapper::getElement() const
562 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
563 return s ? s->getElement() : NULL;
566 static SH_AP_TABLE* groups_for_user(request_rec* r, const char* user, char* grpfile)
569 SH_AP_TABLE* grps=ap_make_table(r->pool,15);
570 char l[MAX_STRING_LEN];
571 const char *group_name, *ll, *w;
573 #ifdef SHIB_APACHE_13
574 if (!(f=ap_pcfg_openfile(r->pool,grpfile))) {
576 if (ap_pcfg_openfile(&f,r->pool,grpfile) != APR_SUCCESS) {
578 ap_log_rerror(APLOG_MARK,APLOG_DEBUG,SH_AP_R(r),"groups_for_user() could not open group file: %s\n",grpfile);
583 #ifdef SHIB_APACHE_13
584 sp=ap_make_sub_pool(r->pool);
586 if (apr_pool_create(&sp,r->pool) != APR_SUCCESS) {
587 ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,
588 "groups_for_user() could not create a subpool");
593 while (!(ap_cfg_getline(l,MAX_STRING_LEN,f))) {
594 if ((*l=='#') || (!*l))
599 group_name=ap_getword(sp,&ll,':');
602 w=ap_getword_conf(sp,&ll);
603 if (!strcmp(w,user)) {
604 ap_table_setn(grps,ap_pstrdup(r->pool,group_name),"in");
614 bool htAccessControl::authorized(
616 ISessionCacheEntry* entry
619 // Make sure the object is our type.
620 ShibTargetApache* sta=dynamic_cast<ShibTargetApache*>(st);
622 throw ConfigurationException("Request wrapper object was not of correct type.");
626 int m=sta->m_req->method_number;
627 bool method_restricted=false;
630 const array_header* reqs_arr=ap_requires(sta->m_req);
634 require_line* reqs=(require_line*)reqs_arr->elts;
636 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(sta->m_req),"REQUIRE nelts: %d", reqs_arr->nelts);
637 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(sta->m_req),"REQUIRE all: %d", sta->m_dc->bRequireAll);
639 vector<bool> auth_OK(reqs_arr->nelts,false);
641 #define SHIB_AP_CHECK_IS_OK { \
642 if (sta->m_dc->bRequireAll < 1) \
648 for (int x=0; x<reqs_arr->nelts; x++) {
650 if (!(reqs[x].method_mask & (1 << m)))
652 method_restricted=true;
653 string remote_user = st->getRemoteUser();
655 t = reqs[x].requirement;
656 w = ap_getword_white(sta->m_req->pool, &t);
658 if (!strcasecmp(w,"shibboleth")) {
659 // This is a dummy rule needed because Apache conflates authn and authz.
660 // Without some require rule, AuthType is ignored and no check_user hooks run.
663 else if (!strcmp(w,"valid-user") && entry) {
664 st->log(ShibTarget::LogLevelDebug,"htAccessControl plugin accepting valid-user based on active session");
667 else if (!strcmp(w,"user") && !remote_user.empty()) {
670 w=ap_getword_conf(sta->m_req->pool,&t);
678 // To do regex matching, we have to convert from UTF-8.
679 auto_ptr<XMLCh> trans(fromUTF8(w));
680 RegularExpression re(trans.get());
681 auto_ptr<XMLCh> trans2(fromUTF8(remote_user.c_str()));
682 if (re.matches(trans2.get())) {
683 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin accepting user (") + w + ")");
687 catch (XMLException& ex) {
688 auto_ptr_char tmp(ex.getMessage());
689 st->log(ShibTarget::LogLevelError,
690 string("htAccessControl plugin caught exception while parsing regular expression (") + w + "): " + tmp.get());
693 else if (remote_user==w) {
694 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin accepting user (") + w + ")");
699 else if (!strcmp(w,"group")) {
700 SH_AP_TABLE* grpstatus=NULL;
701 if (sta->m_dc->szAuthGrpFile && !remote_user.empty()) {
702 st->log(ShibTarget::LogLevelDebug,string("htAccessControl plugin using groups file: ") + sta->m_dc->szAuthGrpFile);
703 grpstatus=groups_for_user(sta->m_req,remote_user.c_str(),sta->m_dc->szAuthGrpFile);
709 w=ap_getword_conf(sta->m_req->pool,&t);
710 if (ap_table_get(grpstatus,w)) {
711 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin accepting group (") + w + ")");
717 Iterator<IAAP*> provs=st->getApplication()->getAAPProviders();
718 AAP wrapper(provs,w);
719 if (wrapper.fail()) {
720 st->log(ShibTarget::LogLevelWarn, string("htAccessControl plugin didn't recognize require rule: ") + w);
725 const char* vals=ap_table_get(sta->m_req->headers_in,wrapper->getHeader());
727 w=ap_getword_conf(sta->m_req->pool,&t);
734 auto_ptr<RegularExpression> re;
737 auto_ptr<XMLCh> trans(fromUTF8(w));
738 auto_ptr<RegularExpression> temp(new RegularExpression(trans.get()));
742 string vals_str(vals);
744 for (unsigned int i = 0; i < vals_str.length(); i++) {
745 if (vals_str.at(i) == ';') {
747 st->log(ShibTarget::LogLevelError, string("htAccessControl plugin found invalid header encoding (") +
748 vals + "): starts with a semicolon");
749 throw SAMLException("Invalid information supplied to authorization plugin.");
752 if (vals_str.at(i-1) == '\\') {
753 vals_str.erase(i-1, 1);
758 string val = vals_str.substr(j, i-j);
761 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
762 if (re->matches(trans.get())) {
763 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
764 ", got " + val + ": authorization granted");
768 else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
769 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
770 ", got " + val + ": authorization granted.");
774 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
775 ", got " + val + ": authoritzation not granted.");
780 string val = vals_str.substr(j, vals_str.length()-j);
782 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
783 if (re->matches(trans.get())) {
784 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
785 ", got " + val + ": authorization granted.");
789 else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
790 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
791 ", got " + val + ": authorization granted");
795 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
796 ", got " + val + ": authorization not granted");
799 catch (XMLException& ex) {
800 auto_ptr_char tmp(ex.getMessage());
801 st->log(ShibTarget::LogLevelError, string("htAccessControl plugin caught exception while parsing regular expression (")
802 + w + "): " + tmp.get());
808 // check if all require directives are true
809 bool auth_all_OK = true;
810 for (int i= 0; i<reqs_arr->nelts; i++) {
811 auth_all_OK &= auth_OK[i];
813 if (auth_all_OK || !method_restricted)
819 #ifndef SHIB_APACHE_13
822 * Empty cleanup hook, Apache 2.x doesn't check NULL very well...
824 extern "C" apr_status_t shib_exit(void* data)
827 g_Config->shutdown();
830 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,0,NULL,"shib_exit() done\n");
838 * Cleanup the (per-process) pool info.
840 #ifdef SHIB_APACHE_13
841 extern "C" void shib_child_exit(server_rec* s, SH_AP_POOL* p)
844 extern "C" apr_status_t shib_child_exit(void* data)
846 server_rec* s = NULL;
849 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit(%d) dealing with g_Config..", (int)getpid());
850 g_Config->shutdown();
852 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit() done\n");
854 #ifndef SHIB_APACHE_13
861 * Things to do when the child process is initialized.
862 * (or after the configs are read in apache-2)
864 #ifdef SHIB_APACHE_13
865 extern "C" void shib_child_init(server_rec* s, SH_AP_POOL* p)
867 extern "C" void shib_child_init(apr_pool_t* p, server_rec* s)
870 // Initialize runtime components.
872 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init(%d) starting", (int)getpid());
875 ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() already initialized!");
880 g_Config=&ShibTargetConfig::getConfig();
881 g_Config->setFeatures(
882 ShibTargetConfig::Listener |
883 ShibTargetConfig::Metadata |
884 ShibTargetConfig::AAP |
885 ShibTargetConfig::RequestMapper |
886 ShibTargetConfig::LocalExtensions |
887 ShibTargetConfig::Logging
889 if (!g_Config->init(g_szSchemaDir)) {
890 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize libraries");
893 SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::htAccessControlType,&htAccessFactory);
894 SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::NativeRequestMapType,&ApacheRequestMapFactory);
895 // We hijack the legacy type so that 1.2 config files will load this plugin
896 SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::LegacyRequestMapType,&ApacheRequestMapFactory);
898 if (!g_Config->load(g_szSHIBConfig)) {
899 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to load configuration");
904 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize system");
908 // Set the cleanup handler
909 apr_pool_cleanup_register(p, NULL, &shib_exit, &shib_child_exit);
911 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() done");
914 typedef const char* (*config_fn_t)(void);
916 #ifdef SHIB_APACHE_13
918 // SHIB Module commands
920 static command_rec shire_cmds[] = {
921 {"SHIREConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
922 RSRC_CONF, TAKE1, "Path to shibboleth.xml config file."},
923 {"ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
924 RSRC_CONF, TAKE1, "Path to shibboleth.xml config file."},
925 {"ShibSchemaDir", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
926 RSRC_CONF, TAKE1, "Path to Shibboleth XML schema directory."},
928 {"ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
929 (void *) XtOffsetOf (shib_server_config, szScheme),
930 RSRC_CONF, TAKE1, "URL scheme to force into generated URLs for a vhost."},
932 {"ShibDisable", (config_fn_t)ap_set_flag_slot,
933 (void *) XtOffsetOf (shib_dir_config, bOff),
934 OR_AUTHCFG, FLAG, "Disable all Shib module activity here to save processing effort"},
935 {"ShibApplicationId", (config_fn_t)ap_set_string_slot,
936 (void *) XtOffsetOf (shib_dir_config, szApplicationId),
937 OR_AUTHCFG, FLAG, "Set Shibboleth applicationId property for content"},
938 {"ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
939 (void *) XtOffsetOf (shib_dir_config, bBasicHijack),
940 OR_AUTHCFG, FLAG, "Respond to AuthType Basic and convert to shib?"},
941 {"ShibRequireSession", (config_fn_t)ap_set_flag_slot,
942 (void *) XtOffsetOf (shib_dir_config, bRequireSession),
943 OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist."},
944 {"ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
945 (void *) XtOffsetOf (shib_dir_config, szRequireWith),
946 OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist using a specific SessionInitiator"},
947 {"ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
948 (void *) XtOffsetOf (shib_dir_config, bExportAssertion),
949 OR_AUTHCFG, FLAG, "Export SAML attribute assertion(s) to Shib-Attributes header?"},
950 {"AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
951 (void *) XtOffsetOf (shib_dir_config, szAuthGrpFile),
952 OR_AUTHCFG, TAKE1, "text file containing group names and member user IDs"},
953 {"ShibRequireAll", (config_fn_t)ap_set_flag_slot,
954 (void *) XtOffsetOf (shib_dir_config, bRequireAll),
955 OR_AUTHCFG, FLAG, "All require directives must match!"},
961 handler_rec shib_handlers[] = {
962 { "shib-handler", shib_handler },
966 module MODULE_VAR_EXPORT mod_shib = {
967 STANDARD_MODULE_STUFF,
968 NULL, /* initializer */
969 create_shib_dir_config, /* dir config creater */
970 merge_shib_dir_config, /* dir merger --- default is to override */
971 create_shib_server_config, /* server config */
972 merge_shib_server_config, /* merge server config */
973 shire_cmds, /* command table */
974 shib_handlers, /* handlers */
975 NULL, /* filename translation */
976 shib_check_user, /* check_user_id */
977 shib_auth_checker, /* check auth */
978 NULL, /* check access */
979 NULL, /* type_checker */
982 NULL, /* header parser */
983 shib_child_init, /* child_init */
984 shib_child_exit, /* child_exit */
985 NULL /* post read-request */
988 #elif defined(SHIB_APACHE_20)
990 extern "C" void shib_register_hooks (apr_pool_t *p)
992 ap_hook_child_init(shib_child_init, NULL, NULL, APR_HOOK_MIDDLE);
993 ap_hook_check_user_id(shib_check_user, NULL, NULL, APR_HOOK_MIDDLE);
994 ap_hook_auth_checker(shib_auth_checker, NULL, NULL, APR_HOOK_FIRST);
995 ap_hook_handler(shib_handler, NULL, NULL, APR_HOOK_LAST);
998 // SHIB Module commands
1001 static command_rec shib_cmds[] = {
1002 AP_INIT_TAKE1("ShibConfig",
1003 (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1004 RSRC_CONF, "Path to shibboleth.xml config file."),
1005 AP_INIT_TAKE1("ShibSchemaDir",
1006 (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1007 RSRC_CONF, "Path to Shibboleth XML schema directory."),
1009 AP_INIT_TAKE1("ShibURLScheme",
1010 (config_fn_t)shib_set_server_string_slot,
1011 (void *) offsetof (shib_server_config, szScheme),
1012 RSRC_CONF, "URL scheme to force into generated URLs for a vhost."),
1014 AP_INIT_FLAG("ShibDisable", (config_fn_t)ap_set_flag_slot,
1015 (void *) offsetof (shib_dir_config, bOff),
1016 OR_AUTHCFG, "Disable all Shib module activity here to save processing effort"),
1017 AP_INIT_TAKE1("ShibApplicationId", (config_fn_t)ap_set_string_slot,
1018 (void *) offsetof (shib_dir_config, szApplicationId),
1019 OR_AUTHCFG, "Set Shibboleth applicationId property for content"),
1020 AP_INIT_FLAG("ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1021 (void *) offsetof (shib_dir_config, bBasicHijack),
1022 OR_AUTHCFG, "Respond to AuthType Basic and convert to shib?"),
1023 AP_INIT_FLAG("ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1024 (void *) offsetof (shib_dir_config, bRequireSession),
1025 OR_AUTHCFG, "Initiates a new session if one does not exist."),
1026 AP_INIT_TAKE1("ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
1027 (void *) offsetof (shib_dir_config, szRequireWith),
1028 OR_AUTHCFG, "Initiates a new session if one does not exist using a specific SessionInitiator"),
1029 AP_INIT_FLAG("ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1030 (void *) offsetof (shib_dir_config, bExportAssertion),
1031 OR_AUTHCFG, "Export SAML attribute assertion(s) to Shib-Attributes header?"),
1032 AP_INIT_TAKE1("AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
1033 (void *) offsetof (shib_dir_config, szAuthGrpFile),
1034 OR_AUTHCFG, "Text file containing group names and member user IDs"),
1035 AP_INIT_FLAG("ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1036 (void *) offsetof (shib_dir_config, bRequireAll),
1037 OR_AUTHCFG, "All require directives must match!"),
1042 module AP_MODULE_DECLARE_DATA mod_shib = {
1043 STANDARD20_MODULE_STUFF,
1044 create_shib_dir_config, /* create dir config */
1045 merge_shib_dir_config, /* merge dir config --- default is to override */
1046 create_shib_server_config, /* create server config */
1047 merge_shib_server_config, /* merge server config */
1048 shib_cmds, /* command table */
1049 shib_register_hooks /* register hooks */
1053 #error "undefined APACHE version"