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;
71 using namespace xmltooling;
74 extern "C" module MODULE_VAR_EXPORT mod_shib;
77 char* g_szSHIBConfig = NULL;
78 char* g_szSchemaDir = NULL;
79 ShibTargetConfig* g_Config = NULL;
80 string g_unsetHeaderValue;
81 static const char* g_UserDataKey = "_shib_check_user_";
84 /********************************************************************************/
85 // Basic Apache Configuration code.
88 // per-server module configuration structure
89 struct shib_server_config
94 // creates the per-server configuration
95 extern "C" void* create_shib_server_config(SH_AP_POOL* p, server_rec* s)
97 shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
102 // overrides server configuration in virtual servers
103 extern "C" void* merge_shib_server_config (SH_AP_POOL* p, void* base, void* sub)
105 shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
106 shib_server_config* parent=(shib_server_config*)base;
107 shib_server_config* child=(shib_server_config*)sub;
110 sc->szScheme=ap_pstrdup(p,child->szScheme);
111 else if (parent->szScheme)
112 sc->szScheme=ap_pstrdup(p,parent->szScheme);
119 // per-dir module configuration structure
120 struct shib_dir_config
123 char* szAuthGrpFile; // Auth GroupFile name
124 int bRequireAll; // all require directives must match, otherwise OR logic
126 // Content Configuration
127 char* szApplicationId; // Shib applicationId value
128 char* szRequireWith; // require a session using a specific initiator?
129 char* szRedirectToSSL; // redirect non-SSL requests to SSL port
130 int bOff; // flat-out disable all Shib processing
131 int bBasicHijack; // activate for AuthType Basic?
132 int bRequireSession; // require a session?
133 int bExportAssertion; // export SAML assertion to the environment?
136 // creates per-directory config structure
137 extern "C" void* create_shib_dir_config (SH_AP_POOL* p, char* d)
139 shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
141 dc->bBasicHijack = -1;
142 dc->bRequireSession = -1;
143 dc->bExportAssertion = -1;
144 dc->bRequireAll = -1;
145 dc->szRedirectToSSL = NULL;
146 dc->szAuthGrpFile = NULL;
147 dc->szApplicationId = NULL;
148 dc->szRequireWith = NULL;
152 // overrides server configuration in directories
153 extern "C" void* merge_shib_dir_config (SH_AP_POOL* p, void* base, void* sub)
155 shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
156 shib_dir_config* parent=(shib_dir_config*)base;
157 shib_dir_config* child=(shib_dir_config*)sub;
159 if (child->szAuthGrpFile)
160 dc->szAuthGrpFile=ap_pstrdup(p,child->szAuthGrpFile);
161 else if (parent->szAuthGrpFile)
162 dc->szAuthGrpFile=ap_pstrdup(p,parent->szAuthGrpFile);
164 dc->szAuthGrpFile=NULL;
166 if (child->szApplicationId)
167 dc->szApplicationId=ap_pstrdup(p,child->szApplicationId);
168 else if (parent->szApplicationId)
169 dc->szApplicationId=ap_pstrdup(p,parent->szApplicationId);
171 dc->szApplicationId=NULL;
173 if (child->szRequireWith)
174 dc->szRequireWith=ap_pstrdup(p,child->szRequireWith);
175 else if (parent->szRequireWith)
176 dc->szRequireWith=ap_pstrdup(p,parent->szRequireWith);
178 dc->szRequireWith=NULL;
180 if (child->szRedirectToSSL)
181 dc->szRedirectToSSL=ap_pstrdup(p,child->szRedirectToSSL);
182 else if (parent->szRedirectToSSL)
183 dc->szRedirectToSSL=ap_pstrdup(p,parent->szRedirectToSSL);
185 dc->szRedirectToSSL=NULL;
187 dc->bOff=((child->bOff==-1) ? parent->bOff : child->bOff);
188 dc->bBasicHijack=((child->bBasicHijack==-1) ? parent->bBasicHijack : child->bBasicHijack);
189 dc->bRequireSession=((child->bRequireSession==-1) ? parent->bRequireSession : child->bRequireSession);
190 dc->bExportAssertion=((child->bExportAssertion==-1) ? parent->bExportAssertion : child->bExportAssertion);
191 dc->bRequireAll=((child->bRequireAll==-1) ? parent->bRequireAll : child->bRequireAll);
195 // generic global slot handlers
196 extern "C" const char* ap_set_global_string_slot(cmd_parms* parms, void*, const char* arg)
198 *((char**)(parms->info))=ap_pstrdup(parms->pool,arg);
202 extern "C" const char* shib_set_server_string_slot(cmd_parms* parms, void*, const char* arg)
204 char* base=(char*)ap_get_module_config(parms->server->module_config,&mod_shib);
205 size_t offset=(size_t)parms->info;
206 *((char**)(base + offset))=ap_pstrdup(parms->pool,arg);
210 extern "C" const char* shib_ap_set_file_slot(cmd_parms* parms,
211 #ifdef SHIB_APACHE_13
212 char* arg1, char* arg2
214 void* arg1, const char* arg2
218 ap_set_file_slot(parms, arg1, arg2);
222 /********************************************************************************/
223 // Apache ShibTarget subclass(es) here.
225 class ShibTargetApache : public ShibTarget
227 mutable string m_body;
228 mutable bool m_gotBody;
232 shib_dir_config* m_dc;
233 shib_server_config* m_sc;
235 ShibTargetApache(request_rec* req) : m_gotBody(false) {
236 m_sc = (shib_server_config*)ap_get_module_config(req->server->module_config, &mod_shib);
237 m_dc = (shib_dir_config*)ap_get_module_config(req->per_dir_config, &mod_shib);
240 m_sc->szScheme ? m_sc->szScheme : ap_http_method(req),
241 ap_get_server_name(req),
242 (int)ap_get_server_port(req),
244 ap_table_get(req->headers_in, "Content-type"),
245 req->connection->remote_ip,
251 virtual ~ShibTargetApache() {}
253 virtual void log(ShibLogLevel level, const string &msg) {
254 ShibTarget::log(level,msg);
255 #ifdef SHIB_APACHE_13
256 ap_log_rerror(APLOG_MARK,
257 (level == LogLevelDebug ? APLOG_DEBUG :
258 (level == LogLevelInfo ? APLOG_INFO :
259 (level == LogLevelWarn ? APLOG_WARNING : APLOG_ERR)))|APLOG_NOERRNO, SH_AP_R(m_req), msg.c_str());
261 if (level == LogLevelError)
262 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(m_req), msg.c_str());
265 virtual string getCookies(void) const {
266 const char *c = ap_table_get(m_req->headers_in, "Cookie");
267 return string(c ? c : "");
269 virtual void setCookie(const string &name, const string &value) {
270 char* val = ap_psprintf(m_req->pool, "%s=%s", name.c_str(), value.c_str());
271 ap_table_addn(m_req->err_headers_out, "Set-Cookie", val);
273 virtual const char* getQueryString() const { return m_req->args; }
274 virtual const char* getRequestBody() const {
276 return m_body.c_str();
277 // Read the posted data
278 if (ap_setup_client_block(m_req, REQUEST_CHUNKED_ERROR))
279 throw saml::SAMLException("Apache function (setup_client_block) failed while reading POST request body.");
280 if (!ap_should_client_block(m_req))
281 throw saml::SAMLException("Apache function (should_client_block) failed while reading POST request body.");
282 if (m_req->remaining > 1024*1024)
283 throw saml::SAMLException("Blocked POST request body larger than size limit.");
285 char buff[HUGE_STRING_LEN];
286 ap_hard_timeout("[mod_shib] getRequestBody", m_req);
287 memset(buff, 0, sizeof(buff));
288 while (ap_get_client_block(m_req, buff, sizeof(buff)-1) > 0) {
289 ap_reset_timeout(m_req);
291 memset(buff, 0, sizeof(buff));
293 ap_kill_timeout(m_req);
294 return m_body.c_str();
296 virtual void clearHeader(const string &name) {
297 ap_table_unset(m_req->headers_in, name.c_str());
298 ap_table_set(m_req->headers_in, name.c_str(), g_unsetHeaderValue.c_str());
300 virtual void setHeader(const string &name, const string &value) {
301 ap_table_set(m_req->headers_in, name.c_str(), value.c_str());
303 virtual string getHeader(const string &name) {
304 const char *hdr = ap_table_get(m_req->headers_in, name.c_str());
305 return string(hdr ? hdr : "");
307 virtual void setRemoteUser(const string &user) {
308 SH_AP_USER(m_req) = ap_pstrdup(m_req->pool, user.c_str());
310 virtual string getRemoteUser(void) {
311 return string(SH_AP_USER(m_req) ? SH_AP_USER(m_req) : "");
313 virtual void* sendPage(
316 const string& content_type="text/html",
317 const saml::Iterator<header_t>& headers=EMPTY(header_t)
319 m_req->content_type = ap_psprintf(m_req->pool, content_type.c_str());
320 while (headers.hasNext()) {
321 const header_t& h=headers.next();
322 ap_table_set(m_req->headers_out, h.first.c_str(), h.second.c_str());
324 ap_send_http_header(m_req);
325 ap_rprintf(m_req, msg.c_str());
326 return (void*)((code==200) ? DONE : code);
328 virtual void* sendRedirect(const string& url) {
329 ap_table_set(m_req->headers_out, "Location", url.c_str());
330 return (void*)REDIRECT;
332 virtual void* returnDecline(void) { return (void*)DECLINED; }
333 virtual void* returnOK(void) { return (void*)OK; }
336 /********************************************************************************/
339 extern "C" int shib_check_user(request_rec* r)
341 // Short-circuit entirely?
342 if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
345 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_check_user(%d): ENTER\n", (int)getpid());
347 ostringstream threadid;
348 threadid << "[" << getpid() << "] shib_check_user" << '\0';
349 saml::NDC ndc(threadid.str().c_str());
352 ShibTargetApache sta(r);
354 // Check user authentication and export information, then set the handler bypass
355 pair<bool,void*> res = sta.doCheckAuthN(true);
356 apr_pool_userdata_setn((const void*)42,g_UserDataKey,NULL,r->pool);
357 if (res.first) return (int)res.second;
359 // user auth was okay -- export the assertions now
360 res = sta.doExportAssertions();
361 if (res.first) return (int)res.second;
363 // export happened successfully.. this user is ok.
366 catch (saml::SAMLException& e) {
367 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user threw an exception: %s", e.what());
372 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user threw an uncaught exception!");
378 extern "C" int shib_handler(request_rec* r)
380 // Short-circuit entirely?
381 if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
384 ostringstream threadid;
385 threadid << "[" << getpid() << "] shib_handler" << '\0';
386 saml::NDC ndc(threadid.str().c_str());
388 #ifndef SHIB_APACHE_13
389 // With 2.x, this handler always runs, though last.
390 // We check if shib_check_user ran, because it will detect a handler request
391 // and dispatch it directly.
393 apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
394 if (data==(const void*)42) {
395 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler skipped since check_user ran");
400 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler(%d): ENTER: %s", (int)getpid(), r->handler);
403 ShibTargetApache sta(r);
405 pair<bool,void*> res = sta.doHandler();
406 if (res.first) return (int)res.second;
408 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "doHandler() did not do anything.");
411 catch (saml::SAMLException& e) {
412 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler threw an exception: %s", e.what());
417 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler threw an uncaught exception!");
424 * shib_auth_checker() -- a simple resource manager to
425 * process the .htaccess settings
427 extern "C" int shib_auth_checker(request_rec* r)
429 // Short-circuit entirely?
430 if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
433 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_auth_checker(%d): ENTER", (int)getpid());
435 ostringstream threadid;
436 threadid << "[" << getpid() << "] shib_auth_checker" << '\0';
437 saml::NDC ndc(threadid.str().c_str());
440 ShibTargetApache sta(r);
442 pair<bool,void*> res = sta.doCheckAuthZ();
443 if (res.first) return (int)res.second;
448 catch (saml::SAMLException& e) {
449 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an exception: %s", e.what());
454 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an uncaught exception!");
460 // Access control plugin that enforces htaccess rules
461 class htAccessControl : virtual public IAccessControl
465 ~htAccessControl() {}
470 ISessionCacheEntry* entry
474 saml::IPlugIn* htAccessFactory(const DOMElement* e)
476 return new htAccessControl();
479 class ApacheRequestMapper : public virtual IRequestMapper, public virtual PropertySet
482 ApacheRequestMapper(const DOMElement* e);
483 ~ApacheRequestMapper() { delete m_mapper; delete m_htaccess; delete m_staKey; delete m_propsKey; }
484 void lock() { m_mapper->lock(); }
485 void unlock() { m_staKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
486 Settings getSettings(ShibTarget* st) const;
488 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
489 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
490 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
491 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
492 pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
493 const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
494 const DOMElement* getElement() const;
497 IRequestMapper* m_mapper;
499 ThreadKey* m_propsKey;
500 IAccessControl* m_htaccess;
503 saml::IPlugIn* ApacheRequestMapFactory(const DOMElement* e)
505 return new ApacheRequestMapper(e);
508 ApacheRequestMapper::ApacheRequestMapper(const DOMElement* e) : m_mapper(NULL), m_staKey(NULL), m_propsKey(NULL), m_htaccess(NULL)
510 saml::IPlugIn* p=saml::SAMLConfig::getConfig().getPlugMgr().newPlugin(shibtarget::XML::XMLRequestMapType,e);
511 m_mapper=dynamic_cast<IRequestMapper*>(p);
514 throw saml::UnsupportedExtensionException("Embedded request mapper plugin was not of correct type.");
516 m_htaccess=new htAccessControl();
517 m_staKey=ThreadKey::create(NULL);
518 m_propsKey=ThreadKey::create(NULL);
521 IRequestMapper::Settings ApacheRequestMapper::getSettings(ShibTarget* st) const
523 Settings s=m_mapper->getSettings(st);
524 m_staKey->setData(dynamic_cast<ShibTargetApache*>(st));
525 m_propsKey->setData((void*)s.first);
526 return pair<const PropertySet*,IAccessControl*>(this,s.second ? s.second : m_htaccess);
529 pair<bool,bool> ApacheRequestMapper::getBool(const char* name, const char* ns) const
531 ShibTargetApache* sta=reinterpret_cast<ShibTargetApache*>(m_staKey->getData());
532 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
534 // Override Apache-settable boolean properties.
535 if (name && !strcmp(name,"requireSession") && sta->m_dc->bRequireSession==1)
536 return make_pair(true,true);
537 else if (name && !strcmp(name,"exportAssertion") && sta->m_dc->bExportAssertion==1)
538 return make_pair(true,true);
540 return s ? s->getBool(name,ns) : make_pair(false,false);
543 pair<bool,const char*> ApacheRequestMapper::getString(const char* name, const char* ns) const
545 ShibTargetApache* sta=reinterpret_cast<ShibTargetApache*>(m_staKey->getData());
546 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
548 // Override Apache-settable string properties.
549 if (name && !strcmp(name,"authType")) {
550 const char *auth_type=ap_auth_type(sta->m_req);
552 // Check for Basic Hijack
553 if (!strcasecmp(auth_type, "basic") && sta->m_dc->bBasicHijack == 1)
554 auth_type = "shibboleth";
555 return make_pair(true,auth_type);
558 else if (name && !strcmp(name,"applicationId") && sta->m_dc->szApplicationId)
559 return pair<bool,const char*>(true,sta->m_dc->szApplicationId);
560 else if (name && !strcmp(name,"requireSessionWith") && sta->m_dc->szRequireWith)
561 return pair<bool,const char*>(true,sta->m_dc->szRequireWith);
562 else if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
563 return pair<bool,const char*>(true,sta->m_dc->szRedirectToSSL);
565 return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
568 pair<bool,const XMLCh*> ApacheRequestMapper::getXMLString(const char* name, const char* ns) const
570 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
571 return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
574 pair<bool,unsigned int> ApacheRequestMapper::getUnsignedInt(const char* name, const char* ns) const
576 ShibTargetApache* sta=reinterpret_cast<ShibTargetApache*>(m_staKey->getData());
577 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
579 // Override Apache-settable int properties.
580 if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
581 return pair<bool,unsigned int>(true,strtol(sta->m_dc->szRedirectToSSL,NULL,10));
583 return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
586 pair<bool,int> ApacheRequestMapper::getInt(const char* name, const char* ns) const
588 ShibTargetApache* sta=reinterpret_cast<ShibTargetApache*>(m_staKey->getData());
589 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
591 // Override Apache-settable int properties.
592 if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
593 return pair<bool,int>(true,atoi(sta->m_dc->szRedirectToSSL));
595 return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
598 const PropertySet* ApacheRequestMapper::getPropertySet(const char* name, const char* ns) const
600 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
601 return s ? s->getPropertySet(name,ns) : NULL;
604 const DOMElement* ApacheRequestMapper::getElement() const
606 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
607 return s ? s->getElement() : NULL;
610 static SH_AP_TABLE* groups_for_user(request_rec* r, const char* user, char* grpfile)
613 SH_AP_TABLE* grps=ap_make_table(r->pool,15);
614 char l[MAX_STRING_LEN];
615 const char *group_name, *ll, *w;
617 #ifdef SHIB_APACHE_13
618 if (!(f=ap_pcfg_openfile(r->pool,grpfile))) {
620 if (ap_pcfg_openfile(&f,r->pool,grpfile) != APR_SUCCESS) {
622 ap_log_rerror(APLOG_MARK,APLOG_DEBUG,SH_AP_R(r),"groups_for_user() could not open group file: %s\n",grpfile);
627 #ifdef SHIB_APACHE_13
628 sp=ap_make_sub_pool(r->pool);
630 if (apr_pool_create(&sp,r->pool) != APR_SUCCESS) {
631 ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,
632 "groups_for_user() could not create a subpool");
637 while (!(ap_cfg_getline(l,MAX_STRING_LEN,f))) {
638 if ((*l=='#') || (!*l))
643 group_name=ap_getword(sp,&ll,':');
646 w=ap_getword_conf(sp,&ll);
647 if (!strcmp(w,user)) {
648 ap_table_setn(grps,ap_pstrdup(r->pool,group_name),"in");
658 bool htAccessControl::authorized(
660 ISessionCacheEntry* entry
663 // Make sure the object is our type.
664 ShibTargetApache* sta=dynamic_cast<ShibTargetApache*>(st);
666 throw ConfigurationException("Request wrapper object was not of correct type.");
670 int m=sta->m_req->method_number;
671 bool method_restricted=false;
674 const array_header* reqs_arr=ap_requires(sta->m_req);
678 require_line* reqs=(require_line*)reqs_arr->elts;
680 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(sta->m_req),"REQUIRE nelts: %d", reqs_arr->nelts);
681 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(sta->m_req),"REQUIRE all: %d", sta->m_dc->bRequireAll);
683 vector<bool> auth_OK(reqs_arr->nelts,false);
685 #define SHIB_AP_CHECK_IS_OK { \
686 if (sta->m_dc->bRequireAll < 1) \
692 for (int x=0; x<reqs_arr->nelts; x++) {
694 if (!(reqs[x].method_mask & (1 << m)))
696 method_restricted=true;
697 string remote_user = st->getRemoteUser();
699 t = reqs[x].requirement;
700 w = ap_getword_white(sta->m_req->pool, &t);
702 if (!strcasecmp(w,"shibboleth")) {
703 // This is a dummy rule needed because Apache conflates authn and authz.
704 // Without some require rule, AuthType is ignored and no check_user hooks run.
707 else if (!strcmp(w,"valid-user")) {
709 st->log(ShibTarget::LogLevelDebug,"htAccessControl plugin accepting valid-user based on active session");
713 st->log(ShibTarget::LogLevelError,"htAccessControl plugin rejecting access for valid-user rule, no session is active");
715 else if (!strcmp(w,"user") && !remote_user.empty()) {
718 w=ap_getword_conf(sta->m_req->pool,&t);
726 // To do regex matching, we have to convert from UTF-8.
727 auto_ptr<XMLCh> trans(fromUTF8(w));
728 RegularExpression re(trans.get());
729 auto_ptr<XMLCh> trans2(fromUTF8(remote_user.c_str()));
730 if (re.matches(trans2.get())) {
731 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin accepting user (") + w + ")");
735 catch (XMLException& ex) {
736 auto_ptr_char tmp(ex.getMessage());
737 st->log(ShibTarget::LogLevelError,
738 string("htAccessControl plugin caught exception while parsing regular expression (") + w + "): " + tmp.get());
741 else if (remote_user==w) {
742 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin accepting user (") + w + ")");
747 else if (!strcmp(w,"group")) {
748 SH_AP_TABLE* grpstatus=NULL;
749 if (sta->m_dc->szAuthGrpFile && !remote_user.empty()) {
750 st->log(ShibTarget::LogLevelDebug,string("htAccessControl plugin using groups file: ") + sta->m_dc->szAuthGrpFile);
751 grpstatus=groups_for_user(sta->m_req,remote_user.c_str(),sta->m_dc->szAuthGrpFile);
757 w=ap_getword_conf(sta->m_req->pool,&t);
758 if (ap_table_get(grpstatus,w)) {
759 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin accepting group (") + w + ")");
765 saml::Iterator<shibboleth::IAAP*> provs=st->getApplication()->getAAPProviders();
766 shibboleth::AAP wrapper(provs,w);
767 if (wrapper.fail()) {
768 st->log(ShibTarget::LogLevelWarn, string("htAccessControl plugin didn't recognize require rule: ") + w);
774 if (!strcmp(wrapper->getHeader(),"REMOTE_USER"))
775 vals=remote_user.c_str();
777 vals=ap_table_get(sta->m_req->headers_in,wrapper->getHeader());
778 while (*t && vals && *vals) {
779 w=ap_getword_conf(sta->m_req->pool,&t);
786 auto_ptr<RegularExpression> re;
789 auto_ptr<XMLCh> trans(fromUTF8(w));
790 auto_ptr<RegularExpression> temp(new RegularExpression(trans.get()));
794 string vals_str(vals);
796 for (unsigned int i = 0; i < vals_str.length(); i++) {
797 if (vals_str.at(i) == ';') {
799 st->log(ShibTarget::LogLevelError, string("htAccessControl plugin found invalid header encoding (") +
800 vals + "): starts with a semicolon");
801 throw saml::SAMLException("Invalid information supplied to authorization plugin.");
804 if (vals_str.at(i-1) == '\\') {
805 vals_str.erase(i-1, 1);
810 string val = vals_str.substr(j, i-j);
813 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
814 if (re->matches(trans.get())) {
815 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
816 ", got " + val + ": authorization granted");
820 else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
821 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
822 ", got " + val + ": authorization granted.");
826 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
827 ", got " + val + ": authoritzation not granted.");
832 string val = vals_str.substr(j, vals_str.length()-j);
834 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
835 if (re->matches(trans.get())) {
836 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
837 ", got " + val + ": authorization granted.");
841 else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
842 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
843 ", got " + val + ": authorization granted");
847 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
848 ", got " + val + ": authorization not granted");
851 catch (XMLException& ex) {
852 auto_ptr_char tmp(ex.getMessage());
853 st->log(ShibTarget::LogLevelError, string("htAccessControl plugin caught exception while parsing regular expression (")
854 + w + "): " + tmp.get());
860 // check if all require directives are true
861 bool auth_all_OK = true;
862 for (int i= 0; i<reqs_arr->nelts; i++) {
863 auth_all_OK &= auth_OK[i];
865 if (auth_all_OK || !method_restricted)
871 #ifndef SHIB_APACHE_13
874 * Empty cleanup hook, Apache 2.x doesn't check NULL very well...
876 extern "C" apr_status_t shib_exit(void* data)
879 g_Config->shutdown();
882 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,0,NULL,"shib_exit() done\n");
890 * Cleanup the (per-process) pool info.
892 #ifdef SHIB_APACHE_13
893 extern "C" void shib_child_exit(server_rec* s, SH_AP_POOL* p)
896 extern "C" apr_status_t shib_child_exit(void* data)
898 server_rec* s = NULL;
901 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit(%d) dealing with g_Config..", (int)getpid());
902 g_Config->shutdown();
904 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit() done\n");
906 #ifndef SHIB_APACHE_13
913 * Things to do when the child process is initialized.
914 * (or after the configs are read in apache-2)
916 #ifdef SHIB_APACHE_13
917 extern "C" void shib_child_init(server_rec* s, SH_AP_POOL* p)
919 extern "C" void shib_child_init(apr_pool_t* p, server_rec* s)
922 // Initialize runtime components.
924 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init(%d) starting", (int)getpid());
927 ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() already initialized!");
932 g_Config=&ShibTargetConfig::getConfig();
933 SPConfig::getConfig().setFeatures(
938 SPConfig::RequestMapper |
939 SPConfig::InProcess |
942 if (!g_Config->init(g_szSchemaDir)) {
943 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize libraries");
946 saml::SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::htAccessControlType,&htAccessFactory);
947 saml::SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::NativeRequestMapType,&ApacheRequestMapFactory);
948 // We hijack the legacy type so that 1.2 config files will load this plugin
949 saml::SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::LegacyRequestMapType,&ApacheRequestMapFactory);
951 if (!g_Config->load(g_szSHIBConfig)) {
952 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to load configuration");
956 IConfig* conf=g_Config->getINI();
957 saml::Locker locker(conf);
958 const PropertySet* props=conf->getPropertySet("Local");
960 pair<bool,const char*> unsetValue=props->getString("unsetHeaderValue");
961 if (unsetValue.first)
962 g_unsetHeaderValue = unsetValue.second;
966 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize system");
970 // Set the cleanup handler
971 apr_pool_cleanup_register(p, NULL, &shib_exit, &shib_child_exit);
973 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() done");
976 typedef const char* (*config_fn_t)(void);
978 #ifdef SHIB_APACHE_13
980 // SHIB Module commands
982 static command_rec shire_cmds[] = {
983 {"ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
984 RSRC_CONF, TAKE1, "Path to shibboleth.xml config file"},
985 {"ShibSchemaDir", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
986 RSRC_CONF, TAKE1, "Path to Shibboleth XML schema directory"},
988 {"ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
989 (void *) XtOffsetOf (shib_server_config, szScheme),
990 RSRC_CONF, TAKE1, "URL scheme to force into generated URLs for a vhost"},
992 {"ShibDisable", (config_fn_t)ap_set_flag_slot,
993 (void *) XtOffsetOf (shib_dir_config, bOff),
994 OR_AUTHCFG, FLAG, "Disable all Shib module activity here to save processing effort"},
995 {"ShibApplicationId", (config_fn_t)ap_set_string_slot,
996 (void *) XtOffsetOf (shib_dir_config, szApplicationId),
997 OR_AUTHCFG, TAKE1, "Set Shibboleth applicationId property for content"},
998 {"ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
999 (void *) XtOffsetOf (shib_dir_config, bBasicHijack),
1000 OR_AUTHCFG, FLAG, "Respond to AuthType Basic and convert to shibboleth"},
1001 {"ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1002 (void *) XtOffsetOf (shib_dir_config, bRequireSession),
1003 OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist"},
1004 {"ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
1005 (void *) XtOffsetOf (shib_dir_config, szRequireWith),
1006 OR_AUTHCFG, TAKE1, "Initiates a new session if one does not exist using a specific SessionInitiator"},
1007 {"ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1008 (void *) XtOffsetOf (shib_dir_config, bExportAssertion),
1009 OR_AUTHCFG, FLAG, "Export SAML attribute assertion(s) to Shib-Attributes header"},
1010 {"ShibRedirectToSSL", (config_fn_t)ap_set_string_slot,
1011 (void *) XtOffsetOf (shib_dir_config, szRedirectToSSL),
1012 OR_AUTHCFG, TAKE1, "Redirect non-SSL requests to designated port" },
1013 {"AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
1014 (void *) XtOffsetOf (shib_dir_config, szAuthGrpFile),
1015 OR_AUTHCFG, TAKE1, "text file containing group names and member user IDs"},
1016 {"ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1017 (void *) XtOffsetOf (shib_dir_config, bRequireAll),
1018 OR_AUTHCFG, FLAG, "All require directives must match"},
1024 handler_rec shib_handlers[] = {
1025 { "shib-handler", shib_handler },
1029 module MODULE_VAR_EXPORT mod_shib = {
1030 STANDARD_MODULE_STUFF,
1031 NULL, /* initializer */
1032 create_shib_dir_config, /* dir config creater */
1033 merge_shib_dir_config, /* dir merger --- default is to override */
1034 create_shib_server_config, /* server config */
1035 merge_shib_server_config, /* merge server config */
1036 shire_cmds, /* command table */
1037 shib_handlers, /* handlers */
1038 NULL, /* filename translation */
1039 shib_check_user, /* check_user_id */
1040 shib_auth_checker, /* check auth */
1041 NULL, /* check access */
1042 NULL, /* type_checker */
1045 NULL, /* header parser */
1046 shib_child_init, /* child_init */
1047 shib_child_exit, /* child_exit */
1048 NULL /* post read-request */
1051 #elif defined(SHIB_APACHE_20) || defined(SHIB_APACHE_22)
1053 extern "C" void shib_register_hooks (apr_pool_t *p)
1055 ap_hook_child_init(shib_child_init, NULL, NULL, APR_HOOK_MIDDLE);
1056 ap_hook_check_user_id(shib_check_user, NULL, NULL, APR_HOOK_MIDDLE);
1057 ap_hook_auth_checker(shib_auth_checker, NULL, NULL, APR_HOOK_FIRST);
1058 ap_hook_handler(shib_handler, NULL, NULL, APR_HOOK_LAST);
1061 // SHIB Module commands
1064 static command_rec shib_cmds[] = {
1065 AP_INIT_TAKE1("ShibConfig",
1066 (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1067 RSRC_CONF, "Path to shibboleth.xml config file"),
1068 AP_INIT_TAKE1("ShibSchemaDir",
1069 (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1070 RSRC_CONF, "Path to Shibboleth XML schema directory"),
1072 AP_INIT_TAKE1("ShibURLScheme",
1073 (config_fn_t)shib_set_server_string_slot,
1074 (void *) offsetof (shib_server_config, szScheme),
1075 RSRC_CONF, "URL scheme to force into generated URLs for a vhost"),
1077 AP_INIT_FLAG("ShibDisable", (config_fn_t)ap_set_flag_slot,
1078 (void *) offsetof (shib_dir_config, bOff),
1079 OR_AUTHCFG, "Disable all Shib module activity here to save processing effort"),
1080 AP_INIT_TAKE1("ShibApplicationId", (config_fn_t)ap_set_string_slot,
1081 (void *) offsetof (shib_dir_config, szApplicationId),
1082 OR_AUTHCFG, "Set Shibboleth applicationId property for content"),
1083 AP_INIT_FLAG("ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1084 (void *) offsetof (shib_dir_config, bBasicHijack),
1085 OR_AUTHCFG, "Respond to AuthType Basic and convert to shibboleth"),
1086 AP_INIT_FLAG("ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1087 (void *) offsetof (shib_dir_config, bRequireSession),
1088 OR_AUTHCFG, "Initiates a new session if one does not exist"),
1089 AP_INIT_TAKE1("ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
1090 (void *) offsetof (shib_dir_config, szRequireWith),
1091 OR_AUTHCFG, "Initiates a new session if one does not exist using a specific SessionInitiator"),
1092 AP_INIT_FLAG("ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1093 (void *) offsetof (shib_dir_config, bExportAssertion),
1094 OR_AUTHCFG, "Export SAML attribute assertion(s) to Shib-Attributes header"),
1095 AP_INIT_TAKE1("ShibRedirectToSSL", (config_fn_t)ap_set_string_slot,
1096 (void *) offsetof (shib_dir_config, szRedirectToSSL),
1097 OR_AUTHCFG, "Redirect non-SSL requests to designated port"),
1098 AP_INIT_TAKE1("AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
1099 (void *) offsetof (shib_dir_config, szAuthGrpFile),
1100 OR_AUTHCFG, "Text file containing group names and member user IDs"),
1101 AP_INIT_FLAG("ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1102 (void *) offsetof (shib_dir_config, bRequireAll),
1103 OR_AUTHCFG, "All require directives must match"),
1108 module AP_MODULE_DECLARE_DATA mod_shib = {
1109 STANDARD20_MODULE_STUFF,
1110 create_shib_dir_config, /* create dir config */
1111 merge_shib_dir_config, /* merge dir config --- default is to override */
1112 create_shib_server_config, /* create server config */
1113 merge_shib_server_config, /* merge server config */
1114 shib_cmds, /* command table */
1115 shib_register_hooks /* register hooks */
1119 #error "undefined APACHE version"