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
34 #include <shibsp/exceptions.h>
35 #include <shibsp/SPConfig.h>
38 #include <saml/saml.h>
39 #include <shib/shib.h>
40 #include <shib-target/shib-target.h>
41 #include <xercesc/util/regx/RegularExpression.hpp>
49 // Apache specific header files
51 #include <http_config.h>
52 #include <http_protocol.h>
53 #include <http_main.h>
55 #include <http_core.h>
58 #ifndef SHIB_APACHE_13
59 #include <http_request.h>
60 #include <apr_strings.h>
61 #include <apr_pools.h>
68 #include <unistd.h> // for getpid()
71 using namespace shibsp;
72 using namespace shibtarget;
73 using namespace xmltooling;
76 extern "C" module MODULE_VAR_EXPORT mod_shib;
79 char* g_szSHIBConfig = NULL;
80 char* g_szSchemaDir = NULL;
81 ShibTargetConfig* g_Config = NULL;
82 string g_unsetHeaderValue;
83 static const char* g_UserDataKey = "_shib_check_user_";
86 /********************************************************************************/
87 // Basic Apache Configuration code.
90 // per-server module configuration structure
91 struct shib_server_config
96 // creates the per-server configuration
97 extern "C" void* create_shib_server_config(SH_AP_POOL* p, server_rec* s)
99 shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
104 // overrides server configuration in virtual servers
105 extern "C" void* merge_shib_server_config (SH_AP_POOL* p, void* base, void* sub)
107 shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
108 shib_server_config* parent=(shib_server_config*)base;
109 shib_server_config* child=(shib_server_config*)sub;
112 sc->szScheme=ap_pstrdup(p,child->szScheme);
113 else if (parent->szScheme)
114 sc->szScheme=ap_pstrdup(p,parent->szScheme);
121 // per-dir module configuration structure
122 struct shib_dir_config
125 char* szAuthGrpFile; // Auth GroupFile name
126 int bRequireAll; // all require directives must match, otherwise OR logic
128 // Content Configuration
129 char* szApplicationId; // Shib applicationId value
130 char* szRequireWith; // require a session using a specific initiator?
131 char* szRedirectToSSL; // redirect non-SSL requests to SSL port
132 int bOff; // flat-out disable all Shib processing
133 int bBasicHijack; // activate for AuthType Basic?
134 int bRequireSession; // require a session?
135 int bExportAssertion; // export SAML assertion to the environment?
138 // creates per-directory config structure
139 extern "C" void* create_shib_dir_config (SH_AP_POOL* p, char* d)
141 shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
143 dc->bBasicHijack = -1;
144 dc->bRequireSession = -1;
145 dc->bExportAssertion = -1;
146 dc->bRequireAll = -1;
147 dc->szRedirectToSSL = NULL;
148 dc->szAuthGrpFile = NULL;
149 dc->szApplicationId = NULL;
150 dc->szRequireWith = NULL;
154 // overrides server configuration in directories
155 extern "C" void* merge_shib_dir_config (SH_AP_POOL* p, void* base, void* sub)
157 shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
158 shib_dir_config* parent=(shib_dir_config*)base;
159 shib_dir_config* child=(shib_dir_config*)sub;
161 if (child->szAuthGrpFile)
162 dc->szAuthGrpFile=ap_pstrdup(p,child->szAuthGrpFile);
163 else if (parent->szAuthGrpFile)
164 dc->szAuthGrpFile=ap_pstrdup(p,parent->szAuthGrpFile);
166 dc->szAuthGrpFile=NULL;
168 if (child->szApplicationId)
169 dc->szApplicationId=ap_pstrdup(p,child->szApplicationId);
170 else if (parent->szApplicationId)
171 dc->szApplicationId=ap_pstrdup(p,parent->szApplicationId);
173 dc->szApplicationId=NULL;
175 if (child->szRequireWith)
176 dc->szRequireWith=ap_pstrdup(p,child->szRequireWith);
177 else if (parent->szRequireWith)
178 dc->szRequireWith=ap_pstrdup(p,parent->szRequireWith);
180 dc->szRequireWith=NULL;
182 if (child->szRedirectToSSL)
183 dc->szRedirectToSSL=ap_pstrdup(p,child->szRedirectToSSL);
184 else if (parent->szRedirectToSSL)
185 dc->szRedirectToSSL=ap_pstrdup(p,parent->szRedirectToSSL);
187 dc->szRedirectToSSL=NULL;
189 dc->bOff=((child->bOff==-1) ? parent->bOff : child->bOff);
190 dc->bBasicHijack=((child->bBasicHijack==-1) ? parent->bBasicHijack : child->bBasicHijack);
191 dc->bRequireSession=((child->bRequireSession==-1) ? parent->bRequireSession : child->bRequireSession);
192 dc->bExportAssertion=((child->bExportAssertion==-1) ? parent->bExportAssertion : child->bExportAssertion);
193 dc->bRequireAll=((child->bRequireAll==-1) ? parent->bRequireAll : child->bRequireAll);
197 // generic global slot handlers
198 extern "C" const char* ap_set_global_string_slot(cmd_parms* parms, void*, const char* arg)
200 *((char**)(parms->info))=ap_pstrdup(parms->pool,arg);
204 extern "C" const char* shib_set_server_string_slot(cmd_parms* parms, void*, const char* arg)
206 char* base=(char*)ap_get_module_config(parms->server->module_config,&mod_shib);
207 size_t offset=(size_t)parms->info;
208 *((char**)(base + offset))=ap_pstrdup(parms->pool,arg);
212 extern "C" const char* shib_ap_set_file_slot(cmd_parms* parms,
213 #ifdef SHIB_APACHE_13
214 char* arg1, char* arg2
216 void* arg1, const char* arg2
220 ap_set_file_slot(parms, arg1, arg2);
224 /********************************************************************************/
225 // Apache ShibTarget subclass(es) here.
227 class ShibTargetApache : public ShibTarget
229 mutable string m_body;
230 mutable bool m_gotBody;
234 shib_dir_config* m_dc;
235 shib_server_config* m_sc;
237 ShibTargetApache(request_rec* req) : m_gotBody(false) {
238 m_sc = (shib_server_config*)ap_get_module_config(req->server->module_config, &mod_shib);
239 m_dc = (shib_dir_config*)ap_get_module_config(req->per_dir_config, &mod_shib);
242 m_sc->szScheme ? m_sc->szScheme : ap_http_method(req),
243 ap_get_server_name(req),
244 (int)ap_get_server_port(req),
246 ap_table_get(req->headers_in, "Content-type"),
247 req->connection->remote_ip,
253 virtual ~ShibTargetApache() {}
255 virtual void log(ShibLogLevel level, const string &msg) {
256 ShibTarget::log(level,msg);
257 #ifdef SHIB_APACHE_13
258 ap_log_rerror(APLOG_MARK,
259 (level == LogLevelDebug ? APLOG_DEBUG :
260 (level == LogLevelInfo ? APLOG_INFO :
261 (level == LogLevelWarn ? APLOG_WARNING : APLOG_ERR)))|APLOG_NOERRNO, SH_AP_R(m_req), msg.c_str());
263 if (level == LogLevelError)
264 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(m_req), msg.c_str());
267 virtual string getCookies(void) const {
268 const char *c = ap_table_get(m_req->headers_in, "Cookie");
269 return string(c ? c : "");
271 virtual void setCookie(const string &name, const string &value) {
272 char* val = ap_psprintf(m_req->pool, "%s=%s", name.c_str(), value.c_str());
273 ap_table_addn(m_req->err_headers_out, "Set-Cookie", val);
275 virtual const char* getQueryString() const { return m_req->args; }
276 virtual const char* getRequestBody() const {
278 return m_body.c_str();
279 // Read the posted data
280 if (ap_setup_client_block(m_req, REQUEST_CHUNKED_ERROR))
281 throw saml::SAMLException("Apache function (setup_client_block) failed while reading POST request body.");
282 if (!ap_should_client_block(m_req))
283 throw saml::SAMLException("Apache function (should_client_block) failed while reading POST request body.");
284 if (m_req->remaining > 1024*1024)
285 throw saml::SAMLException("Blocked POST request body larger than size limit.");
287 char buff[HUGE_STRING_LEN];
288 ap_hard_timeout("[mod_shib] getRequestBody", m_req);
289 memset(buff, 0, sizeof(buff));
290 while (ap_get_client_block(m_req, buff, sizeof(buff)-1) > 0) {
291 ap_reset_timeout(m_req);
293 memset(buff, 0, sizeof(buff));
295 ap_kill_timeout(m_req);
296 return m_body.c_str();
298 virtual void clearHeader(const string &name) {
299 ap_table_unset(m_req->headers_in, name.c_str());
300 ap_table_set(m_req->headers_in, name.c_str(), g_unsetHeaderValue.c_str());
302 virtual void setHeader(const string &name, const string &value) {
303 ap_table_set(m_req->headers_in, name.c_str(), value.c_str());
305 virtual string getHeader(const string &name) {
306 const char *hdr = ap_table_get(m_req->headers_in, name.c_str());
307 return string(hdr ? hdr : "");
309 virtual void setRemoteUser(const string &user) {
310 SH_AP_USER(m_req) = ap_pstrdup(m_req->pool, user.c_str());
312 virtual string getRemoteUser(void) {
313 return string(SH_AP_USER(m_req) ? SH_AP_USER(m_req) : "");
315 virtual void* sendPage(
318 const string& content_type="text/html",
319 const saml::Iterator<header_t>& headers=EMPTY(header_t)
321 m_req->content_type = ap_psprintf(m_req->pool, content_type.c_str());
322 while (headers.hasNext()) {
323 const header_t& h=headers.next();
324 ap_table_set(m_req->headers_out, h.first.c_str(), h.second.c_str());
326 ap_send_http_header(m_req);
327 ap_rprintf(m_req, msg.c_str());
328 return (void*)((code==200) ? DONE : code);
330 virtual void* sendRedirect(const string& url) {
331 ap_table_set(m_req->headers_out, "Location", url.c_str());
332 return (void*)REDIRECT;
334 virtual void* returnDecline(void) { return (void*)DECLINED; }
335 virtual void* returnOK(void) { return (void*)OK; }
338 /********************************************************************************/
341 extern "C" int shib_check_user(request_rec* r)
343 // Short-circuit entirely?
344 if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
347 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_check_user(%d): ENTER\n", (int)getpid());
349 ostringstream threadid;
350 threadid << "[" << getpid() << "] shib_check_user" << '\0';
351 saml::NDC ndc(threadid.str().c_str());
354 ShibTargetApache sta(r);
356 // Check user authentication and export information, then set the handler bypass
357 pair<bool,void*> res = sta.doCheckAuthN(true);
358 apr_pool_userdata_setn((const void*)42,g_UserDataKey,NULL,r->pool);
359 if (res.first) return (int)res.second;
361 // user auth was okay -- export the assertions now
362 res = sta.doExportAssertions();
363 if (res.first) return (int)res.second;
365 // export happened successfully.. this user is ok.
368 catch (saml::SAMLException& e) {
369 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user threw an exception: %s", e.what());
374 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user threw an uncaught exception!");
380 extern "C" int shib_handler(request_rec* r)
382 // Short-circuit entirely?
383 if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
386 ostringstream threadid;
387 threadid << "[" << getpid() << "] shib_handler" << '\0';
388 saml::NDC ndc(threadid.str().c_str());
390 #ifndef SHIB_APACHE_13
391 // With 2.x, this handler always runs, though last.
392 // We check if shib_check_user ran, because it will detect a handler request
393 // and dispatch it directly.
395 apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
396 if (data==(const void*)42) {
397 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler skipped since check_user ran");
402 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler(%d): ENTER: %s", (int)getpid(), r->handler);
405 ShibTargetApache sta(r);
407 pair<bool,void*> res = sta.doHandler();
408 if (res.first) return (int)res.second;
410 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "doHandler() did not do anything.");
413 catch (saml::SAMLException& e) {
414 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler threw an exception: %s", e.what());
419 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler threw an uncaught exception!");
426 * shib_auth_checker() -- a simple resource manager to
427 * process the .htaccess settings
429 extern "C" int shib_auth_checker(request_rec* r)
431 // Short-circuit entirely?
432 if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
435 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_auth_checker(%d): ENTER", (int)getpid());
437 ostringstream threadid;
438 threadid << "[" << getpid() << "] shib_auth_checker" << '\0';
439 saml::NDC ndc(threadid.str().c_str());
442 ShibTargetApache sta(r);
444 pair<bool,void*> res = sta.doCheckAuthZ();
445 if (res.first) return (int)res.second;
450 catch (saml::SAMLException& e) {
451 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an exception: %s", e.what());
456 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an uncaught exception!");
462 // Access control plugin that enforces htaccess rules
463 class htAccessControl : virtual public IAccessControl
467 ~htAccessControl() {}
472 ISessionCacheEntry* entry
476 saml::IPlugIn* htAccessFactory(const DOMElement* e)
478 return new htAccessControl();
481 class ApacheRequestMapper : public virtual IRequestMapper, public virtual PropertySet
484 ApacheRequestMapper(const DOMElement* e);
485 ~ApacheRequestMapper() { delete m_mapper; delete m_htaccess; delete m_staKey; delete m_propsKey; }
486 void lock() { m_mapper->lock(); }
487 void unlock() { m_staKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
488 Settings getSettings(ShibTarget* st) const;
490 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
491 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
492 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
493 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
494 pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
495 const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
496 const DOMElement* getElement() const;
499 IRequestMapper* m_mapper;
501 ThreadKey* m_propsKey;
502 IAccessControl* m_htaccess;
505 saml::IPlugIn* ApacheRequestMapFactory(const DOMElement* e)
507 return new ApacheRequestMapper(e);
510 ApacheRequestMapper::ApacheRequestMapper(const DOMElement* e) : m_mapper(NULL), m_staKey(NULL), m_propsKey(NULL), m_htaccess(NULL)
512 saml::IPlugIn* p=saml::SAMLConfig::getConfig().getPlugMgr().newPlugin(shibtarget::XML::XMLRequestMapType,e);
513 m_mapper=dynamic_cast<IRequestMapper*>(p);
516 throw saml::UnsupportedExtensionException("Embedded request mapper plugin was not of correct type.");
518 m_htaccess=new htAccessControl();
519 m_staKey=ThreadKey::create(NULL);
520 m_propsKey=ThreadKey::create(NULL);
523 IRequestMapper::Settings ApacheRequestMapper::getSettings(ShibTarget* st) const
525 Settings s=m_mapper->getSettings(st);
526 m_staKey->setData(dynamic_cast<ShibTargetApache*>(st));
527 m_propsKey->setData((void*)s.first);
528 return pair<const PropertySet*,IAccessControl*>(this,s.second ? s.second : m_htaccess);
531 pair<bool,bool> ApacheRequestMapper::getBool(const char* name, const char* ns) const
533 ShibTargetApache* sta=reinterpret_cast<ShibTargetApache*>(m_staKey->getData());
534 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
536 // Override Apache-settable boolean properties.
537 if (name && !strcmp(name,"requireSession") && sta->m_dc->bRequireSession==1)
538 return make_pair(true,true);
539 else if (name && !strcmp(name,"exportAssertion") && sta->m_dc->bExportAssertion==1)
540 return make_pair(true,true);
542 return s ? s->getBool(name,ns) : make_pair(false,false);
545 pair<bool,const char*> ApacheRequestMapper::getString(const char* name, const char* ns) const
547 ShibTargetApache* sta=reinterpret_cast<ShibTargetApache*>(m_staKey->getData());
548 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
550 // Override Apache-settable string properties.
551 if (name && !strcmp(name,"authType")) {
552 const char *auth_type=ap_auth_type(sta->m_req);
554 // Check for Basic Hijack
555 if (!strcasecmp(auth_type, "basic") && sta->m_dc->bBasicHijack == 1)
556 auth_type = "shibboleth";
557 return make_pair(true,auth_type);
560 else if (name && !strcmp(name,"applicationId") && sta->m_dc->szApplicationId)
561 return pair<bool,const char*>(true,sta->m_dc->szApplicationId);
562 else if (name && !strcmp(name,"requireSessionWith") && sta->m_dc->szRequireWith)
563 return pair<bool,const char*>(true,sta->m_dc->szRequireWith);
564 else if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
565 return pair<bool,const char*>(true,sta->m_dc->szRedirectToSSL);
567 return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
570 pair<bool,const XMLCh*> ApacheRequestMapper::getXMLString(const char* name, const char* ns) const
572 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
573 return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
576 pair<bool,unsigned int> ApacheRequestMapper::getUnsignedInt(const char* name, const char* ns) const
578 ShibTargetApache* sta=reinterpret_cast<ShibTargetApache*>(m_staKey->getData());
579 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
581 // Override Apache-settable int properties.
582 if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
583 return pair<bool,unsigned int>(true,strtol(sta->m_dc->szRedirectToSSL,NULL,10));
585 return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
588 pair<bool,int> ApacheRequestMapper::getInt(const char* name, const char* ns) const
590 ShibTargetApache* sta=reinterpret_cast<ShibTargetApache*>(m_staKey->getData());
591 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
593 // Override Apache-settable int properties.
594 if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
595 return pair<bool,int>(true,atoi(sta->m_dc->szRedirectToSSL));
597 return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
600 const PropertySet* ApacheRequestMapper::getPropertySet(const char* name, const char* ns) const
602 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
603 return s ? s->getPropertySet(name,ns) : NULL;
606 const DOMElement* ApacheRequestMapper::getElement() const
608 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
609 return s ? s->getElement() : NULL;
612 static SH_AP_TABLE* groups_for_user(request_rec* r, const char* user, char* grpfile)
615 SH_AP_TABLE* grps=ap_make_table(r->pool,15);
616 char l[MAX_STRING_LEN];
617 const char *group_name, *ll, *w;
619 #ifdef SHIB_APACHE_13
620 if (!(f=ap_pcfg_openfile(r->pool,grpfile))) {
622 if (ap_pcfg_openfile(&f,r->pool,grpfile) != APR_SUCCESS) {
624 ap_log_rerror(APLOG_MARK,APLOG_DEBUG,SH_AP_R(r),"groups_for_user() could not open group file: %s\n",grpfile);
629 #ifdef SHIB_APACHE_13
630 sp=ap_make_sub_pool(r->pool);
632 if (apr_pool_create(&sp,r->pool) != APR_SUCCESS) {
633 ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,
634 "groups_for_user() could not create a subpool");
639 while (!(ap_cfg_getline(l,MAX_STRING_LEN,f))) {
640 if ((*l=='#') || (!*l))
645 group_name=ap_getword(sp,&ll,':');
648 w=ap_getword_conf(sp,&ll);
649 if (!strcmp(w,user)) {
650 ap_table_setn(grps,ap_pstrdup(r->pool,group_name),"in");
660 bool htAccessControl::authorized(
662 ISessionCacheEntry* entry
665 // Make sure the object is our type.
666 ShibTargetApache* sta=dynamic_cast<ShibTargetApache*>(st);
668 throw ConfigurationException("Request wrapper object was not of correct type.");
672 int m=sta->m_req->method_number;
673 bool method_restricted=false;
676 const array_header* reqs_arr=ap_requires(sta->m_req);
680 require_line* reqs=(require_line*)reqs_arr->elts;
682 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(sta->m_req),"REQUIRE nelts: %d", reqs_arr->nelts);
683 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(sta->m_req),"REQUIRE all: %d", sta->m_dc->bRequireAll);
685 vector<bool> auth_OK(reqs_arr->nelts,false);
687 #define SHIB_AP_CHECK_IS_OK { \
688 if (sta->m_dc->bRequireAll < 1) \
694 for (int x=0; x<reqs_arr->nelts; x++) {
696 if (!(reqs[x].method_mask & (1 << m)))
698 method_restricted=true;
699 string remote_user = st->getRemoteUser();
701 t = reqs[x].requirement;
702 w = ap_getword_white(sta->m_req->pool, &t);
704 if (!strcasecmp(w,"shibboleth")) {
705 // This is a dummy rule needed because Apache conflates authn and authz.
706 // Without some require rule, AuthType is ignored and no check_user hooks run.
709 else if (!strcmp(w,"valid-user")) {
711 st->log(ShibTarget::LogLevelDebug,"htAccessControl plugin accepting valid-user based on active session");
715 st->log(ShibTarget::LogLevelError,"htAccessControl plugin rejecting access for valid-user rule, no session is active");
717 else if (!strcmp(w,"user") && !remote_user.empty()) {
720 w=ap_getword_conf(sta->m_req->pool,&t);
728 // To do regex matching, we have to convert from UTF-8.
729 auto_ptr<XMLCh> trans(fromUTF8(w));
730 RegularExpression re(trans.get());
731 auto_ptr<XMLCh> trans2(fromUTF8(remote_user.c_str()));
732 if (re.matches(trans2.get())) {
733 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin accepting user (") + w + ")");
737 catch (XMLException& ex) {
738 auto_ptr_char tmp(ex.getMessage());
739 st->log(ShibTarget::LogLevelError,
740 string("htAccessControl plugin caught exception while parsing regular expression (") + w + "): " + tmp.get());
743 else if (remote_user==w) {
744 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin accepting user (") + w + ")");
749 else if (!strcmp(w,"group")) {
750 SH_AP_TABLE* grpstatus=NULL;
751 if (sta->m_dc->szAuthGrpFile && !remote_user.empty()) {
752 st->log(ShibTarget::LogLevelDebug,string("htAccessControl plugin using groups file: ") + sta->m_dc->szAuthGrpFile);
753 grpstatus=groups_for_user(sta->m_req,remote_user.c_str(),sta->m_dc->szAuthGrpFile);
759 w=ap_getword_conf(sta->m_req->pool,&t);
760 if (ap_table_get(grpstatus,w)) {
761 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin accepting group (") + w + ")");
767 saml::Iterator<shibboleth::IAAP*> provs=st->getApplication()->getAAPProviders();
768 shibboleth::AAP wrapper(provs,w);
769 if (wrapper.fail()) {
770 st->log(ShibTarget::LogLevelWarn, string("htAccessControl plugin didn't recognize require rule: ") + w);
776 if (!strcmp(wrapper->getHeader(),"REMOTE_USER"))
777 vals=remote_user.c_str();
779 vals=ap_table_get(sta->m_req->headers_in,wrapper->getHeader());
780 while (*t && vals && *vals) {
781 w=ap_getword_conf(sta->m_req->pool,&t);
788 auto_ptr<RegularExpression> re;
791 auto_ptr<XMLCh> trans(fromUTF8(w));
792 auto_ptr<RegularExpression> temp(new RegularExpression(trans.get()));
796 string vals_str(vals);
798 for (unsigned int i = 0; i < vals_str.length(); i++) {
799 if (vals_str.at(i) == ';') {
801 st->log(ShibTarget::LogLevelError, string("htAccessControl plugin found invalid header encoding (") +
802 vals + "): starts with a semicolon");
803 throw saml::SAMLException("Invalid information supplied to authorization plugin.");
806 if (vals_str.at(i-1) == '\\') {
807 vals_str.erase(i-1, 1);
812 string val = vals_str.substr(j, i-j);
815 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
816 if (re->matches(trans.get())) {
817 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
818 ", got " + val + ": authorization granted");
822 else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
823 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
824 ", got " + val + ": authorization granted.");
828 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
829 ", got " + val + ": authoritzation not granted.");
834 string val = vals_str.substr(j, vals_str.length()-j);
836 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
837 if (re->matches(trans.get())) {
838 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
839 ", got " + val + ": authorization granted.");
843 else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
844 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
845 ", got " + val + ": authorization granted");
849 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
850 ", got " + val + ": authorization not granted");
853 catch (XMLException& ex) {
854 auto_ptr_char tmp(ex.getMessage());
855 st->log(ShibTarget::LogLevelError, string("htAccessControl plugin caught exception while parsing regular expression (")
856 + w + "): " + tmp.get());
862 // check if all require directives are true
863 bool auth_all_OK = true;
864 for (int i= 0; i<reqs_arr->nelts; i++) {
865 auth_all_OK &= auth_OK[i];
867 if (auth_all_OK || !method_restricted)
873 #ifndef SHIB_APACHE_13
876 * Empty cleanup hook, Apache 2.x doesn't check NULL very well...
878 extern "C" apr_status_t shib_exit(void* data)
881 g_Config->shutdown();
884 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,0,NULL,"shib_exit() done\n");
892 * Cleanup the (per-process) pool info.
894 #ifdef SHIB_APACHE_13
895 extern "C" void shib_child_exit(server_rec* s, SH_AP_POOL* p)
898 extern "C" apr_status_t shib_child_exit(void* data)
900 server_rec* s = NULL;
903 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit(%d) dealing with g_Config..", (int)getpid());
904 g_Config->shutdown();
906 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit() done\n");
908 #ifndef SHIB_APACHE_13
915 * Things to do when the child process is initialized.
916 * (or after the configs are read in apache-2)
918 #ifdef SHIB_APACHE_13
919 extern "C" void shib_child_init(server_rec* s, SH_AP_POOL* p)
921 extern "C" void shib_child_init(apr_pool_t* p, server_rec* s)
924 // Initialize runtime components.
926 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init(%d) starting", (int)getpid());
929 ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() already initialized!");
934 g_Config=&ShibTargetConfig::getConfig();
935 SPConfig::getConfig().setFeatures(
940 SPConfig::RequestMapper |
941 SPConfig::InProcess |
944 if (!g_Config->init(g_szSchemaDir)) {
945 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize libraries");
948 saml::SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::htAccessControlType,&htAccessFactory);
949 saml::SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::NativeRequestMapType,&ApacheRequestMapFactory);
950 // We hijack the legacy type so that 1.2 config files will load this plugin
951 saml::SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::LegacyRequestMapType,&ApacheRequestMapFactory);
953 if (!g_Config->load(g_szSHIBConfig)) {
954 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to load configuration");
958 IConfig* conf=g_Config->getINI();
959 saml::Locker locker(conf);
960 const PropertySet* props=conf->getPropertySet("Local");
962 pair<bool,const char*> unsetValue=props->getString("unsetHeaderValue");
963 if (unsetValue.first)
964 g_unsetHeaderValue = unsetValue.second;
968 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize system");
972 // Set the cleanup handler
973 apr_pool_cleanup_register(p, NULL, &shib_exit, &shib_child_exit);
975 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() done");
978 typedef const char* (*config_fn_t)(void);
980 #ifdef SHIB_APACHE_13
982 // SHIB Module commands
984 static command_rec shire_cmds[] = {
985 {"ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
986 RSRC_CONF, TAKE1, "Path to shibboleth.xml config file"},
987 {"ShibSchemaDir", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
988 RSRC_CONF, TAKE1, "Path to Shibboleth XML schema directory"},
990 {"ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
991 (void *) XtOffsetOf (shib_server_config, szScheme),
992 RSRC_CONF, TAKE1, "URL scheme to force into generated URLs for a vhost"},
994 {"ShibDisable", (config_fn_t)ap_set_flag_slot,
995 (void *) XtOffsetOf (shib_dir_config, bOff),
996 OR_AUTHCFG, FLAG, "Disable all Shib module activity here to save processing effort"},
997 {"ShibApplicationId", (config_fn_t)ap_set_string_slot,
998 (void *) XtOffsetOf (shib_dir_config, szApplicationId),
999 OR_AUTHCFG, TAKE1, "Set Shibboleth applicationId property for content"},
1000 {"ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1001 (void *) XtOffsetOf (shib_dir_config, bBasicHijack),
1002 OR_AUTHCFG, FLAG, "Respond to AuthType Basic and convert to shibboleth"},
1003 {"ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1004 (void *) XtOffsetOf (shib_dir_config, bRequireSession),
1005 OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist"},
1006 {"ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
1007 (void *) XtOffsetOf (shib_dir_config, szRequireWith),
1008 OR_AUTHCFG, TAKE1, "Initiates a new session if one does not exist using a specific SessionInitiator"},
1009 {"ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1010 (void *) XtOffsetOf (shib_dir_config, bExportAssertion),
1011 OR_AUTHCFG, FLAG, "Export SAML attribute assertion(s) to Shib-Attributes header"},
1012 {"ShibRedirectToSSL", (config_fn_t)ap_set_string_slot,
1013 (void *) XtOffsetOf (shib_dir_config, szRedirectToSSL),
1014 OR_AUTHCFG, TAKE1, "Redirect non-SSL requests to designated port" },
1015 {"AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
1016 (void *) XtOffsetOf (shib_dir_config, szAuthGrpFile),
1017 OR_AUTHCFG, TAKE1, "text file containing group names and member user IDs"},
1018 {"ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1019 (void *) XtOffsetOf (shib_dir_config, bRequireAll),
1020 OR_AUTHCFG, FLAG, "All require directives must match"},
1026 handler_rec shib_handlers[] = {
1027 { "shib-handler", shib_handler },
1031 module MODULE_VAR_EXPORT mod_shib = {
1032 STANDARD_MODULE_STUFF,
1033 NULL, /* initializer */
1034 create_shib_dir_config, /* dir config creater */
1035 merge_shib_dir_config, /* dir merger --- default is to override */
1036 create_shib_server_config, /* server config */
1037 merge_shib_server_config, /* merge server config */
1038 shire_cmds, /* command table */
1039 shib_handlers, /* handlers */
1040 NULL, /* filename translation */
1041 shib_check_user, /* check_user_id */
1042 shib_auth_checker, /* check auth */
1043 NULL, /* check access */
1044 NULL, /* type_checker */
1047 NULL, /* header parser */
1048 shib_child_init, /* child_init */
1049 shib_child_exit, /* child_exit */
1050 NULL /* post read-request */
1053 #elif defined(SHIB_APACHE_20) || defined(SHIB_APACHE_22)
1055 extern "C" void shib_register_hooks (apr_pool_t *p)
1057 ap_hook_child_init(shib_child_init, NULL, NULL, APR_HOOK_MIDDLE);
1058 ap_hook_check_user_id(shib_check_user, NULL, NULL, APR_HOOK_MIDDLE);
1059 ap_hook_auth_checker(shib_auth_checker, NULL, NULL, APR_HOOK_FIRST);
1060 ap_hook_handler(shib_handler, NULL, NULL, APR_HOOK_LAST);
1063 // SHIB Module commands
1066 static command_rec shib_cmds[] = {
1067 AP_INIT_TAKE1("ShibConfig",
1068 (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1069 RSRC_CONF, "Path to shibboleth.xml config file"),
1070 AP_INIT_TAKE1("ShibSchemaDir",
1071 (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1072 RSRC_CONF, "Path to Shibboleth XML schema directory"),
1074 AP_INIT_TAKE1("ShibURLScheme",
1075 (config_fn_t)shib_set_server_string_slot,
1076 (void *) offsetof (shib_server_config, szScheme),
1077 RSRC_CONF, "URL scheme to force into generated URLs for a vhost"),
1079 AP_INIT_FLAG("ShibDisable", (config_fn_t)ap_set_flag_slot,
1080 (void *) offsetof (shib_dir_config, bOff),
1081 OR_AUTHCFG, "Disable all Shib module activity here to save processing effort"),
1082 AP_INIT_TAKE1("ShibApplicationId", (config_fn_t)ap_set_string_slot,
1083 (void *) offsetof (shib_dir_config, szApplicationId),
1084 OR_AUTHCFG, "Set Shibboleth applicationId property for content"),
1085 AP_INIT_FLAG("ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1086 (void *) offsetof (shib_dir_config, bBasicHijack),
1087 OR_AUTHCFG, "Respond to AuthType Basic and convert to shibboleth"),
1088 AP_INIT_FLAG("ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1089 (void *) offsetof (shib_dir_config, bRequireSession),
1090 OR_AUTHCFG, "Initiates a new session if one does not exist"),
1091 AP_INIT_TAKE1("ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
1092 (void *) offsetof (shib_dir_config, szRequireWith),
1093 OR_AUTHCFG, "Initiates a new session if one does not exist using a specific SessionInitiator"),
1094 AP_INIT_FLAG("ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1095 (void *) offsetof (shib_dir_config, bExportAssertion),
1096 OR_AUTHCFG, "Export SAML attribute assertion(s) to Shib-Attributes header"),
1097 AP_INIT_TAKE1("ShibRedirectToSSL", (config_fn_t)ap_set_string_slot,
1098 (void *) offsetof (shib_dir_config, szRedirectToSSL),
1099 OR_AUTHCFG, "Redirect non-SSL requests to designated port"),
1100 AP_INIT_TAKE1("AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
1101 (void *) offsetof (shib_dir_config, szAuthGrpFile),
1102 OR_AUTHCFG, "Text file containing group names and member user IDs"),
1103 AP_INIT_FLAG("ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1104 (void *) offsetof (shib_dir_config, bRequireAll),
1105 OR_AUTHCFG, "All require directives must match"),
1110 module AP_MODULE_DECLARE_DATA mod_shib = {
1111 STANDARD20_MODULE_STUFF,
1112 create_shib_dir_config, /* create dir config */
1113 merge_shib_dir_config, /* merge dir config --- default is to override */
1114 create_shib_server_config, /* create server config */
1115 merge_shib_server_config, /* merge server config */
1116 shib_cmds, /* command table */
1117 shib_register_hooks /* register hooks */
1121 #error "undefined APACHE version"