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/shib-threads.h>
38 #include <shib-target/shib-target.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()
71 using namespace shibboleth;
72 using namespace shibtarget;
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 static const char* g_UserDataKey = "_shib_check_user_";
83 /********************************************************************************/
84 // Basic Apache Configuration code.
87 // per-server module configuration structure
88 struct shib_server_config
93 // creates the per-server configuration
94 extern "C" void* create_shib_server_config(SH_AP_POOL* p, server_rec* s)
96 shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
101 // overrides server configuration in virtual servers
102 extern "C" void* merge_shib_server_config (SH_AP_POOL* p, void* base, void* sub)
104 shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
105 shib_server_config* parent=(shib_server_config*)base;
106 shib_server_config* child=(shib_server_config*)sub;
109 sc->szScheme=ap_pstrdup(p,child->szScheme);
110 else if (parent->szScheme)
111 sc->szScheme=ap_pstrdup(p,parent->szScheme);
118 // per-dir module configuration structure
119 struct shib_dir_config
122 char* szAuthGrpFile; // Auth GroupFile name
123 int bRequireAll; // all require directives must match, otherwise OR logic
125 // Content Configuration
126 char* szApplicationId; // Shib applicationId value
127 char* szRequireWith; // require a session using a specific initiator?
128 char* szRedirectToSSL; // redirect non-SSL requests to SSL port
129 int bOff; // flat-out disable all Shib processing
130 int bBasicHijack; // activate for AuthType Basic?
131 int bRequireSession; // require a session?
132 int bExportAssertion; // export SAML assertion to the environment?
135 // creates per-directory config structure
136 extern "C" void* create_shib_dir_config (SH_AP_POOL* p, char* d)
138 shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
140 dc->bBasicHijack = -1;
141 dc->bRequireSession = -1;
142 dc->bExportAssertion = -1;
143 dc->bRequireAll = -1;
144 dc->szRedirectToSSL = NULL;
145 dc->szAuthGrpFile = NULL;
146 dc->szApplicationId = NULL;
147 dc->szRequireWith = NULL;
151 // overrides server configuration in directories
152 extern "C" void* merge_shib_dir_config (SH_AP_POOL* p, void* base, void* sub)
154 shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
155 shib_dir_config* parent=(shib_dir_config*)base;
156 shib_dir_config* child=(shib_dir_config*)sub;
158 if (child->szAuthGrpFile)
159 dc->szAuthGrpFile=ap_pstrdup(p,child->szAuthGrpFile);
160 else if (parent->szAuthGrpFile)
161 dc->szAuthGrpFile=ap_pstrdup(p,parent->szAuthGrpFile);
163 dc->szAuthGrpFile=NULL;
165 if (child->szApplicationId)
166 dc->szApplicationId=ap_pstrdup(p,child->szApplicationId);
167 else if (parent->szApplicationId)
168 dc->szApplicationId=ap_pstrdup(p,parent->szApplicationId);
170 dc->szApplicationId=NULL;
172 if (child->szRequireWith)
173 dc->szRequireWith=ap_pstrdup(p,child->szRequireWith);
174 else if (parent->szRequireWith)
175 dc->szRequireWith=ap_pstrdup(p,parent->szRequireWith);
177 dc->szRequireWith=NULL;
179 if (child->szRedirectToSSL)
180 dc->szRedirectToSSL=ap_pstrdup(p,child->szRedirectToSSL);
181 else if (parent->szRedirectToSSL)
182 dc->szRedirectToSSL=ap_pstrdup(p,parent->szRedirectToSSL);
184 dc->szRedirectToSSL=NULL;
186 dc->bOff=((child->bOff==-1) ? parent->bOff : child->bOff);
187 dc->bBasicHijack=((child->bBasicHijack==-1) ? parent->bBasicHijack : child->bBasicHijack);
188 dc->bRequireSession=((child->bRequireSession==-1) ? parent->bRequireSession : child->bRequireSession);
189 dc->bExportAssertion=((child->bExportAssertion==-1) ? parent->bExportAssertion : child->bExportAssertion);
190 dc->bRequireAll=((child->bRequireAll==-1) ? parent->bRequireAll : child->bRequireAll);
194 // generic global slot handlers
195 extern "C" const char* ap_set_global_string_slot(cmd_parms* parms, void*, const char* arg)
197 *((char**)(parms->info))=ap_pstrdup(parms->pool,arg);
201 extern "C" const char* shib_set_server_string_slot(cmd_parms* parms, void*, const char* arg)
203 char* base=(char*)ap_get_module_config(parms->server->module_config,&mod_shib);
204 size_t offset=(size_t)parms->info;
205 *((char**)(base + offset))=ap_pstrdup(parms->pool,arg);
209 extern "C" const char* shib_ap_set_file_slot(cmd_parms* parms,
210 #ifdef SHIB_APACHE_13
211 char* arg1, char* arg2
213 void* arg1, const char* arg2
217 ap_set_file_slot(parms, arg1, arg2);
221 /********************************************************************************/
222 // Apache ShibTarget subclass(es) here.
224 class ShibTargetApache : public ShibTarget
226 mutable string m_body;
227 mutable bool m_gotBody;
231 shib_dir_config* m_dc;
232 shib_server_config* m_sc;
234 ShibTargetApache(request_rec* req) : m_gotBody(false) {
235 m_sc = (shib_server_config*)ap_get_module_config(req->server->module_config, &mod_shib);
236 m_dc = (shib_dir_config*)ap_get_module_config(req->per_dir_config, &mod_shib);
239 m_sc->szScheme ? m_sc->szScheme : ap_http_method(req),
240 ap_get_server_name(req),
241 (int)ap_get_server_port(req),
243 ap_table_get(req->headers_in, "Content-type"),
244 req->connection->remote_ip,
250 virtual ~ShibTargetApache() {}
252 virtual void log(ShibLogLevel level, const string &msg) {
253 ShibTarget::log(level,msg);
254 #ifdef SHIB_APACHE_13
255 ap_log_rerror(APLOG_MARK,
256 (level == LogLevelDebug ? APLOG_DEBUG :
257 (level == LogLevelInfo ? APLOG_INFO :
258 (level == LogLevelWarn ? APLOG_WARNING : APLOG_ERR)))|APLOG_NOERRNO, SH_AP_R(m_req), msg.c_str());
260 if (level == LogLevelError)
261 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(m_req), msg.c_str());
264 virtual string getCookies(void) const {
265 const char *c = ap_table_get(m_req->headers_in, "Cookie");
266 return string(c ? c : "");
268 virtual void setCookie(const string &name, const string &value) {
269 char* val = ap_psprintf(m_req->pool, "%s=%s", name.c_str(), value.c_str());
270 ap_table_addn(m_req->err_headers_out, "Set-Cookie", val);
272 virtual const char* getQueryString() const { return m_req->args; }
273 virtual const char* getRequestBody() const {
275 return m_body.c_str();
276 // Read the posted data
277 if (ap_setup_client_block(m_req, REQUEST_CHUNKED_ERROR))
278 throw SAMLException("Apache function (setup_client_block) failed while reading POST request body.");
279 if (!ap_should_client_block(m_req))
280 throw SAMLException("Apache function (should_client_block) failed while reading POST request body.");
281 if (m_req->remaining > 1024*1024)
282 throw SAMLException("Blocked POST request body larger than size limit.");
284 char buff[HUGE_STRING_LEN];
285 ap_hard_timeout("[mod_shib] getRequestBody", m_req);
286 memset(buff, 0, sizeof(buff));
287 while (ap_get_client_block(m_req, buff, sizeof(buff)-1) > 0) {
288 ap_reset_timeout(m_req);
290 memset(buff, 0, sizeof(buff));
292 ap_kill_timeout(m_req);
293 return m_body.c_str();
295 virtual void clearHeader(const string &name) {
296 ap_table_unset(m_req->headers_in, name.c_str());
298 virtual void setHeader(const string &name, const string &value) {
299 ap_table_set(m_req->headers_in, name.c_str(), value.c_str());
301 virtual string getHeader(const string &name) {
302 const char *hdr = ap_table_get(m_req->headers_in, name.c_str());
303 return string(hdr ? hdr : "");
305 virtual void setRemoteUser(const string &user) {
306 SH_AP_USER(m_req) = ap_pstrdup(m_req->pool, user.c_str());
308 virtual string getRemoteUser(void) {
309 return string(SH_AP_USER(m_req) ? SH_AP_USER(m_req) : "");
311 virtual void* sendPage(
314 const string& content_type="text/html",
315 const Iterator<header_t>& headers=EMPTY(header_t)
317 m_req->content_type = ap_psprintf(m_req->pool, content_type.c_str());
318 while (headers.hasNext()) {
319 const header_t& h=headers.next();
320 ap_table_set(m_req->headers_out, h.first.c_str(), h.second.c_str());
322 ap_send_http_header(m_req);
323 ap_rprintf(m_req, msg.c_str());
324 return (void*)((code==200) ? DONE : code);
326 virtual void* sendRedirect(const string& url) {
327 ap_table_set(m_req->headers_out, "Location", url.c_str());
328 return (void*)REDIRECT;
330 virtual void* returnDecline(void) { return (void*)DECLINED; }
331 virtual void* returnOK(void) { return (void*)OK; }
334 /********************************************************************************/
337 extern "C" int shib_check_user(request_rec* r)
339 // Short-circuit entirely?
340 if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
343 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_check_user(%d): ENTER\n", (int)getpid());
345 ostringstream threadid;
346 threadid << "[" << getpid() << "] shib_check_user" << '\0';
347 saml::NDC ndc(threadid.str().c_str());
350 ShibTargetApache sta(r);
352 // Check user authentication and export information, then set the handler bypass
353 pair<bool,void*> res = sta.doCheckAuthN(true);
354 apr_pool_userdata_setn((const void*)42,g_UserDataKey,NULL,r->pool);
355 if (res.first) return (int)res.second;
357 // user auth was okay -- export the assertions now
358 res = sta.doExportAssertions();
359 if (res.first) return (int)res.second;
361 // export happened successfully.. this user is ok.
364 catch (SAMLException& e) {
365 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user threw an exception: %s", e.what());
370 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user threw an uncaught exception!");
376 extern "C" int shib_handler(request_rec* r)
378 // Short-circuit entirely?
379 if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
382 ostringstream threadid;
383 threadid << "[" << getpid() << "] shib_handler" << '\0';
384 saml::NDC ndc(threadid.str().c_str());
386 #ifndef SHIB_APACHE_13
387 // With 2.x, this handler always runs, though last.
388 // We check if shib_check_user ran, because it will detect a handler request
389 // and dispatch it directly.
391 apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
392 if (data==(const void*)42) {
393 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler skipped since check_user ran");
398 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler(%d): ENTER: %s", (int)getpid(), r->handler);
401 ShibTargetApache sta(r);
403 pair<bool,void*> res = sta.doHandler();
404 if (res.first) return (int)res.second;
406 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "doHandler() did not do anything.");
409 catch (SAMLException& e) {
410 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler threw an exception: %s", e.what());
415 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler threw an uncaught exception!");
422 * shib_auth_checker() -- a simple resource manager to
423 * process the .htaccess settings
425 extern "C" int shib_auth_checker(request_rec* r)
427 // Short-circuit entirely?
428 if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
431 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_auth_checker(%d): ENTER", (int)getpid());
433 ostringstream threadid;
434 threadid << "[" << getpid() << "] shib_auth_checker" << '\0';
435 saml::NDC ndc(threadid.str().c_str());
438 ShibTargetApache sta(r);
440 pair<bool,void*> res = sta.doCheckAuthZ();
441 if (res.first) return (int)res.second;
446 catch (SAMLException& e) {
447 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an exception: %s", e.what());
452 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an uncaught exception!");
458 // Access control plugin that enforces htaccess rules
459 class htAccessControl : virtual public IAccessControl
463 ~htAccessControl() {}
468 ISessionCacheEntry* entry
472 IPlugIn* htAccessFactory(const DOMElement* e)
474 return new htAccessControl();
477 class ApacheRequestMapper : public virtual IRequestMapper, public virtual IPropertySet
480 ApacheRequestMapper(const DOMElement* e);
481 ~ApacheRequestMapper() { delete m_mapper; delete m_htaccess; delete m_staKey; delete m_propsKey; }
482 void lock() { m_mapper->lock(); }
483 void unlock() { m_staKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
484 Settings getSettings(ShibTarget* st) const;
486 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
487 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
488 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
489 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
490 pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
491 const IPropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
492 const DOMElement* getElement() const;
495 IRequestMapper* m_mapper;
497 ThreadKey* m_propsKey;
498 IAccessControl* m_htaccess;
501 IPlugIn* ApacheRequestMapFactory(const DOMElement* e)
503 return new ApacheRequestMapper(e);
506 ApacheRequestMapper::ApacheRequestMapper(const DOMElement* e) : m_mapper(NULL), m_staKey(NULL), m_propsKey(NULL), m_htaccess(NULL)
508 IPlugIn* p=SAMLConfig::getConfig().getPlugMgr().newPlugin(shibtarget::XML::XMLRequestMapType,e);
509 m_mapper=dynamic_cast<IRequestMapper*>(p);
512 throw UnsupportedExtensionException("Embedded request mapper plugin was not of correct type.");
514 m_htaccess=new htAccessControl();
515 m_staKey=ThreadKey::create(NULL);
516 m_propsKey=ThreadKey::create(NULL);
519 IRequestMapper::Settings ApacheRequestMapper::getSettings(ShibTarget* st) const
521 Settings s=m_mapper->getSettings(st);
522 m_staKey->setData(dynamic_cast<ShibTargetApache*>(st));
523 m_propsKey->setData((void*)s.first);
524 return pair<const IPropertySet*,IAccessControl*>(this,s.second ? s.second : m_htaccess);
527 pair<bool,bool> ApacheRequestMapper::getBool(const char* name, const char* ns) const
529 ShibTargetApache* sta=reinterpret_cast<ShibTargetApache*>(m_staKey->getData());
530 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
532 // Override Apache-settable boolean properties.
533 if (name && !strcmp(name,"requireSession") && sta->m_dc->bRequireSession==1)
534 return make_pair(true,true);
535 else if (name && !strcmp(name,"exportAssertion") && sta->m_dc->bExportAssertion==1)
536 return make_pair(true,true);
538 return s ? s->getBool(name,ns) : make_pair(false,false);
541 pair<bool,const char*> ApacheRequestMapper::getString(const char* name, const char* ns) const
543 ShibTargetApache* sta=reinterpret_cast<ShibTargetApache*>(m_staKey->getData());
544 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
546 // Override Apache-settable string properties.
547 if (name && !strcmp(name,"authType")) {
548 const char *auth_type=ap_auth_type(sta->m_req);
550 // Check for Basic Hijack
551 if (!strcasecmp(auth_type, "basic") && sta->m_dc->bBasicHijack == 1)
552 auth_type = "shibboleth";
553 return make_pair(true,auth_type);
556 else if (name && !strcmp(name,"applicationId") && sta->m_dc->szApplicationId)
557 return pair<bool,const char*>(true,sta->m_dc->szApplicationId);
558 else if (name && !strcmp(name,"requireSessionWith") && sta->m_dc->szRequireWith)
559 return pair<bool,const char*>(true,sta->m_dc->szRequireWith);
560 else if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
561 return pair<bool,const char*>(true,sta->m_dc->szRedirectToSSL);
563 return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
566 pair<bool,const XMLCh*> ApacheRequestMapper::getXMLString(const char* name, const char* ns) const
568 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
569 return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
572 pair<bool,unsigned int> ApacheRequestMapper::getUnsignedInt(const char* name, const char* ns) const
574 ShibTargetApache* sta=reinterpret_cast<ShibTargetApache*>(m_staKey->getData());
575 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
577 // Override Apache-settable int properties.
578 if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
579 return pair<bool,unsigned int>(true,strtol(sta->m_dc->szRedirectToSSL,NULL,10));
581 return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
584 pair<bool,int> ApacheRequestMapper::getInt(const char* name, const char* ns) const
586 ShibTargetApache* sta=reinterpret_cast<ShibTargetApache*>(m_staKey->getData());
587 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
589 // Override Apache-settable int properties.
590 if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
591 return pair<bool,int>(true,atoi(sta->m_dc->szRedirectToSSL));
593 return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
596 const IPropertySet* ApacheRequestMapper::getPropertySet(const char* name, const char* ns) const
598 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
599 return s ? s->getPropertySet(name,ns) : NULL;
602 const DOMElement* ApacheRequestMapper::getElement() const
604 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
605 return s ? s->getElement() : NULL;
608 static SH_AP_TABLE* groups_for_user(request_rec* r, const char* user, char* grpfile)
611 SH_AP_TABLE* grps=ap_make_table(r->pool,15);
612 char l[MAX_STRING_LEN];
613 const char *group_name, *ll, *w;
615 #ifdef SHIB_APACHE_13
616 if (!(f=ap_pcfg_openfile(r->pool,grpfile))) {
618 if (ap_pcfg_openfile(&f,r->pool,grpfile) != APR_SUCCESS) {
620 ap_log_rerror(APLOG_MARK,APLOG_DEBUG,SH_AP_R(r),"groups_for_user() could not open group file: %s\n",grpfile);
625 #ifdef SHIB_APACHE_13
626 sp=ap_make_sub_pool(r->pool);
628 if (apr_pool_create(&sp,r->pool) != APR_SUCCESS) {
629 ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,
630 "groups_for_user() could not create a subpool");
635 while (!(ap_cfg_getline(l,MAX_STRING_LEN,f))) {
636 if ((*l=='#') || (!*l))
641 group_name=ap_getword(sp,&ll,':');
644 w=ap_getword_conf(sp,&ll);
645 if (!strcmp(w,user)) {
646 ap_table_setn(grps,ap_pstrdup(r->pool,group_name),"in");
656 bool htAccessControl::authorized(
658 ISessionCacheEntry* entry
661 // Make sure the object is our type.
662 ShibTargetApache* sta=dynamic_cast<ShibTargetApache*>(st);
664 throw ConfigurationException("Request wrapper object was not of correct type.");
668 int m=sta->m_req->method_number;
669 bool method_restricted=false;
672 const array_header* reqs_arr=ap_requires(sta->m_req);
676 require_line* reqs=(require_line*)reqs_arr->elts;
678 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(sta->m_req),"REQUIRE nelts: %d", reqs_arr->nelts);
679 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(sta->m_req),"REQUIRE all: %d", sta->m_dc->bRequireAll);
681 vector<bool> auth_OK(reqs_arr->nelts,false);
683 #define SHIB_AP_CHECK_IS_OK { \
684 if (sta->m_dc->bRequireAll < 1) \
690 for (int x=0; x<reqs_arr->nelts; x++) {
692 if (!(reqs[x].method_mask & (1 << m)))
694 method_restricted=true;
695 string remote_user = st->getRemoteUser();
697 t = reqs[x].requirement;
698 w = ap_getword_white(sta->m_req->pool, &t);
700 if (!strcasecmp(w,"shibboleth")) {
701 // This is a dummy rule needed because Apache conflates authn and authz.
702 // Without some require rule, AuthType is ignored and no check_user hooks run.
705 else if (!strcmp(w,"valid-user")) {
707 st->log(ShibTarget::LogLevelDebug,"htAccessControl plugin accepting valid-user based on active session");
711 st->log(ShibTarget::LogLevelError,"htAccessControl plugin rejecting access for valid-user rule, no session is active");
713 else if (!strcmp(w,"user") && !remote_user.empty()) {
716 w=ap_getword_conf(sta->m_req->pool,&t);
724 // To do regex matching, we have to convert from UTF-8.
725 auto_ptr<XMLCh> trans(fromUTF8(w));
726 RegularExpression re(trans.get());
727 auto_ptr<XMLCh> trans2(fromUTF8(remote_user.c_str()));
728 if (re.matches(trans2.get())) {
729 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin accepting user (") + w + ")");
733 catch (XMLException& ex) {
734 auto_ptr_char tmp(ex.getMessage());
735 st->log(ShibTarget::LogLevelError,
736 string("htAccessControl plugin caught exception while parsing regular expression (") + w + "): " + tmp.get());
739 else if (remote_user==w) {
740 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin accepting user (") + w + ")");
745 else if (!strcmp(w,"group")) {
746 SH_AP_TABLE* grpstatus=NULL;
747 if (sta->m_dc->szAuthGrpFile && !remote_user.empty()) {
748 st->log(ShibTarget::LogLevelDebug,string("htAccessControl plugin using groups file: ") + sta->m_dc->szAuthGrpFile);
749 grpstatus=groups_for_user(sta->m_req,remote_user.c_str(),sta->m_dc->szAuthGrpFile);
755 w=ap_getword_conf(sta->m_req->pool,&t);
756 if (ap_table_get(grpstatus,w)) {
757 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin accepting group (") + w + ")");
763 Iterator<IAAP*> provs=st->getApplication()->getAAPProviders();
764 AAP wrapper(provs,w);
765 if (wrapper.fail()) {
766 st->log(ShibTarget::LogLevelWarn, string("htAccessControl plugin didn't recognize require rule: ") + w);
771 const char* vals=ap_table_get(sta->m_req->headers_in,wrapper->getHeader());
773 w=ap_getword_conf(sta->m_req->pool,&t);
780 auto_ptr<RegularExpression> re;
783 auto_ptr<XMLCh> trans(fromUTF8(w));
784 auto_ptr<RegularExpression> temp(new RegularExpression(trans.get()));
788 string vals_str(vals);
790 for (unsigned int i = 0; i < vals_str.length(); i++) {
791 if (vals_str.at(i) == ';') {
793 st->log(ShibTarget::LogLevelError, string("htAccessControl plugin found invalid header encoding (") +
794 vals + "): starts with a semicolon");
795 throw SAMLException("Invalid information supplied to authorization plugin.");
798 if (vals_str.at(i-1) == '\\') {
799 vals_str.erase(i-1, 1);
804 string val = vals_str.substr(j, i-j);
807 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
808 if (re->matches(trans.get())) {
809 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
810 ", got " + val + ": authorization granted");
814 else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
815 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
816 ", got " + val + ": authorization granted.");
820 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
821 ", got " + val + ": authoritzation not granted.");
826 string val = vals_str.substr(j, vals_str.length()-j);
828 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
829 if (re->matches(trans.get())) {
830 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
831 ", got " + val + ": authorization granted.");
835 else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
836 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
837 ", got " + val + ": authorization granted");
841 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
842 ", got " + val + ": authorization not granted");
845 catch (XMLException& ex) {
846 auto_ptr_char tmp(ex.getMessage());
847 st->log(ShibTarget::LogLevelError, string("htAccessControl plugin caught exception while parsing regular expression (")
848 + w + "): " + tmp.get());
854 // check if all require directives are true
855 bool auth_all_OK = true;
856 for (int i= 0; i<reqs_arr->nelts; i++) {
857 auth_all_OK &= auth_OK[i];
859 if (auth_all_OK || !method_restricted)
865 #ifndef SHIB_APACHE_13
868 * Empty cleanup hook, Apache 2.x doesn't check NULL very well...
870 extern "C" apr_status_t shib_exit(void* data)
873 g_Config->shutdown();
876 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,0,NULL,"shib_exit() done\n");
884 * Cleanup the (per-process) pool info.
886 #ifdef SHIB_APACHE_13
887 extern "C" void shib_child_exit(server_rec* s, SH_AP_POOL* p)
890 extern "C" apr_status_t shib_child_exit(void* data)
892 server_rec* s = NULL;
895 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit(%d) dealing with g_Config..", (int)getpid());
896 g_Config->shutdown();
898 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit() done\n");
900 #ifndef SHIB_APACHE_13
907 * Things to do when the child process is initialized.
908 * (or after the configs are read in apache-2)
910 #ifdef SHIB_APACHE_13
911 extern "C" void shib_child_init(server_rec* s, SH_AP_POOL* p)
913 extern "C" void shib_child_init(apr_pool_t* p, server_rec* s)
916 // Initialize runtime components.
918 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init(%d) starting", (int)getpid());
921 ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() already initialized!");
926 g_Config=&ShibTargetConfig::getConfig();
927 g_Config->setFeatures(
928 ShibTargetConfig::Caching |
929 ShibTargetConfig::Listener |
930 ShibTargetConfig::Metadata |
931 ShibTargetConfig::AAP |
932 ShibTargetConfig::RequestMapper |
933 ShibTargetConfig::InProcess |
934 ShibTargetConfig::Logging
936 if (!g_Config->init(g_szSchemaDir)) {
937 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize libraries");
940 SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::htAccessControlType,&htAccessFactory);
941 SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::NativeRequestMapType,&ApacheRequestMapFactory);
942 // We hijack the legacy type so that 1.2 config files will load this plugin
943 SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::LegacyRequestMapType,&ApacheRequestMapFactory);
945 if (!g_Config->load(g_szSHIBConfig)) {
946 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to load configuration");
951 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize system");
955 // Set the cleanup handler
956 apr_pool_cleanup_register(p, NULL, &shib_exit, &shib_child_exit);
958 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() done");
961 typedef const char* (*config_fn_t)(void);
963 #ifdef SHIB_APACHE_13
965 // SHIB Module commands
967 static command_rec shire_cmds[] = {
968 {"ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
969 RSRC_CONF, TAKE1, "Path to shibboleth.xml config file"},
970 {"ShibSchemaDir", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
971 RSRC_CONF, TAKE1, "Path to Shibboleth XML schema directory"},
973 {"ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
974 (void *) XtOffsetOf (shib_server_config, szScheme),
975 RSRC_CONF, TAKE1, "URL scheme to force into generated URLs for a vhost"},
977 {"ShibDisable", (config_fn_t)ap_set_flag_slot,
978 (void *) XtOffsetOf (shib_dir_config, bOff),
979 OR_AUTHCFG, FLAG, "Disable all Shib module activity here to save processing effort"},
980 {"ShibApplicationId", (config_fn_t)ap_set_string_slot,
981 (void *) XtOffsetOf (shib_dir_config, szApplicationId),
982 OR_AUTHCFG, TAKE1, "Set Shibboleth applicationId property for content"},
983 {"ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
984 (void *) XtOffsetOf (shib_dir_config, bBasicHijack),
985 OR_AUTHCFG, FLAG, "Respond to AuthType Basic and convert to shibboleth"},
986 {"ShibRequireSession", (config_fn_t)ap_set_flag_slot,
987 (void *) XtOffsetOf (shib_dir_config, bRequireSession),
988 OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist"},
989 {"ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
990 (void *) XtOffsetOf (shib_dir_config, szRequireWith),
991 OR_AUTHCFG, TAKE1, "Initiates a new session if one does not exist using a specific SessionInitiator"},
992 {"ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
993 (void *) XtOffsetOf (shib_dir_config, bExportAssertion),
994 OR_AUTHCFG, FLAG, "Export SAML attribute assertion(s) to Shib-Attributes header"},
995 {"ShibRedirectToSSL", (config_fn_t)ap_set_string_slot,
996 (void *) XtOffsetOf (shib_dir_config, szRedirectToSSL),
997 OR_AUTHCFG, TAKE1, "Redirect non-SSL requests to designated port" },
998 {"AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
999 (void *) XtOffsetOf (shib_dir_config, szAuthGrpFile),
1000 OR_AUTHCFG, TAKE1, "text file containing group names and member user IDs"},
1001 {"ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1002 (void *) XtOffsetOf (shib_dir_config, bRequireAll),
1003 OR_AUTHCFG, FLAG, "All require directives must match"},
1009 handler_rec shib_handlers[] = {
1010 { "shib-handler", shib_handler },
1014 module MODULE_VAR_EXPORT mod_shib = {
1015 STANDARD_MODULE_STUFF,
1016 NULL, /* initializer */
1017 create_shib_dir_config, /* dir config creater */
1018 merge_shib_dir_config, /* dir merger --- default is to override */
1019 create_shib_server_config, /* server config */
1020 merge_shib_server_config, /* merge server config */
1021 shire_cmds, /* command table */
1022 shib_handlers, /* handlers */
1023 NULL, /* filename translation */
1024 shib_check_user, /* check_user_id */
1025 shib_auth_checker, /* check auth */
1026 NULL, /* check access */
1027 NULL, /* type_checker */
1030 NULL, /* header parser */
1031 shib_child_init, /* child_init */
1032 shib_child_exit, /* child_exit */
1033 NULL /* post read-request */
1036 #elif defined(SHIB_APACHE_20)
1038 extern "C" void shib_register_hooks (apr_pool_t *p)
1040 ap_hook_child_init(shib_child_init, NULL, NULL, APR_HOOK_MIDDLE);
1041 ap_hook_check_user_id(shib_check_user, NULL, NULL, APR_HOOK_MIDDLE);
1042 ap_hook_auth_checker(shib_auth_checker, NULL, NULL, APR_HOOK_FIRST);
1043 ap_hook_handler(shib_handler, NULL, NULL, APR_HOOK_LAST);
1046 // SHIB Module commands
1049 static command_rec shib_cmds[] = {
1050 AP_INIT_TAKE1("ShibConfig",
1051 (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1052 RSRC_CONF, "Path to shibboleth.xml config file"),
1053 AP_INIT_TAKE1("ShibSchemaDir",
1054 (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1055 RSRC_CONF, "Path to Shibboleth XML schema directory"),
1057 AP_INIT_TAKE1("ShibURLScheme",
1058 (config_fn_t)shib_set_server_string_slot,
1059 (void *) offsetof (shib_server_config, szScheme),
1060 RSRC_CONF, "URL scheme to force into generated URLs for a vhost"),
1062 AP_INIT_FLAG("ShibDisable", (config_fn_t)ap_set_flag_slot,
1063 (void *) offsetof (shib_dir_config, bOff),
1064 OR_AUTHCFG, "Disable all Shib module activity here to save processing effort"),
1065 AP_INIT_TAKE1("ShibApplicationId", (config_fn_t)ap_set_string_slot,
1066 (void *) offsetof (shib_dir_config, szApplicationId),
1067 OR_AUTHCFG, "Set Shibboleth applicationId property for content"),
1068 AP_INIT_FLAG("ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1069 (void *) offsetof (shib_dir_config, bBasicHijack),
1070 OR_AUTHCFG, "Respond to AuthType Basic and convert to shibboleth"),
1071 AP_INIT_FLAG("ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1072 (void *) offsetof (shib_dir_config, bRequireSession),
1073 OR_AUTHCFG, "Initiates a new session if one does not exist"),
1074 AP_INIT_TAKE1("ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
1075 (void *) offsetof (shib_dir_config, szRequireWith),
1076 OR_AUTHCFG, "Initiates a new session if one does not exist using a specific SessionInitiator"),
1077 AP_INIT_FLAG("ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1078 (void *) offsetof (shib_dir_config, bExportAssertion),
1079 OR_AUTHCFG, "Export SAML attribute assertion(s) to Shib-Attributes header"),
1080 AP_INIT_TAKE1("ShibRedirectToSSL", (config_fn_t)ap_set_string_slot,
1081 (void *) offsetof (shib_dir_config, szRedirectToSSL),
1082 OR_AUTHCFG, "Redirect non-SSL requests to designated port"),
1083 AP_INIT_TAKE1("AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
1084 (void *) offsetof (shib_dir_config, szAuthGrpFile),
1085 OR_AUTHCFG, "Text file containing group names and member user IDs"),
1086 AP_INIT_FLAG("ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1087 (void *) offsetof (shib_dir_config, bRequireAll),
1088 OR_AUTHCFG, "All require directives must match"),
1093 module AP_MODULE_DECLARE_DATA mod_shib = {
1094 STANDARD20_MODULE_STUFF,
1095 create_shib_dir_config, /* create dir config */
1096 merge_shib_dir_config, /* merge dir config --- default is to override */
1097 create_shib_server_config, /* create server config */
1098 merge_shib_server_config, /* merge server config */
1099 shib_cmds, /* command table */
1100 shib_register_hooks /* register hooks */
1104 #error "undefined APACHE version"