2 * Copyright 2001-2005 Internet2
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 * mod_apache.cpp -- the core Apache Module code
20 * Created by: Derek Atkins <derek@ihtfp.com>
26 #undef _XOPEN_SOURCE // causes gethostname conflict in unistd.h
30 #include <saml/saml.h>
31 #include <shib/shib.h>
32 #include <shib/shib-threads.h>
33 #include <shib-target/shib-target.h>
34 #include <xercesc/util/regx/RegularExpression.hpp>
38 // Apache specific header files
40 #include <http_config.h>
41 #include <http_protocol.h>
42 #include <http_main.h>
44 #include <http_core.h>
47 #ifndef SHIB_APACHE_13
48 #include <http_request.h>
49 #include <apr_strings.h>
50 #include <apr_pools.h>
57 #include <unistd.h> // for getpid()
62 using namespace shibboleth;
63 using namespace shibtarget;
65 extern "C" module MODULE_VAR_EXPORT mod_shib;
68 char* g_szSHIBConfig = NULL;
69 char* g_szSchemaDir = NULL;
70 ShibTargetConfig* g_Config = NULL;
71 static const char* g_UserDataKey = "_shib_check_user_";
74 /********************************************************************************/
75 // Basic Apache Configuration code.
78 // per-server module configuration structure
79 struct shib_server_config
84 // creates the per-server configuration
85 extern "C" void* create_shib_server_config(SH_AP_POOL* p, server_rec* s)
87 shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
92 // overrides server configuration in virtual servers
93 extern "C" void* merge_shib_server_config (SH_AP_POOL* p, void* base, void* sub)
95 shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
96 shib_server_config* parent=(shib_server_config*)base;
97 shib_server_config* child=(shib_server_config*)sub;
100 sc->szScheme=ap_pstrdup(p,child->szScheme);
101 else if (parent->szScheme)
102 sc->szScheme=ap_pstrdup(p,parent->szScheme);
109 // per-dir module configuration structure
110 struct shib_dir_config
113 char* szAuthGrpFile; // Auth GroupFile name
114 int bRequireAll; // all require directives must match, otherwise OR logic
116 // Content Configuration
117 char* szApplicationId; // Shib applicationId value
118 char* szRequireWith; // require a session using a specific initiator?
119 char* szRedirectToSSL; // redirect non-SSL requests to SSL port
120 int bOff; // flat-out disable all Shib processing
121 int bBasicHijack; // activate for AuthType Basic?
122 int bRequireSession; // require a session?
123 int bExportAssertion; // export SAML assertion to the environment?
126 // creates per-directory config structure
127 extern "C" void* create_shib_dir_config (SH_AP_POOL* p, char* d)
129 shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
131 dc->bBasicHijack = -1;
132 dc->bRequireSession = -1;
133 dc->bExportAssertion = -1;
134 dc->bRequireAll = -1;
135 dc->szRedirectToSSL = NULL;
136 dc->szAuthGrpFile = NULL;
137 dc->szApplicationId = NULL;
138 dc->szRequireWith = NULL;
142 // overrides server configuration in directories
143 extern "C" void* merge_shib_dir_config (SH_AP_POOL* p, void* base, void* sub)
145 shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
146 shib_dir_config* parent=(shib_dir_config*)base;
147 shib_dir_config* child=(shib_dir_config*)sub;
149 if (child->szAuthGrpFile)
150 dc->szAuthGrpFile=ap_pstrdup(p,child->szAuthGrpFile);
151 else if (parent->szAuthGrpFile)
152 dc->szAuthGrpFile=ap_pstrdup(p,parent->szAuthGrpFile);
154 dc->szAuthGrpFile=NULL;
156 if (child->szApplicationId)
157 dc->szApplicationId=ap_pstrdup(p,child->szApplicationId);
158 else if (parent->szApplicationId)
159 dc->szApplicationId=ap_pstrdup(p,parent->szApplicationId);
161 dc->szApplicationId=NULL;
163 if (child->szRequireWith)
164 dc->szRequireWith=ap_pstrdup(p,child->szRequireWith);
165 else if (parent->szRequireWith)
166 dc->szRequireWith=ap_pstrdup(p,parent->szRequireWith);
168 dc->szRequireWith=NULL;
170 if (child->szRedirectToSSL)
171 dc->szRedirectToSSL=ap_pstrdup(p,child->szRedirectToSSL);
172 else if (parent->szRedirectToSSL)
173 dc->szRedirectToSSL=ap_pstrdup(p,parent->szRedirectToSSL);
175 dc->szRedirectToSSL=NULL;
177 dc->bOff=((child->bOff==-1) ? parent->bOff : child->bOff);
178 dc->bBasicHijack=((child->bBasicHijack==-1) ? parent->bBasicHijack : child->bBasicHijack);
179 dc->bRequireSession=((child->bRequireSession==-1) ? parent->bRequireSession : child->bRequireSession);
180 dc->bExportAssertion=((child->bExportAssertion==-1) ? parent->bExportAssertion : child->bExportAssertion);
181 dc->bRequireAll=((child->bRequireAll==-1) ? parent->bRequireAll : child->bRequireAll);
185 // generic global slot handlers
186 extern "C" const char* ap_set_global_string_slot(cmd_parms* parms, void*, const char* arg)
188 *((char**)(parms->info))=ap_pstrdup(parms->pool,arg);
192 extern "C" const char* shib_set_server_string_slot(cmd_parms* parms, void*, const char* arg)
194 char* base=(char*)ap_get_module_config(parms->server->module_config,&mod_shib);
195 int offset=(int)parms->info;
196 *((char**)(base + offset))=ap_pstrdup(parms->pool,arg);
200 extern "C" const char* shib_ap_set_file_slot(cmd_parms* parms,
201 #ifdef SHIB_APACHE_13
202 char* arg1, char* arg2
204 void* arg1, const char* arg2
208 ap_set_file_slot(parms, arg1, arg2);
212 /********************************************************************************/
213 // Apache ShibTarget subclass(es) here.
215 class ShibTargetApache : public ShibTarget
218 ShibTargetApache(request_rec* req) {
219 m_sc = (shib_server_config*)ap_get_module_config(req->server->module_config, &mod_shib);
220 m_dc = (shib_dir_config*)ap_get_module_config(req->per_dir_config, &mod_shib);
223 m_sc->szScheme ? m_sc->szScheme : ap_http_method(req),
224 ap_get_server_name(req),
225 (int)ap_get_server_port(req),
227 ap_table_get(req->headers_in, "Content-type"),
228 req->connection->remote_ip,
234 ~ShibTargetApache() { }
236 virtual void log(ShibLogLevel level, const string &msg) {
237 ShibTarget::log(level,msg);
238 #ifdef SHIB_APACHE_13
239 ap_log_rerror(APLOG_MARK,
240 (level == LogLevelDebug ? APLOG_DEBUG :
241 (level == LogLevelInfo ? APLOG_INFO :
242 (level == LogLevelWarn ? APLOG_WARNING : APLOG_ERR)))|APLOG_NOERRNO, SH_AP_R(m_req), msg.c_str());
244 if (level == LogLevelError)
245 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(m_req), msg.c_str());
248 virtual string getCookies(void) const {
249 const char *c = ap_table_get(m_req->headers_in, "Cookie");
250 return string(c ? c : "");
252 virtual void setCookie(const string &name, const string &value) {
253 char* val = ap_psprintf(m_req->pool, "%s=%s", name.c_str(), value.c_str());
254 ap_table_addn(m_req->err_headers_out, "Set-Cookie", val);
256 virtual string getArgs(void) { return string(m_req->args ? m_req->args : ""); }
257 virtual string getPostData(void) {
258 // Read the posted data
259 if (ap_setup_client_block(m_req, REQUEST_CHUNKED_ERROR))
260 throw FatalProfileException("Apache function (setup_client_block) failed while reading profile submission.");
261 if (!ap_should_client_block(m_req))
262 throw FatalProfileException("Apache function (should_client_block) failed while reading profile submission.");
263 if (m_req->remaining > 1024*1024)
264 throw FatalProfileException("Blocked too-large a submission to profile endpoint.");
266 char buff[HUGE_STRING_LEN];
267 ap_hard_timeout("[mod_shib] getPostData", m_req);
268 memset(buff, 0, sizeof(buff));
269 while (ap_get_client_block(m_req, buff, sizeof(buff)-1) > 0) {
270 ap_reset_timeout(m_req);
272 memset(buff, 0, sizeof(buff));
274 ap_kill_timeout(m_req);
278 virtual void clearHeader(const string &name) {
279 ap_table_unset(m_req->headers_in, name.c_str());
281 virtual void setHeader(const string &name, const string &value) {
282 ap_table_set(m_req->headers_in, name.c_str(), value.c_str());
284 virtual string getHeader(const string &name) {
285 const char *hdr = ap_table_get(m_req->headers_in, name.c_str());
286 return string(hdr ? hdr : "");
288 virtual void setRemoteUser(const string &user) {
289 SH_AP_USER(m_req) = ap_pstrdup(m_req->pool, user.c_str());
291 virtual string getRemoteUser(void) {
292 return string(SH_AP_USER(m_req) ? SH_AP_USER(m_req) : "");
294 virtual void* sendPage(
297 const string& content_type="text/html",
298 const Iterator<header_t>& headers=EMPTY(header_t)
300 m_req->content_type = ap_psprintf(m_req->pool, content_type.c_str());
301 while (headers.hasNext()) {
302 const header_t& h=headers.next();
303 ap_table_set(m_req->headers_out, h.first.c_str(), h.second.c_str());
305 ap_send_http_header(m_req);
306 ap_rprintf(m_req, msg.c_str());
307 return (void*)((code==200) ? DONE : code);
309 virtual void* sendRedirect(const string& url) {
310 ap_table_set(m_req->headers_out, "Location", url.c_str());
311 return (void*)REDIRECT;
313 virtual void* returnDecline(void) { return (void*)DECLINED; }
314 virtual void* returnOK(void) { return (void*)OK; }
317 shib_dir_config* m_dc;
318 shib_server_config* m_sc;
321 /********************************************************************************/
324 extern "C" int shib_check_user(request_rec* r)
326 // Short-circuit entirely?
327 if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
330 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_check_user(%d): ENTER\n", (int)getpid());
332 ostringstream threadid;
333 threadid << "[" << getpid() << "] shib_check_user" << '\0';
334 saml::NDC ndc(threadid.str().c_str());
337 ShibTargetApache sta(r);
339 // Check user authentication and export information, then set the handler bypass
340 pair<bool,void*> res = sta.doCheckAuthN(true);
341 apr_pool_userdata_setn((const void*)42,g_UserDataKey,NULL,r->pool);
342 if (res.first) return (int)res.second;
344 // user auth was okay -- export the assertions now
345 res = sta.doExportAssertions();
346 if (res.first) return (int)res.second;
348 // export happened successfully.. this user is ok.
351 catch (SAMLException& e) {
352 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user threw an exception: %s", e.what());
357 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user threw an uncaught exception!");
363 extern "C" int shib_handler(request_rec* r)
365 // Short-circuit entirely?
366 if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
369 ostringstream threadid;
370 threadid << "[" << getpid() << "] shib_handler" << '\0';
371 saml::NDC ndc(threadid.str().c_str());
373 #ifndef SHIB_APACHE_13
374 // With 2.x, this handler always runs, though last.
375 // We check if shib_check_user ran, because it will detect a handler request
376 // and dispatch it directly.
378 apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
379 if (data==(const void*)42) {
380 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler skipped since check_user ran");
385 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler(%d): ENTER: %s", (int)getpid(), r->handler);
388 ShibTargetApache sta(r);
390 pair<bool,void*> res = sta.doHandler();
391 if (res.first) return (int)res.second;
393 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "doHandler() did not do anything.");
396 catch (SAMLException& e) {
397 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler threw an exception: %s", e.what());
402 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler threw an uncaught exception!");
409 * shib_auth_checker() -- a simple resource manager to
410 * process the .htaccess settings
412 extern "C" int shib_auth_checker(request_rec* r)
414 // Short-circuit entirely?
415 if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
418 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_auth_checker(%d): ENTER", (int)getpid());
420 ostringstream threadid;
421 threadid << "[" << getpid() << "] shib_auth_checker" << '\0';
422 saml::NDC ndc(threadid.str().c_str());
425 ShibTargetApache sta(r);
427 pair<bool,void*> res = sta.doCheckAuthZ();
428 if (res.first) return (int)res.second;
433 catch (SAMLException& e) {
434 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an exception: %s", e.what());
439 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an uncaught exception!");
445 // Access control plugin that enforces htaccess rules
446 class htAccessControl : virtual public IAccessControl
450 ~htAccessControl() {}
455 ISessionCacheEntry* entry
459 IPlugIn* htAccessFactory(const DOMElement* e)
461 return new htAccessControl();
464 class ApacheRequestMapper : public virtual IRequestMapper, public virtual IPropertySet
467 ApacheRequestMapper(const DOMElement* e);
468 ~ApacheRequestMapper() { delete m_mapper; delete m_htaccess; delete m_staKey; delete m_propsKey; }
469 void lock() { m_mapper->lock(); }
470 void unlock() { m_staKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
471 Settings getSettings(ShibTarget* st) const;
473 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
474 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
475 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
476 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
477 pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
478 const IPropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
479 const DOMElement* getElement() const;
482 IRequestMapper* m_mapper;
484 ThreadKey* m_propsKey;
485 IAccessControl* m_htaccess;
488 IPlugIn* ApacheRequestMapFactory(const DOMElement* e)
490 return new ApacheRequestMapper(e);
493 ApacheRequestMapper::ApacheRequestMapper(const DOMElement* e) : m_mapper(NULL), m_staKey(NULL), m_propsKey(NULL), m_htaccess(NULL)
495 IPlugIn* p=SAMLConfig::getConfig().getPlugMgr().newPlugin(shibtarget::XML::XMLRequestMapType,e);
496 m_mapper=dynamic_cast<IRequestMapper*>(p);
499 throw UnsupportedExtensionException("Embedded request mapper plugin was not of correct type.");
501 m_htaccess=new htAccessControl();
502 m_staKey=ThreadKey::create(NULL);
503 m_propsKey=ThreadKey::create(NULL);
506 IRequestMapper::Settings ApacheRequestMapper::getSettings(ShibTarget* st) const
508 Settings s=m_mapper->getSettings(st);
509 m_staKey->setData(dynamic_cast<ShibTargetApache*>(st));
510 m_propsKey->setData((void*)s.first);
511 return pair<const IPropertySet*,IAccessControl*>(this,s.second ? s.second : m_htaccess);
514 pair<bool,bool> ApacheRequestMapper::getBool(const char* name, const char* ns) const
516 ShibTargetApache* sta=reinterpret_cast<ShibTargetApache*>(m_staKey->getData());
517 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
519 // Override Apache-settable boolean properties.
520 if (name && !strcmp(name,"requireSession") && sta->m_dc->bRequireSession==1)
521 return make_pair(true,true);
522 else if (name && !strcmp(name,"exportAssertion") && sta->m_dc->bExportAssertion==1)
523 return make_pair(true,true);
525 return s ? s->getBool(name,ns) : make_pair(false,false);
528 pair<bool,const char*> ApacheRequestMapper::getString(const char* name, const char* ns) const
530 ShibTargetApache* sta=reinterpret_cast<ShibTargetApache*>(m_staKey->getData());
531 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
533 // Override Apache-settable string properties.
534 if (name && !strcmp(name,"authType")) {
535 const char *auth_type=ap_auth_type(sta->m_req);
537 // Check for Basic Hijack
538 if (!strcasecmp(auth_type, "basic") && sta->m_dc->bBasicHijack == 1)
539 auth_type = "shibboleth";
540 return make_pair(true,auth_type);
543 else if (name && !strcmp(name,"applicationId") && sta->m_dc->szApplicationId)
544 return pair<bool,const char*>(true,sta->m_dc->szApplicationId);
545 else if (name && !strcmp(name,"requireSessionWith") && sta->m_dc->szRequireWith)
546 return pair<bool,const char*>(true,sta->m_dc->szRequireWith);
547 else if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
548 return pair<bool,const char*>(true,sta->m_dc->szRedirectToSSL);
550 return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
553 pair<bool,const XMLCh*> ApacheRequestMapper::getXMLString(const char* name, const char* ns) const
555 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
556 return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
559 pair<bool,unsigned int> ApacheRequestMapper::getUnsignedInt(const char* name, const char* ns) const
561 ShibTargetApache* sta=reinterpret_cast<ShibTargetApache*>(m_staKey->getData());
562 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
564 // Override Apache-settable int properties.
565 if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
566 return pair<bool,unsigned int>(true,strtol(sta->m_dc->szRedirectToSSL,NULL,10));
568 return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
571 pair<bool,int> ApacheRequestMapper::getInt(const char* name, const char* ns) const
573 ShibTargetApache* sta=reinterpret_cast<ShibTargetApache*>(m_staKey->getData());
574 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
576 // Override Apache-settable int properties.
577 if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
578 return pair<bool,int>(true,atoi(sta->m_dc->szRedirectToSSL));
580 return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
583 const IPropertySet* ApacheRequestMapper::getPropertySet(const char* name, const char* ns) const
585 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
586 return s ? s->getPropertySet(name,ns) : NULL;
589 const DOMElement* ApacheRequestMapper::getElement() const
591 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
592 return s ? s->getElement() : NULL;
595 static SH_AP_TABLE* groups_for_user(request_rec* r, const char* user, char* grpfile)
598 SH_AP_TABLE* grps=ap_make_table(r->pool,15);
599 char l[MAX_STRING_LEN];
600 const char *group_name, *ll, *w;
602 #ifdef SHIB_APACHE_13
603 if (!(f=ap_pcfg_openfile(r->pool,grpfile))) {
605 if (ap_pcfg_openfile(&f,r->pool,grpfile) != APR_SUCCESS) {
607 ap_log_rerror(APLOG_MARK,APLOG_DEBUG,SH_AP_R(r),"groups_for_user() could not open group file: %s\n",grpfile);
612 #ifdef SHIB_APACHE_13
613 sp=ap_make_sub_pool(r->pool);
615 if (apr_pool_create(&sp,r->pool) != APR_SUCCESS) {
616 ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,
617 "groups_for_user() could not create a subpool");
622 while (!(ap_cfg_getline(l,MAX_STRING_LEN,f))) {
623 if ((*l=='#') || (!*l))
628 group_name=ap_getword(sp,&ll,':');
631 w=ap_getword_conf(sp,&ll);
632 if (!strcmp(w,user)) {
633 ap_table_setn(grps,ap_pstrdup(r->pool,group_name),"in");
643 bool htAccessControl::authorized(
645 ISessionCacheEntry* entry
648 // Make sure the object is our type.
649 ShibTargetApache* sta=dynamic_cast<ShibTargetApache*>(st);
651 throw ConfigurationException("Request wrapper object was not of correct type.");
655 int m=sta->m_req->method_number;
656 bool method_restricted=false;
659 const array_header* reqs_arr=ap_requires(sta->m_req);
663 require_line* reqs=(require_line*)reqs_arr->elts;
665 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(sta->m_req),"REQUIRE nelts: %d", reqs_arr->nelts);
666 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(sta->m_req),"REQUIRE all: %d", sta->m_dc->bRequireAll);
668 vector<bool> auth_OK(reqs_arr->nelts,false);
670 #define SHIB_AP_CHECK_IS_OK { \
671 if (sta->m_dc->bRequireAll < 1) \
677 for (int x=0; x<reqs_arr->nelts; x++) {
679 if (!(reqs[x].method_mask & (1 << m)))
681 method_restricted=true;
682 string remote_user = st->getRemoteUser();
684 t = reqs[x].requirement;
685 w = ap_getword_white(sta->m_req->pool, &t);
687 if (!strcasecmp(w,"shibboleth")) {
688 // This is a dummy rule needed because Apache conflates authn and authz.
689 // Without some require rule, AuthType is ignored and no check_user hooks run.
692 else if (!strcmp(w,"valid-user")) {
694 st->log(ShibTarget::LogLevelDebug,"htAccessControl plugin accepting valid-user based on active session");
698 st->log(ShibTarget::LogLevelError,"htAccessControl plugin rejecting access for valid-user rule, no session is active");
700 else if (!strcmp(w,"user") && !remote_user.empty()) {
703 w=ap_getword_conf(sta->m_req->pool,&t);
711 // To do regex matching, we have to convert from UTF-8.
712 auto_ptr<XMLCh> trans(fromUTF8(w));
713 RegularExpression re(trans.get());
714 auto_ptr<XMLCh> trans2(fromUTF8(remote_user.c_str()));
715 if (re.matches(trans2.get())) {
716 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin accepting user (") + w + ")");
720 catch (XMLException& ex) {
721 auto_ptr_char tmp(ex.getMessage());
722 st->log(ShibTarget::LogLevelError,
723 string("htAccessControl plugin caught exception while parsing regular expression (") + w + "): " + tmp.get());
726 else if (remote_user==w) {
727 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin accepting user (") + w + ")");
732 else if (!strcmp(w,"group")) {
733 SH_AP_TABLE* grpstatus=NULL;
734 if (sta->m_dc->szAuthGrpFile && !remote_user.empty()) {
735 st->log(ShibTarget::LogLevelDebug,string("htAccessControl plugin using groups file: ") + sta->m_dc->szAuthGrpFile);
736 grpstatus=groups_for_user(sta->m_req,remote_user.c_str(),sta->m_dc->szAuthGrpFile);
742 w=ap_getword_conf(sta->m_req->pool,&t);
743 if (ap_table_get(grpstatus,w)) {
744 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin accepting group (") + w + ")");
750 Iterator<IAAP*> provs=st->getApplication()->getAAPProviders();
751 AAP wrapper(provs,w);
752 if (wrapper.fail()) {
753 st->log(ShibTarget::LogLevelWarn, string("htAccessControl plugin didn't recognize require rule: ") + w);
758 const char* vals=ap_table_get(sta->m_req->headers_in,wrapper->getHeader());
760 w=ap_getword_conf(sta->m_req->pool,&t);
767 auto_ptr<RegularExpression> re;
770 auto_ptr<XMLCh> trans(fromUTF8(w));
771 auto_ptr<RegularExpression> temp(new RegularExpression(trans.get()));
775 string vals_str(vals);
777 for (unsigned int i = 0; i < vals_str.length(); i++) {
778 if (vals_str.at(i) == ';') {
780 st->log(ShibTarget::LogLevelError, string("htAccessControl plugin found invalid header encoding (") +
781 vals + "): starts with a semicolon");
782 throw SAMLException("Invalid information supplied to authorization plugin.");
785 if (vals_str.at(i-1) == '\\') {
786 vals_str.erase(i-1, 1);
791 string val = vals_str.substr(j, i-j);
794 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
795 if (re->matches(trans.get())) {
796 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
797 ", got " + val + ": authorization granted");
801 else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
802 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
803 ", got " + val + ": authorization granted.");
807 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
808 ", got " + val + ": authoritzation not granted.");
813 string val = vals_str.substr(j, vals_str.length()-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 + ": authorization not granted");
832 catch (XMLException& ex) {
833 auto_ptr_char tmp(ex.getMessage());
834 st->log(ShibTarget::LogLevelError, string("htAccessControl plugin caught exception while parsing regular expression (")
835 + w + "): " + tmp.get());
841 // check if all require directives are true
842 bool auth_all_OK = true;
843 for (int i= 0; i<reqs_arr->nelts; i++) {
844 auth_all_OK &= auth_OK[i];
846 if (auth_all_OK || !method_restricted)
852 #ifndef SHIB_APACHE_13
855 * Empty cleanup hook, Apache 2.x doesn't check NULL very well...
857 extern "C" apr_status_t shib_exit(void* data)
860 g_Config->shutdown();
863 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,0,NULL,"shib_exit() done\n");
871 * Cleanup the (per-process) pool info.
873 #ifdef SHIB_APACHE_13
874 extern "C" void shib_child_exit(server_rec* s, SH_AP_POOL* p)
877 extern "C" apr_status_t shib_child_exit(void* data)
879 server_rec* s = NULL;
882 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit(%d) dealing with g_Config..", (int)getpid());
883 g_Config->shutdown();
885 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit() done\n");
887 #ifndef SHIB_APACHE_13
894 * Things to do when the child process is initialized.
895 * (or after the configs are read in apache-2)
897 #ifdef SHIB_APACHE_13
898 extern "C" void shib_child_init(server_rec* s, SH_AP_POOL* p)
900 extern "C" void shib_child_init(apr_pool_t* p, server_rec* s)
903 // Initialize runtime components.
905 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init(%d) starting", (int)getpid());
908 ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() already initialized!");
913 g_Config=&ShibTargetConfig::getConfig();
914 g_Config->setFeatures(
915 ShibTargetConfig::Listener |
916 ShibTargetConfig::Metadata |
917 ShibTargetConfig::AAP |
918 ShibTargetConfig::RequestMapper |
919 ShibTargetConfig::LocalExtensions |
920 ShibTargetConfig::Logging
922 if (!g_Config->init(g_szSchemaDir)) {
923 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize libraries");
926 SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::htAccessControlType,&htAccessFactory);
927 SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::NativeRequestMapType,&ApacheRequestMapFactory);
928 // We hijack the legacy type so that 1.2 config files will load this plugin
929 SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::LegacyRequestMapType,&ApacheRequestMapFactory);
931 if (!g_Config->load(g_szSHIBConfig)) {
932 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to load configuration");
937 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize system");
941 // Set the cleanup handler
942 apr_pool_cleanup_register(p, NULL, &shib_exit, &shib_child_exit);
944 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() done");
947 typedef const char* (*config_fn_t)(void);
949 #ifdef SHIB_APACHE_13
951 // SHIB Module commands
953 static command_rec shire_cmds[] = {
954 {"SHIREConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
955 RSRC_CONF, TAKE1, "Path to shibboleth.xml config file"},
956 {"ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
957 RSRC_CONF, TAKE1, "Path to shibboleth.xml config file"},
958 {"ShibSchemaDir", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
959 RSRC_CONF, TAKE1, "Path to Shibboleth XML schema directory"},
961 {"ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
962 (void *) XtOffsetOf (shib_server_config, szScheme),
963 RSRC_CONF, TAKE1, "URL scheme to force into generated URLs for a vhost"},
965 {"ShibDisable", (config_fn_t)ap_set_flag_slot,
966 (void *) XtOffsetOf (shib_dir_config, bOff),
967 OR_AUTHCFG, FLAG, "Disable all Shib module activity here to save processing effort"},
968 {"ShibApplicationId", (config_fn_t)ap_set_string_slot,
969 (void *) XtOffsetOf (shib_dir_config, szApplicationId),
970 OR_AUTHCFG, TAKE1, "Set Shibboleth applicationId property for content"},
971 {"ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
972 (void *) XtOffsetOf (shib_dir_config, bBasicHijack),
973 OR_AUTHCFG, FLAG, "Respond to AuthType Basic and convert to shibboleth"},
974 {"ShibRequireSession", (config_fn_t)ap_set_flag_slot,
975 (void *) XtOffsetOf (shib_dir_config, bRequireSession),
976 OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist"},
977 {"ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
978 (void *) XtOffsetOf (shib_dir_config, szRequireWith),
979 OR_AUTHCFG, TAKE1, "Initiates a new session if one does not exist using a specific SessionInitiator"},
980 {"ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
981 (void *) XtOffsetOf (shib_dir_config, bExportAssertion),
982 OR_AUTHCFG, FLAG, "Export SAML attribute assertion(s) to Shib-Attributes header"},
983 {"ShibRedirectToSSL", (config_fn_t)ap_set_string_slot,
984 (void *) XtOffsetOf (shib_dir_config, szRedirectToSSL),
985 OR_AUTHCFG, TAKE1, "Redirect non-SSL requests to designated port" },
986 {"AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
987 (void *) XtOffsetOf (shib_dir_config, szAuthGrpFile),
988 OR_AUTHCFG, TAKE1, "text file containing group names and member user IDs"},
989 {"ShibRequireAll", (config_fn_t)ap_set_flag_slot,
990 (void *) XtOffsetOf (shib_dir_config, bRequireAll),
991 OR_AUTHCFG, FLAG, "All require directives must match"},
997 handler_rec shib_handlers[] = {
998 { "shib-handler", shib_handler },
1002 module MODULE_VAR_EXPORT mod_shib = {
1003 STANDARD_MODULE_STUFF,
1004 NULL, /* initializer */
1005 create_shib_dir_config, /* dir config creater */
1006 merge_shib_dir_config, /* dir merger --- default is to override */
1007 create_shib_server_config, /* server config */
1008 merge_shib_server_config, /* merge server config */
1009 shire_cmds, /* command table */
1010 shib_handlers, /* handlers */
1011 NULL, /* filename translation */
1012 shib_check_user, /* check_user_id */
1013 shib_auth_checker, /* check auth */
1014 NULL, /* check access */
1015 NULL, /* type_checker */
1018 NULL, /* header parser */
1019 shib_child_init, /* child_init */
1020 shib_child_exit, /* child_exit */
1021 NULL /* post read-request */
1024 #elif defined(SHIB_APACHE_20)
1026 extern "C" void shib_register_hooks (apr_pool_t *p)
1028 ap_hook_child_init(shib_child_init, NULL, NULL, APR_HOOK_MIDDLE);
1029 ap_hook_check_user_id(shib_check_user, NULL, NULL, APR_HOOK_MIDDLE);
1030 ap_hook_auth_checker(shib_auth_checker, NULL, NULL, APR_HOOK_FIRST);
1031 ap_hook_handler(shib_handler, NULL, NULL, APR_HOOK_LAST);
1034 // SHIB Module commands
1037 static command_rec shib_cmds[] = {
1038 AP_INIT_TAKE1("ShibConfig",
1039 (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1040 RSRC_CONF, "Path to shibboleth.xml config file"),
1041 AP_INIT_TAKE1("ShibSchemaDir",
1042 (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1043 RSRC_CONF, "Path to Shibboleth XML schema directory"),
1045 AP_INIT_TAKE1("ShibURLScheme",
1046 (config_fn_t)shib_set_server_string_slot,
1047 (void *) offsetof (shib_server_config, szScheme),
1048 RSRC_CONF, "URL scheme to force into generated URLs for a vhost"),
1050 AP_INIT_FLAG("ShibDisable", (config_fn_t)ap_set_flag_slot,
1051 (void *) offsetof (shib_dir_config, bOff),
1052 OR_AUTHCFG, "Disable all Shib module activity here to save processing effort"),
1053 AP_INIT_TAKE1("ShibApplicationId", (config_fn_t)ap_set_string_slot,
1054 (void *) offsetof (shib_dir_config, szApplicationId),
1055 OR_AUTHCFG, "Set Shibboleth applicationId property for content"),
1056 AP_INIT_FLAG("ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1057 (void *) offsetof (shib_dir_config, bBasicHijack),
1058 OR_AUTHCFG, "Respond to AuthType Basic and convert to shibboleth"),
1059 AP_INIT_FLAG("ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1060 (void *) offsetof (shib_dir_config, bRequireSession),
1061 OR_AUTHCFG, "Initiates a new session if one does not exist"),
1062 AP_INIT_TAKE1("ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
1063 (void *) offsetof (shib_dir_config, szRequireWith),
1064 OR_AUTHCFG, "Initiates a new session if one does not exist using a specific SessionInitiator"),
1065 AP_INIT_FLAG("ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1066 (void *) offsetof (shib_dir_config, bExportAssertion),
1067 OR_AUTHCFG, "Export SAML attribute assertion(s) to Shib-Attributes header"),
1068 AP_INIT_TAKE1("ShibRedirectToSSL", (config_fn_t)ap_set_string_slot,
1069 (void *) offsetof (shib_dir_config, szRedirectToSSL),
1070 OR_AUTHCFG, "Redirect non-SSL requests to designated port"),
1071 AP_INIT_TAKE1("AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
1072 (void *) offsetof (shib_dir_config, szAuthGrpFile),
1073 OR_AUTHCFG, "Text file containing group names and member user IDs"),
1074 AP_INIT_FLAG("ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1075 (void *) offsetof (shib_dir_config, bRequireAll),
1076 OR_AUTHCFG, "All require directives must match"),
1081 module AP_MODULE_DECLARE_DATA mod_shib = {
1082 STANDARD20_MODULE_STUFF,
1083 create_shib_dir_config, /* create dir config */
1084 merge_shib_dir_config, /* merge dir config --- default is to override */
1085 create_shib_server_config, /* create server config */
1086 merge_shib_server_config, /* merge server config */
1087 shib_cmds, /* command table */
1088 shib_register_hooks /* register hooks */
1092 #error "undefined APACHE version"