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 # define _CRT_NONSTDC_NO_DEPRECATE 1
31 # define _CRT_SECURE_NO_DEPRECATE 1
35 #include <saml/saml.h>
36 #include <shib/shib.h>
37 #include <shib-target/shib-target.h>
38 #include <shibsp/SPConfig.h>
39 #include <xercesc/util/regx/RegularExpression.hpp>
47 // Apache specific header files
49 #include <http_config.h>
50 #include <http_protocol.h>
51 #include <http_main.h>
53 #include <http_core.h>
56 #ifndef SHIB_APACHE_13
57 #include <http_request.h>
58 #include <apr_strings.h>
59 #include <apr_pools.h>
66 #include <unistd.h> // for getpid()
69 using namespace shibsp;
70 using namespace shibtarget;
72 using namespace xmltooling;
75 extern "C" module MODULE_VAR_EXPORT mod_shib;
78 char* g_szSHIBConfig = NULL;
79 char* g_szSchemaDir = NULL;
80 ShibTargetConfig* g_Config = NULL;
81 string g_unsetHeaderValue;
82 static const char* g_UserDataKey = "_shib_check_user_";
85 /********************************************************************************/
86 // Basic Apache Configuration code.
89 // per-server module configuration structure
90 struct shib_server_config
95 // creates the per-server configuration
96 extern "C" void* create_shib_server_config(SH_AP_POOL* p, server_rec* s)
98 shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
103 // overrides server configuration in virtual servers
104 extern "C" void* merge_shib_server_config (SH_AP_POOL* p, void* base, void* sub)
106 shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
107 shib_server_config* parent=(shib_server_config*)base;
108 shib_server_config* child=(shib_server_config*)sub;
111 sc->szScheme=ap_pstrdup(p,child->szScheme);
112 else if (parent->szScheme)
113 sc->szScheme=ap_pstrdup(p,parent->szScheme);
120 // per-dir module configuration structure
121 struct shib_dir_config
124 char* szAuthGrpFile; // Auth GroupFile name
125 int bRequireAll; // all require directives must match, otherwise OR logic
127 // Content Configuration
128 char* szApplicationId; // Shib applicationId value
129 char* szRequireWith; // require a session using a specific initiator?
130 char* szRedirectToSSL; // redirect non-SSL requests to SSL port
131 int bOff; // flat-out disable all Shib processing
132 int bBasicHijack; // activate for AuthType Basic?
133 int bRequireSession; // require a session?
134 int bExportAssertion; // export SAML assertion to the environment?
137 // creates per-directory config structure
138 extern "C" void* create_shib_dir_config (SH_AP_POOL* p, char* d)
140 shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
142 dc->bBasicHijack = -1;
143 dc->bRequireSession = -1;
144 dc->bExportAssertion = -1;
145 dc->bRequireAll = -1;
146 dc->szRedirectToSSL = NULL;
147 dc->szAuthGrpFile = NULL;
148 dc->szApplicationId = NULL;
149 dc->szRequireWith = NULL;
153 // overrides server configuration in directories
154 extern "C" void* merge_shib_dir_config (SH_AP_POOL* p, void* base, void* sub)
156 shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
157 shib_dir_config* parent=(shib_dir_config*)base;
158 shib_dir_config* child=(shib_dir_config*)sub;
160 if (child->szAuthGrpFile)
161 dc->szAuthGrpFile=ap_pstrdup(p,child->szAuthGrpFile);
162 else if (parent->szAuthGrpFile)
163 dc->szAuthGrpFile=ap_pstrdup(p,parent->szAuthGrpFile);
165 dc->szAuthGrpFile=NULL;
167 if (child->szApplicationId)
168 dc->szApplicationId=ap_pstrdup(p,child->szApplicationId);
169 else if (parent->szApplicationId)
170 dc->szApplicationId=ap_pstrdup(p,parent->szApplicationId);
172 dc->szApplicationId=NULL;
174 if (child->szRequireWith)
175 dc->szRequireWith=ap_pstrdup(p,child->szRequireWith);
176 else if (parent->szRequireWith)
177 dc->szRequireWith=ap_pstrdup(p,parent->szRequireWith);
179 dc->szRequireWith=NULL;
181 if (child->szRedirectToSSL)
182 dc->szRedirectToSSL=ap_pstrdup(p,child->szRedirectToSSL);
183 else if (parent->szRedirectToSSL)
184 dc->szRedirectToSSL=ap_pstrdup(p,parent->szRedirectToSSL);
186 dc->szRedirectToSSL=NULL;
188 dc->bOff=((child->bOff==-1) ? parent->bOff : child->bOff);
189 dc->bBasicHijack=((child->bBasicHijack==-1) ? parent->bBasicHijack : child->bBasicHijack);
190 dc->bRequireSession=((child->bRequireSession==-1) ? parent->bRequireSession : child->bRequireSession);
191 dc->bExportAssertion=((child->bExportAssertion==-1) ? parent->bExportAssertion : child->bExportAssertion);
192 dc->bRequireAll=((child->bRequireAll==-1) ? parent->bRequireAll : child->bRequireAll);
196 // generic global slot handlers
197 extern "C" const char* ap_set_global_string_slot(cmd_parms* parms, void*, const char* arg)
199 *((char**)(parms->info))=ap_pstrdup(parms->pool,arg);
203 extern "C" const char* shib_set_server_string_slot(cmd_parms* parms, void*, const char* arg)
205 char* base=(char*)ap_get_module_config(parms->server->module_config,&mod_shib);
206 size_t offset=(size_t)parms->info;
207 *((char**)(base + offset))=ap_pstrdup(parms->pool,arg);
211 extern "C" const char* shib_ap_set_file_slot(cmd_parms* parms,
212 #ifdef SHIB_APACHE_13
213 char* arg1, char* arg2
215 void* arg1, const char* arg2
219 ap_set_file_slot(parms, arg1, arg2);
223 /********************************************************************************/
224 // Apache ShibTarget subclass(es) here.
226 class ShibTargetApache : public ShibTarget
228 mutable string m_body;
229 mutable bool m_gotBody;
233 shib_dir_config* m_dc;
234 shib_server_config* m_sc;
236 ShibTargetApache(request_rec* req) : m_gotBody(false) {
237 m_sc = (shib_server_config*)ap_get_module_config(req->server->module_config, &mod_shib);
238 m_dc = (shib_dir_config*)ap_get_module_config(req->per_dir_config, &mod_shib);
241 m_sc->szScheme ? m_sc->szScheme : ap_http_method(req),
242 ap_get_server_name(req),
243 (int)ap_get_server_port(req),
245 ap_table_get(req->headers_in, "Content-type"),
246 req->connection->remote_ip,
252 virtual ~ShibTargetApache() {}
254 virtual void log(ShibLogLevel level, const string &msg) {
255 ShibTarget::log(level,msg);
256 #ifdef SHIB_APACHE_13
257 ap_log_rerror(APLOG_MARK,
258 (level == LogLevelDebug ? APLOG_DEBUG :
259 (level == LogLevelInfo ? APLOG_INFO :
260 (level == LogLevelWarn ? APLOG_WARNING : APLOG_ERR)))|APLOG_NOERRNO, SH_AP_R(m_req), msg.c_str());
262 if (level == LogLevelError)
263 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(m_req), msg.c_str());
266 virtual string getCookies(void) const {
267 const char *c = ap_table_get(m_req->headers_in, "Cookie");
268 return string(c ? c : "");
270 virtual void setCookie(const string &name, const string &value) {
271 char* val = ap_psprintf(m_req->pool, "%s=%s", name.c_str(), value.c_str());
272 ap_table_addn(m_req->err_headers_out, "Set-Cookie", val);
274 virtual const char* getQueryString() const { return m_req->args; }
275 virtual const char* getRequestBody() const {
277 return m_body.c_str();
278 // Read the posted data
279 if (ap_setup_client_block(m_req, REQUEST_CHUNKED_ERROR))
280 throw SAMLException("Apache function (setup_client_block) failed while reading POST request body.");
281 if (!ap_should_client_block(m_req))
282 throw SAMLException("Apache function (should_client_block) failed while reading POST request body.");
283 if (m_req->remaining > 1024*1024)
284 throw SAMLException("Blocked POST request body larger than size limit.");
286 char buff[HUGE_STRING_LEN];
287 ap_hard_timeout("[mod_shib] getRequestBody", m_req);
288 memset(buff, 0, sizeof(buff));
289 while (ap_get_client_block(m_req, buff, sizeof(buff)-1) > 0) {
290 ap_reset_timeout(m_req);
292 memset(buff, 0, sizeof(buff));
294 ap_kill_timeout(m_req);
295 return m_body.c_str();
297 virtual void clearHeader(const string &name) {
298 ap_table_unset(m_req->headers_in, name.c_str());
299 ap_table_set(m_req->headers_in, name.c_str(), g_unsetHeaderValue.c_str());
301 virtual void setHeader(const string &name, const string &value) {
302 ap_table_set(m_req->headers_in, name.c_str(), value.c_str());
304 virtual string getHeader(const string &name) {
305 const char *hdr = ap_table_get(m_req->headers_in, name.c_str());
306 return string(hdr ? hdr : "");
308 virtual void setRemoteUser(const string &user) {
309 SH_AP_USER(m_req) = ap_pstrdup(m_req->pool, user.c_str());
311 virtual string getRemoteUser(void) {
312 return string(SH_AP_USER(m_req) ? SH_AP_USER(m_req) : "");
314 virtual void* sendPage(
317 const string& content_type="text/html",
318 const Iterator<header_t>& headers=EMPTY(header_t)
320 m_req->content_type = ap_psprintf(m_req->pool, content_type.c_str());
321 while (headers.hasNext()) {
322 const header_t& h=headers.next();
323 ap_table_set(m_req->headers_out, h.first.c_str(), h.second.c_str());
325 ap_send_http_header(m_req);
326 ap_rprintf(m_req, msg.c_str());
327 return (void*)((code==200) ? DONE : code);
329 virtual void* sendRedirect(const string& url) {
330 ap_table_set(m_req->headers_out, "Location", url.c_str());
331 return (void*)REDIRECT;
333 virtual void* returnDecline(void) { return (void*)DECLINED; }
334 virtual void* returnOK(void) { return (void*)OK; }
337 /********************************************************************************/
340 extern "C" int shib_check_user(request_rec* r)
342 // Short-circuit entirely?
343 if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
346 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_check_user(%d): ENTER\n", (int)getpid());
348 ostringstream threadid;
349 threadid << "[" << getpid() << "] shib_check_user" << '\0';
350 saml::NDC ndc(threadid.str().c_str());
353 ShibTargetApache sta(r);
355 // Check user authentication and export information, then set the handler bypass
356 pair<bool,void*> res = sta.doCheckAuthN(true);
357 apr_pool_userdata_setn((const void*)42,g_UserDataKey,NULL,r->pool);
358 if (res.first) return (int)res.second;
360 // user auth was okay -- export the assertions now
361 res = sta.doExportAssertions();
362 if (res.first) return (int)res.second;
364 // export happened successfully.. this user is ok.
367 catch (SAMLException& e) {
368 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user threw an exception: %s", e.what());
373 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user threw an uncaught exception!");
379 extern "C" int shib_handler(request_rec* r)
381 // Short-circuit entirely?
382 if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
385 ostringstream threadid;
386 threadid << "[" << getpid() << "] shib_handler" << '\0';
387 saml::NDC ndc(threadid.str().c_str());
389 #ifndef SHIB_APACHE_13
390 // With 2.x, this handler always runs, though last.
391 // We check if shib_check_user ran, because it will detect a handler request
392 // and dispatch it directly.
394 apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
395 if (data==(const void*)42) {
396 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler skipped since check_user ran");
401 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler(%d): ENTER: %s", (int)getpid(), r->handler);
404 ShibTargetApache sta(r);
406 pair<bool,void*> res = sta.doHandler();
407 if (res.first) return (int)res.second;
409 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "doHandler() did not do anything.");
412 catch (SAMLException& e) {
413 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler threw an exception: %s", e.what());
418 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler threw an uncaught exception!");
425 * shib_auth_checker() -- a simple resource manager to
426 * process the .htaccess settings
428 extern "C" int shib_auth_checker(request_rec* r)
430 // Short-circuit entirely?
431 if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
434 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_auth_checker(%d): ENTER", (int)getpid());
436 ostringstream threadid;
437 threadid << "[" << getpid() << "] shib_auth_checker" << '\0';
438 saml::NDC ndc(threadid.str().c_str());
441 ShibTargetApache sta(r);
443 pair<bool,void*> res = sta.doCheckAuthZ();
444 if (res.first) return (int)res.second;
449 catch (SAMLException& e) {
450 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an exception: %s", e.what());
455 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an uncaught exception!");
461 // Access control plugin that enforces htaccess rules
462 class htAccessControl : virtual public IAccessControl
466 ~htAccessControl() {}
471 ISessionCacheEntry* entry
475 IPlugIn* htAccessFactory(const DOMElement* e)
477 return new htAccessControl();
480 class ApacheRequestMapper : public virtual IRequestMapper, public virtual PropertySet
483 ApacheRequestMapper(const DOMElement* e);
484 ~ApacheRequestMapper() { delete m_mapper; delete m_htaccess; delete m_staKey; delete m_propsKey; }
485 void lock() { m_mapper->lock(); }
486 void unlock() { m_staKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
487 Settings getSettings(ShibTarget* st) const;
489 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
490 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
491 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
492 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
493 pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
494 const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
495 const DOMElement* getElement() const;
498 IRequestMapper* m_mapper;
500 ThreadKey* m_propsKey;
501 IAccessControl* m_htaccess;
504 IPlugIn* ApacheRequestMapFactory(const DOMElement* e)
506 return new ApacheRequestMapper(e);
509 ApacheRequestMapper::ApacheRequestMapper(const DOMElement* e) : m_mapper(NULL), m_staKey(NULL), m_propsKey(NULL), m_htaccess(NULL)
511 IPlugIn* p=SAMLConfig::getConfig().getPlugMgr().newPlugin(shibtarget::XML::XMLRequestMapType,e);
512 m_mapper=dynamic_cast<IRequestMapper*>(p);
515 throw UnsupportedExtensionException("Embedded request mapper plugin was not of correct type.");
517 m_htaccess=new htAccessControl();
518 m_staKey=ThreadKey::create(NULL);
519 m_propsKey=ThreadKey::create(NULL);
522 IRequestMapper::Settings ApacheRequestMapper::getSettings(ShibTarget* st) const
524 Settings s=m_mapper->getSettings(st);
525 m_staKey->setData(dynamic_cast<ShibTargetApache*>(st));
526 m_propsKey->setData((void*)s.first);
527 return pair<const PropertySet*,IAccessControl*>(this,s.second ? s.second : m_htaccess);
530 pair<bool,bool> ApacheRequestMapper::getBool(const char* name, const char* ns) const
532 ShibTargetApache* sta=reinterpret_cast<ShibTargetApache*>(m_staKey->getData());
533 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
535 // Override Apache-settable boolean properties.
536 if (name && !strcmp(name,"requireSession") && sta->m_dc->bRequireSession==1)
537 return make_pair(true,true);
538 else if (name && !strcmp(name,"exportAssertion") && sta->m_dc->bExportAssertion==1)
539 return make_pair(true,true);
541 return s ? s->getBool(name,ns) : make_pair(false,false);
544 pair<bool,const char*> ApacheRequestMapper::getString(const char* name, const char* ns) const
546 ShibTargetApache* sta=reinterpret_cast<ShibTargetApache*>(m_staKey->getData());
547 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
549 // Override Apache-settable string properties.
550 if (name && !strcmp(name,"authType")) {
551 const char *auth_type=ap_auth_type(sta->m_req);
553 // Check for Basic Hijack
554 if (!strcasecmp(auth_type, "basic") && sta->m_dc->bBasicHijack == 1)
555 auth_type = "shibboleth";
556 return make_pair(true,auth_type);
559 else if (name && !strcmp(name,"applicationId") && sta->m_dc->szApplicationId)
560 return pair<bool,const char*>(true,sta->m_dc->szApplicationId);
561 else if (name && !strcmp(name,"requireSessionWith") && sta->m_dc->szRequireWith)
562 return pair<bool,const char*>(true,sta->m_dc->szRequireWith);
563 else if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
564 return pair<bool,const char*>(true,sta->m_dc->szRedirectToSSL);
566 return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
569 pair<bool,const XMLCh*> ApacheRequestMapper::getXMLString(const char* name, const char* ns) const
571 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
572 return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
575 pair<bool,unsigned int> ApacheRequestMapper::getUnsignedInt(const char* name, const char* ns) const
577 ShibTargetApache* sta=reinterpret_cast<ShibTargetApache*>(m_staKey->getData());
578 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
580 // Override Apache-settable int properties.
581 if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
582 return pair<bool,unsigned int>(true,strtol(sta->m_dc->szRedirectToSSL,NULL,10));
584 return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
587 pair<bool,int> ApacheRequestMapper::getInt(const char* name, const char* ns) const
589 ShibTargetApache* sta=reinterpret_cast<ShibTargetApache*>(m_staKey->getData());
590 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
592 // Override Apache-settable int properties.
593 if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
594 return pair<bool,int>(true,atoi(sta->m_dc->szRedirectToSSL));
596 return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
599 const PropertySet* ApacheRequestMapper::getPropertySet(const char* name, const char* ns) const
601 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
602 return s ? s->getPropertySet(name,ns) : NULL;
605 const DOMElement* ApacheRequestMapper::getElement() const
607 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
608 return s ? s->getElement() : NULL;
611 static SH_AP_TABLE* groups_for_user(request_rec* r, const char* user, char* grpfile)
614 SH_AP_TABLE* grps=ap_make_table(r->pool,15);
615 char l[MAX_STRING_LEN];
616 const char *group_name, *ll, *w;
618 #ifdef SHIB_APACHE_13
619 if (!(f=ap_pcfg_openfile(r->pool,grpfile))) {
621 if (ap_pcfg_openfile(&f,r->pool,grpfile) != APR_SUCCESS) {
623 ap_log_rerror(APLOG_MARK,APLOG_DEBUG,SH_AP_R(r),"groups_for_user() could not open group file: %s\n",grpfile);
628 #ifdef SHIB_APACHE_13
629 sp=ap_make_sub_pool(r->pool);
631 if (apr_pool_create(&sp,r->pool) != APR_SUCCESS) {
632 ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,
633 "groups_for_user() could not create a subpool");
638 while (!(ap_cfg_getline(l,MAX_STRING_LEN,f))) {
639 if ((*l=='#') || (!*l))
644 group_name=ap_getword(sp,&ll,':');
647 w=ap_getword_conf(sp,&ll);
648 if (!strcmp(w,user)) {
649 ap_table_setn(grps,ap_pstrdup(r->pool,group_name),"in");
659 bool htAccessControl::authorized(
661 ISessionCacheEntry* entry
664 // Make sure the object is our type.
665 ShibTargetApache* sta=dynamic_cast<ShibTargetApache*>(st);
667 throw ConfigurationException("Request wrapper object was not of correct type.");
671 int m=sta->m_req->method_number;
672 bool method_restricted=false;
675 const array_header* reqs_arr=ap_requires(sta->m_req);
679 require_line* reqs=(require_line*)reqs_arr->elts;
681 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(sta->m_req),"REQUIRE nelts: %d", reqs_arr->nelts);
682 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(sta->m_req),"REQUIRE all: %d", sta->m_dc->bRequireAll);
684 vector<bool> auth_OK(reqs_arr->nelts,false);
686 #define SHIB_AP_CHECK_IS_OK { \
687 if (sta->m_dc->bRequireAll < 1) \
693 for (int x=0; x<reqs_arr->nelts; x++) {
695 if (!(reqs[x].method_mask & (1 << m)))
697 method_restricted=true;
698 string remote_user = st->getRemoteUser();
700 t = reqs[x].requirement;
701 w = ap_getword_white(sta->m_req->pool, &t);
703 if (!strcasecmp(w,"shibboleth")) {
704 // This is a dummy rule needed because Apache conflates authn and authz.
705 // Without some require rule, AuthType is ignored and no check_user hooks run.
708 else if (!strcmp(w,"valid-user")) {
710 st->log(ShibTarget::LogLevelDebug,"htAccessControl plugin accepting valid-user based on active session");
714 st->log(ShibTarget::LogLevelError,"htAccessControl plugin rejecting access for valid-user rule, no session is active");
716 else if (!strcmp(w,"user") && !remote_user.empty()) {
719 w=ap_getword_conf(sta->m_req->pool,&t);
727 // To do regex matching, we have to convert from UTF-8.
728 auto_ptr<XMLCh> trans(fromUTF8(w));
729 RegularExpression re(trans.get());
730 auto_ptr<XMLCh> trans2(fromUTF8(remote_user.c_str()));
731 if (re.matches(trans2.get())) {
732 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin accepting user (") + w + ")");
736 catch (XMLException& ex) {
737 auto_ptr_char tmp(ex.getMessage());
738 st->log(ShibTarget::LogLevelError,
739 string("htAccessControl plugin caught exception while parsing regular expression (") + w + "): " + tmp.get());
742 else if (remote_user==w) {
743 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin accepting user (") + w + ")");
748 else if (!strcmp(w,"group")) {
749 SH_AP_TABLE* grpstatus=NULL;
750 if (sta->m_dc->szAuthGrpFile && !remote_user.empty()) {
751 st->log(ShibTarget::LogLevelDebug,string("htAccessControl plugin using groups file: ") + sta->m_dc->szAuthGrpFile);
752 grpstatus=groups_for_user(sta->m_req,remote_user.c_str(),sta->m_dc->szAuthGrpFile);
758 w=ap_getword_conf(sta->m_req->pool,&t);
759 if (ap_table_get(grpstatus,w)) {
760 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin accepting group (") + w + ")");
766 Iterator<shibboleth::IAAP*> provs=st->getApplication()->getAAPProviders();
767 shibboleth::AAP wrapper(provs,w);
768 if (wrapper.fail()) {
769 st->log(ShibTarget::LogLevelWarn, string("htAccessControl plugin didn't recognize require rule: ") + w);
775 if (!strcmp(wrapper->getHeader(),"REMOTE_USER"))
776 vals=remote_user.c_str();
778 vals=ap_table_get(sta->m_req->headers_in,wrapper->getHeader());
779 while (*t && vals && *vals) {
780 w=ap_getword_conf(sta->m_req->pool,&t);
787 auto_ptr<RegularExpression> re;
790 auto_ptr<XMLCh> trans(fromUTF8(w));
791 auto_ptr<RegularExpression> temp(new RegularExpression(trans.get()));
795 string vals_str(vals);
797 for (unsigned int i = 0; i < vals_str.length(); i++) {
798 if (vals_str.at(i) == ';') {
800 st->log(ShibTarget::LogLevelError, string("htAccessControl plugin found invalid header encoding (") +
801 vals + "): starts with a semicolon");
802 throw SAMLException("Invalid information supplied to authorization plugin.");
805 if (vals_str.at(i-1) == '\\') {
806 vals_str.erase(i-1, 1);
811 string val = vals_str.substr(j, i-j);
814 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
815 if (re->matches(trans.get())) {
816 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
817 ", got " + val + ": authorization granted");
821 else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
822 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
823 ", got " + val + ": authorization granted.");
827 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
828 ", got " + val + ": authoritzation not granted.");
833 string val = vals_str.substr(j, vals_str.length()-j);
835 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
836 if (re->matches(trans.get())) {
837 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
838 ", got " + val + ": authorization granted.");
842 else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
843 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
844 ", got " + val + ": authorization granted");
848 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
849 ", got " + val + ": authorization not granted");
852 catch (XMLException& ex) {
853 auto_ptr_char tmp(ex.getMessage());
854 st->log(ShibTarget::LogLevelError, string("htAccessControl plugin caught exception while parsing regular expression (")
855 + w + "): " + tmp.get());
861 // check if all require directives are true
862 bool auth_all_OK = true;
863 for (int i= 0; i<reqs_arr->nelts; i++) {
864 auth_all_OK &= auth_OK[i];
866 if (auth_all_OK || !method_restricted)
872 #ifndef SHIB_APACHE_13
875 * Empty cleanup hook, Apache 2.x doesn't check NULL very well...
877 extern "C" apr_status_t shib_exit(void* data)
880 g_Config->shutdown();
883 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,0,NULL,"shib_exit() done\n");
891 * Cleanup the (per-process) pool info.
893 #ifdef SHIB_APACHE_13
894 extern "C" void shib_child_exit(server_rec* s, SH_AP_POOL* p)
897 extern "C" apr_status_t shib_child_exit(void* data)
899 server_rec* s = NULL;
902 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit(%d) dealing with g_Config..", (int)getpid());
903 g_Config->shutdown();
905 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit() done\n");
907 #ifndef SHIB_APACHE_13
914 * Things to do when the child process is initialized.
915 * (or after the configs are read in apache-2)
917 #ifdef SHIB_APACHE_13
918 extern "C" void shib_child_init(server_rec* s, SH_AP_POOL* p)
920 extern "C" void shib_child_init(apr_pool_t* p, server_rec* s)
923 // Initialize runtime components.
925 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init(%d) starting", (int)getpid());
928 ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() already initialized!");
933 g_Config=&ShibTargetConfig::getConfig();
934 SPConfig::getConfig().setFeatures(
939 SPConfig::RequestMapper |
940 SPConfig::InProcess |
943 if (!g_Config->init(g_szSchemaDir)) {
944 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize libraries");
947 SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::htAccessControlType,&htAccessFactory);
948 SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::NativeRequestMapType,&ApacheRequestMapFactory);
949 // We hijack the legacy type so that 1.2 config files will load this plugin
950 SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::LegacyRequestMapType,&ApacheRequestMapFactory);
952 if (!g_Config->load(g_szSHIBConfig)) {
953 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to load configuration");
957 IConfig* conf=g_Config->getINI();
959 const PropertySet* props=conf->getPropertySet("Local");
961 pair<bool,const char*> unsetValue=props->getString("unsetHeaderValue");
962 if (unsetValue.first)
963 g_unsetHeaderValue = unsetValue.second;
967 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize system");
971 // Set the cleanup handler
972 apr_pool_cleanup_register(p, NULL, &shib_exit, &shib_child_exit);
974 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() done");
977 typedef const char* (*config_fn_t)(void);
979 #ifdef SHIB_APACHE_13
981 // SHIB Module commands
983 static command_rec shire_cmds[] = {
984 {"ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
985 RSRC_CONF, TAKE1, "Path to shibboleth.xml config file"},
986 {"ShibSchemaDir", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
987 RSRC_CONF, TAKE1, "Path to Shibboleth XML schema directory"},
989 {"ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
990 (void *) XtOffsetOf (shib_server_config, szScheme),
991 RSRC_CONF, TAKE1, "URL scheme to force into generated URLs for a vhost"},
993 {"ShibDisable", (config_fn_t)ap_set_flag_slot,
994 (void *) XtOffsetOf (shib_dir_config, bOff),
995 OR_AUTHCFG, FLAG, "Disable all Shib module activity here to save processing effort"},
996 {"ShibApplicationId", (config_fn_t)ap_set_string_slot,
997 (void *) XtOffsetOf (shib_dir_config, szApplicationId),
998 OR_AUTHCFG, TAKE1, "Set Shibboleth applicationId property for content"},
999 {"ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1000 (void *) XtOffsetOf (shib_dir_config, bBasicHijack),
1001 OR_AUTHCFG, FLAG, "Respond to AuthType Basic and convert to shibboleth"},
1002 {"ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1003 (void *) XtOffsetOf (shib_dir_config, bRequireSession),
1004 OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist"},
1005 {"ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
1006 (void *) XtOffsetOf (shib_dir_config, szRequireWith),
1007 OR_AUTHCFG, TAKE1, "Initiates a new session if one does not exist using a specific SessionInitiator"},
1008 {"ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1009 (void *) XtOffsetOf (shib_dir_config, bExportAssertion),
1010 OR_AUTHCFG, FLAG, "Export SAML attribute assertion(s) to Shib-Attributes header"},
1011 {"ShibRedirectToSSL", (config_fn_t)ap_set_string_slot,
1012 (void *) XtOffsetOf (shib_dir_config, szRedirectToSSL),
1013 OR_AUTHCFG, TAKE1, "Redirect non-SSL requests to designated port" },
1014 {"AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
1015 (void *) XtOffsetOf (shib_dir_config, szAuthGrpFile),
1016 OR_AUTHCFG, TAKE1, "text file containing group names and member user IDs"},
1017 {"ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1018 (void *) XtOffsetOf (shib_dir_config, bRequireAll),
1019 OR_AUTHCFG, FLAG, "All require directives must match"},
1025 handler_rec shib_handlers[] = {
1026 { "shib-handler", shib_handler },
1030 module MODULE_VAR_EXPORT mod_shib = {
1031 STANDARD_MODULE_STUFF,
1032 NULL, /* initializer */
1033 create_shib_dir_config, /* dir config creater */
1034 merge_shib_dir_config, /* dir merger --- default is to override */
1035 create_shib_server_config, /* server config */
1036 merge_shib_server_config, /* merge server config */
1037 shire_cmds, /* command table */
1038 shib_handlers, /* handlers */
1039 NULL, /* filename translation */
1040 shib_check_user, /* check_user_id */
1041 shib_auth_checker, /* check auth */
1042 NULL, /* check access */
1043 NULL, /* type_checker */
1046 NULL, /* header parser */
1047 shib_child_init, /* child_init */
1048 shib_child_exit, /* child_exit */
1049 NULL /* post read-request */
1052 #elif defined(SHIB_APACHE_20) || defined(SHIB_APACHE_22)
1054 extern "C" void shib_register_hooks (apr_pool_t *p)
1056 ap_hook_child_init(shib_child_init, NULL, NULL, APR_HOOK_MIDDLE);
1057 ap_hook_check_user_id(shib_check_user, NULL, NULL, APR_HOOK_MIDDLE);
1058 ap_hook_auth_checker(shib_auth_checker, NULL, NULL, APR_HOOK_FIRST);
1059 ap_hook_handler(shib_handler, NULL, NULL, APR_HOOK_LAST);
1062 // SHIB Module commands
1065 static command_rec shib_cmds[] = {
1066 AP_INIT_TAKE1("ShibConfig",
1067 (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1068 RSRC_CONF, "Path to shibboleth.xml config file"),
1069 AP_INIT_TAKE1("ShibSchemaDir",
1070 (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1071 RSRC_CONF, "Path to Shibboleth XML schema directory"),
1073 AP_INIT_TAKE1("ShibURLScheme",
1074 (config_fn_t)shib_set_server_string_slot,
1075 (void *) offsetof (shib_server_config, szScheme),
1076 RSRC_CONF, "URL scheme to force into generated URLs for a vhost"),
1078 AP_INIT_FLAG("ShibDisable", (config_fn_t)ap_set_flag_slot,
1079 (void *) offsetof (shib_dir_config, bOff),
1080 OR_AUTHCFG, "Disable all Shib module activity here to save processing effort"),
1081 AP_INIT_TAKE1("ShibApplicationId", (config_fn_t)ap_set_string_slot,
1082 (void *) offsetof (shib_dir_config, szApplicationId),
1083 OR_AUTHCFG, "Set Shibboleth applicationId property for content"),
1084 AP_INIT_FLAG("ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1085 (void *) offsetof (shib_dir_config, bBasicHijack),
1086 OR_AUTHCFG, "Respond to AuthType Basic and convert to shibboleth"),
1087 AP_INIT_FLAG("ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1088 (void *) offsetof (shib_dir_config, bRequireSession),
1089 OR_AUTHCFG, "Initiates a new session if one does not exist"),
1090 AP_INIT_TAKE1("ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
1091 (void *) offsetof (shib_dir_config, szRequireWith),
1092 OR_AUTHCFG, "Initiates a new session if one does not exist using a specific SessionInitiator"),
1093 AP_INIT_FLAG("ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1094 (void *) offsetof (shib_dir_config, bExportAssertion),
1095 OR_AUTHCFG, "Export SAML attribute assertion(s) to Shib-Attributes header"),
1096 AP_INIT_TAKE1("ShibRedirectToSSL", (config_fn_t)ap_set_string_slot,
1097 (void *) offsetof (shib_dir_config, szRedirectToSSL),
1098 OR_AUTHCFG, "Redirect non-SSL requests to designated port"),
1099 AP_INIT_TAKE1("AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
1100 (void *) offsetof (shib_dir_config, szAuthGrpFile),
1101 OR_AUTHCFG, "Text file containing group names and member user IDs"),
1102 AP_INIT_FLAG("ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1103 (void *) offsetof (shib_dir_config, bRequireAll),
1104 OR_AUTHCFG, "All require directives must match"),
1109 module AP_MODULE_DECLARE_DATA mod_shib = {
1110 STANDARD20_MODULE_STUFF,
1111 create_shib_dir_config, /* create dir config */
1112 merge_shib_dir_config, /* merge dir config --- default is to override */
1113 create_shib_server_config, /* create server config */
1114 merge_shib_server_config, /* merge server config */
1115 shib_cmds, /* command table */
1116 shib_register_hooks /* register hooks */
1120 #error "undefined APACHE version"