2 * mod_apache.cpp -- the core Apache Module code
4 * Created by: Derek Atkins <derek@ihtfp.com>
10 #undef _XOPEN_SOURCE // causes gethostname conflict in unistd.h
14 #include <saml/saml.h>
15 #include <shib/shib.h>
16 #include <shib/shib-threads.h>
17 #include <shib-target/shib-target.h>
18 #include <xercesc/util/regx/RegularExpression.hpp>
22 // Apache specific header files
24 #include <http_config.h>
25 #include <http_protocol.h>
26 #include <http_main.h>
28 #include <http_core.h>
31 #ifndef SHIB_APACHE_13
32 #include <http_request.h>
33 #include <apr_strings.h>
34 #include <apr_pools.h>
41 #include <unistd.h> // for getpid()
46 using namespace shibboleth;
47 using namespace shibtarget;
49 extern "C" module MODULE_VAR_EXPORT mod_shib;
51 int shib_handler(request_rec* r, const IApplication* application, SHIRE& shire);
55 char* g_szSHIBConfig = NULL;
56 char* g_szSchemaDir = NULL;
57 ShibTargetConfig* g_Config = NULL;
58 static const char* g_UserDataKey = "_shib_check_user_";
61 /********************************************************************************/
62 // Basic Apache Configuration code.
65 // per-server module configuration structure
66 struct shib_server_config
71 // creates the per-server configuration
72 extern "C" void* create_shib_server_config(SH_AP_POOL* p, server_rec* s)
74 shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
79 // overrides server configuration in virtual servers
80 extern "C" void* merge_shib_server_config (SH_AP_POOL* p, void* base, void* sub)
82 shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
83 shib_server_config* parent=(shib_server_config*)base;
84 shib_server_config* child=(shib_server_config*)sub;
87 sc->szScheme=ap_pstrdup(p,child->szScheme);
88 else if (parent->szScheme)
89 sc->szScheme=ap_pstrdup(p,parent->szScheme);
96 // per-dir module configuration structure
97 struct shib_dir_config
100 char* szAuthGrpFile; // Auth GroupFile name
101 int bRequireAll; // all require directives must match, otherwise OR logic
103 // SHIRE Configuration
104 int bBasicHijack; // activate for AuthType Basic?
105 int bRequireSession; // require a session?
106 int bExportAssertion; // export SAML assertion to the environment?
109 // creates per-directory config structure
110 extern "C" void* create_shib_dir_config (SH_AP_POOL* p, char* d)
112 shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
113 dc->bBasicHijack = -1;
114 dc->bRequireSession = -1;
115 dc->bExportAssertion = -1;
116 dc->bRequireAll = -1;
117 dc->szAuthGrpFile = NULL;
121 // overrides server configuration in directories
122 extern "C" void* merge_shib_dir_config (SH_AP_POOL* p, void* base, void* sub)
124 shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
125 shib_dir_config* parent=(shib_dir_config*)base;
126 shib_dir_config* child=(shib_dir_config*)sub;
128 if (child->szAuthGrpFile)
129 dc->szAuthGrpFile=ap_pstrdup(p,child->szAuthGrpFile);
130 else if (parent->szAuthGrpFile)
131 dc->szAuthGrpFile=ap_pstrdup(p,parent->szAuthGrpFile);
133 dc->szAuthGrpFile=NULL;
135 dc->bBasicHijack=((child->bBasicHijack==-1) ? parent->bBasicHijack : child->bBasicHijack);
136 dc->bRequireSession=((child->bRequireSession==-1) ? parent->bRequireSession : child->bRequireSession);
137 dc->bExportAssertion=((child->bExportAssertion==-1) ? parent->bExportAssertion : child->bExportAssertion);
138 dc->bRequireAll=((child->bRequireAll==-1) ? parent->bRequireAll : child->bRequireAll);
142 // generic global slot handlers
143 extern "C" const char* ap_set_global_string_slot(cmd_parms* parms, void*, const char* arg)
145 *((char**)(parms->info))=ap_pstrdup(parms->pool,arg);
149 extern "C" const char* shib_set_server_string_slot(cmd_parms* parms, void*, const char* arg)
151 char* base=(char*)ap_get_module_config(parms->server->module_config,&mod_shib);
152 int offset=(int)parms->info;
153 *((char**)(base + offset))=ap_pstrdup(parms->pool,arg);
157 extern "C" const char* shib_ap_set_file_slot(cmd_parms* parms,
158 #ifdef SHIB_APACHE_13
159 char* arg1, char* arg2
161 void* arg1, const char* arg2
165 ap_set_file_slot(parms, arg1, arg2);
169 /********************************************************************************/
170 // Some other useful helper function(s)
172 static SH_AP_TABLE* groups_for_user(request_rec* r, const char* user, char* grpfile)
175 SH_AP_TABLE* grps=ap_make_table(r->pool,15);
176 char l[MAX_STRING_LEN];
177 const char *group_name, *ll, *w;
179 #ifdef SHIB_APACHE_13
180 if (!(f=ap_pcfg_openfile(r->pool,grpfile))) {
182 if (ap_pcfg_openfile(&f,r->pool,grpfile) != APR_SUCCESS) {
184 ap_log_rerror(APLOG_MARK,APLOG_DEBUG,SH_AP_R(r),"groups_for_user() could not open group file: %s\n",grpfile);
189 #ifdef SHIB_APACHE_13
190 sp=ap_make_sub_pool(r->pool);
192 if (apr_pool_create(&sp,r->pool) != APR_SUCCESS) {
193 ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,
194 "groups_for_user() could not create a subpool");
199 while (!(ap_cfg_getline(l,MAX_STRING_LEN,f))) {
200 if ((*l=='#') || (!*l))
205 group_name=ap_getword(sp,&ll,':');
208 w=ap_getword_conf(sp,&ll);
209 if (!strcmp(w,user)) {
210 ap_table_setn(grps,ap_pstrdup(r->pool,group_name),"in");
220 /********************************************************************************/
221 // Apache ShibTarget subclass(es) here.
223 class HTGroupTableApache : public HTGroupTable
226 HTGroupTableApache(request_rec* r, const char *user, char *grpfile) {
227 groups = groups_for_user(r, user, grpfile);
229 throw ShibTargetException(SHIBRPC_OK, "EEP");
231 ~HTGroupTableApache() {}
232 bool lookup(const char *entry) { return (ap_table_get(groups, entry)!=NULL); }
236 class ShibTargetApache : public ShibTarget
239 ShibTargetApache(request_rec* req) {
240 m_sc = (shib_server_config*)
241 ap_get_module_config(req->server->module_config, &mod_shib);
243 m_dc = (shib_dir_config*)ap_get_module_config(req->per_dir_config, &mod_shib);
245 const char* ct = ap_table_get(req->headers_in, "Content-type");
247 init(g_Config, string(m_sc->szScheme ? m_sc->szScheme : ap_http_method(req)),
248 string(ap_get_server_name(req)), (int)ap_get_server_port(req),
249 string(req->unparsed_uri), string(ct ? ct : ""),
250 string(req->connection->remote_ip), string(req->method));
254 ~ShibTargetApache() { }
256 virtual void log(ShibLogLevel level, const string &msg) {
257 ap_log_rerror(APLOG_MARK,
258 (level == LogLevelDebug ? APLOG_DEBUG :
259 (level == LogLevelInfo ? APLOG_INFO :
260 (level == LogLevelWarn ? APLOG_WARNING :
261 APLOG_ERR)))|APLOG_NOERRNO, SH_AP_R(m_req),
264 virtual string getCookies(void) {
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_setn(m_req->err_headers_out, "Set-Cookie", val);
272 virtual string getArgs(void) { return string(m_req->args ? m_req->args : ""); }
273 virtual string getPostData(void) {
274 // Read the posted data
275 if (ap_setup_client_block(m_req, REQUEST_CHUNKED_ERROR))
276 throw ShibTargetException(SHIBRPC_OK, "CGI setup_client_block failed");
277 if (!ap_should_client_block(m_req))
278 throw ShibTargetException(SHIBRPC_OK, "CGI should_client_block failed");
279 if (m_req->remaining > 1024*1024)
280 throw ShibTargetException (SHIBRPC_OK, "CGI length too long...");
283 char buff[HUGE_STRING_LEN];
284 ap_hard_timeout("[mod_shib] getPostData", m_req);
285 memset(buff, 0, sizeof(buff));
286 while (ap_get_client_block(m_req, buff, sizeof(buff)-1) > 0) {
287 ap_reset_timeout(m_req);
289 memset(buff, 0, sizeof(buff));
291 ap_kill_timeout(m_req);
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 // override so we can look at the actual auth type and maybe override it.
312 virtual string getAuthType(void) {
313 const char *auth_type=ap_auth_type(m_req);
316 if (strcasecmp(auth_type, "shibboleth")) {
317 if (!strcasecmp(auth_type, "basic") && m_dc->bBasicHijack == 1) {
318 core_dir_config* conf= (core_dir_config*)
319 ap_get_module_config(m_req->per_dir_config,
320 ap_find_linked_module("http_core.c"));
321 auth_type = conf->ap_auth_type = "shibboleth";
324 return string(auth_type);
326 // Override this function because we want to add the Apache Directory override
327 virtual pair<bool,bool> getRequireSession(IRequestMapper::Settings &settings) {
328 pair<bool,bool> requireSession = settings.first->getBool("requireSession");
329 if (!requireSession.first || !requireSession.second)
330 if (m_dc->bRequireSession == 1)
331 requireSession.second=true;
333 return requireSession;
336 virtual HTAccessInfo* getAccessInfo(void) {
337 int m = m_req->method_number;
338 const array_header* reqs_arr = ap_requires(m_req);
342 require_line* reqs = (require_line*) reqs_arr->elts;
344 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req),
345 "REQUIRE nelts: %d", reqs_arr->nelts);
346 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req),
347 "REQUIRE all: %d", m_dc->bRequireAll);
349 HTAccessInfo* ht = new HTAccessInfo();
350 ht->requireAll = (m_dc->bRequireAll >= 0);
351 ht->elements.reserve(reqs_arr->nelts);
352 for (int x = 0; x < reqs_arr->nelts; x++) {
353 HTAccessInfo::RequireLine* rline = new HTAccessInfo::RequireLine();
354 rline->use_line = (reqs[x].method_mask & (1 << m));
355 rline->tokens.reserve(6); // No reason to reserve specifically 6 tokens
356 const char* t = reqs[x].requirement;
357 const char* w = ap_getword_white(m_req->pool, &t);
358 rline->tokens.push_back(w);
360 w = ap_getword_conf(m_req->pool, &t);
361 rline->tokens.push_back(w);
363 ht->elements.push_back(rline);
367 virtual HTGroupTable* getGroupTable(string &user) {
368 if (m_dc->szAuthGrpFile && !user.empty()) {
369 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req),
370 "getGroupTable() using groups file: %s\n",
371 m_dc->szAuthGrpFile);
373 HTGroupTableApache *gt = new HTGroupTableApache(m_req, user.c_str(),
374 m_dc->szAuthGrpFile);
381 virtual void* sendPage(
383 const string content_type,
384 const saml::Iterator<header_t>& headers=EMPTY(header_t),
387 m_req->content_type = ap_psprintf(m_req->pool, content_type.c_str());
388 while (headers.hasNext()) {
389 const header_t& h=headers.next();
390 ap_table_setn(m_req->headers_out, h.first.c_str(), h.second.c_str());
392 ap_send_http_header(m_req);
393 ap_rprintf(m_req, msg.c_str());
396 virtual void* sendRedirect(const string url) {
397 ap_table_set(m_req->headers_out, "Location", url.c_str());
398 return (void*)REDIRECT;
400 virtual void* returnDecline(void) { return (void*)DECLINED; }
401 virtual void* returnOK(void) { return (void*)OK; }
404 shib_dir_config* m_dc;
405 shib_server_config* m_sc;
408 /********************************************************************************/
411 extern "C" int shib_check_user(request_rec* r)
413 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
414 "shib_check_user(%d): ENTER\n", (int)getpid());
416 ostringstream threadid;
417 threadid << "[" << getpid() << "] shib_check_user" << '\0';
418 saml::NDC ndc(threadid.str().c_str());
423 ShibTargetApache sta(r);
425 // Check user authentication, the set the post handler bypass
426 pair<bool,void*> res = sta.doCheckAuthN((sta.m_dc->bRequireSession == 1), true);
427 apr_pool_userdata_setn((const void*)42,g_UserDataKey,NULL,r->pool);
428 if (res.first) return (int)res.second;
430 // user auth was okay -- export the assertions now
431 res = sta.doExportAssertions((sta.m_dc->bExportAssertion == 1));
432 if (res.first) return (int)res.second;
434 // export happened successfully.. this user is ok.
439 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r),
440 "shib_check_user threw an uncaught exception!");
446 extern "C" int shib_post_handler(request_rec* r)
448 ostringstream threadid;
449 threadid << "[" << getpid() << "] shib_post_handler" << '\0';
450 saml::NDC ndc(threadid.str().c_str());
452 #ifndef SHIB_APACHE_13
453 // With 2.x, this handler always runs, though last.
454 // We check if shib_check_user ran, because it will detect a SHIRE request
455 // and dispatch it directly.
457 apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
458 if (data==(const void*)42) {
459 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_post_handler skipped since check_user ran");
464 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
465 "shib_post_handler(%d): ENTER", (int)getpid());
470 ShibTargetApache sta(r);
472 pair<bool,void*> res = sta.doHandleProfile();
473 if (res.first) return (int)res.second;
475 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r),
476 "doHandleProfile() did not do anything.");
481 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r),
482 "shib_post_handler threw an uncaught exception!");
489 * shib_auth_checker() -- a simple resource manager to
490 * process the .htaccess settings and copy attributes
491 * into the HTTP headers.
493 extern "C" int shib_auth_checker(request_rec* r)
495 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
496 "shib_check_user(%d): ENTER", (int)getpid());
498 ostringstream threadid;
499 threadid << "[" << getpid() << "] shib_auth_checker" << '\0';
500 saml::NDC ndc(threadid.str().c_str());
505 ShibTargetApache sta(r);
507 pair<bool,void*> res = sta.doCheckAuthZ();
508 if (res.first) return (int)res.second;
515 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r),
516 "shib_auth_checker threw an uncaught exception!");
523 static char* shib_get_targeturl(request_rec* r, const char* scheme=NULL)
525 // On 1.3, this is always canonical, but on 2.0, UseCanonicalName comes into play.
526 // However, we also have a setting to forcibly replace the scheme for esoteric cases.
528 unsigned port = ap_get_server_port(r);
529 if ((!strcmp(scheme,"http") && port==80) || (!strcmp(scheme,"https") && port==443)) {
530 return ap_pstrcat(r->pool, scheme, "://", ap_get_server_name(r), r->unparsed_uri, NULL);
532 return ap_psprintf(r->pool, "%s://%s:%u%s", scheme, ap_get_server_name(r), port, r->unparsed_uri);
534 return ap_construct_url(r->pool,r->unparsed_uri,r);
537 extern "C" int shib_check_user(request_rec* r)
539 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: ENTER");
540 shib_dir_config* dc=(shib_dir_config*)ap_get_module_config(r->per_dir_config,&mod_shib);
541 shib_server_config* sc=(shib_server_config*)ap_get_module_config(r->server->module_config,&mod_shib);
543 ostringstream threadid;
544 threadid << "[" << getpid() << "] shib_check_user" << '\0';
545 saml::NDC ndc(threadid.str().c_str());
547 const char* targeturl=shib_get_targeturl(r,sc->szScheme);
549 // We lock the configuration system for the duration.
550 IConfig* conf=g_Config->getINI();
553 // Map request to application and content settings.
554 IRequestMapper* mapper=conf->getRequestMapper();
555 Locker locker2(mapper);
556 IRequestMapper::Settings settings=mapper->getSettingsFromParsedURL(
557 (sc-> szScheme ? sc-> szScheme : ap_http_method(r)), ap_get_server_name(r), ap_get_server_port(r), r->unparsed_uri
559 pair<bool,const char*> application_id=settings.first->getString("applicationId");
560 const IApplication* application=conf->getApplication(application_id.second);
562 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
563 "shib_check_user: unable to map request to application settings, check configuration");
567 // Declare SHIRE object for this request.
568 SHIRE shire(application);
570 const char* shireURL=shire.getShireURL(targeturl);
572 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
573 "shib_check_user: unable to map request to proper shireURL setting, check configuration");
577 // Get location of this application's assertion consumer service and see if this is it.
578 if (strstr(targeturl,shireURL)) {
579 return shib_handler(r,application,shire);
582 // We can short circuit the handler if we run this...
583 apr_pool_userdata_setn((const void*)42,g_UserDataKey,NULL,r->pool);
585 // Regular access to arbitrary resource...check AuthType
586 const char *auth_type=ap_auth_type(r);
590 if (strcasecmp(auth_type,"shibboleth")) {
591 if (!strcasecmp(auth_type,"basic") && dc->bBasicHijack==1) {
592 core_dir_config* conf=
593 (core_dir_config*)ap_get_module_config(r->per_dir_config,
594 ap_find_linked_module("http_core.c"));
595 conf->ap_auth_type="shibboleth";
601 pair<bool,bool> requireSession = settings.first->getBool("requireSession");
602 if (!requireSession.first || !requireSession.second)
603 if (dc->bRequireSession==1)
604 requireSession.second=true;
606 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: session check for %s",targeturl);
608 pair<const char*,const char*> shib_cookie=shire.getCookieNameProps(); // always returns *something*
610 // We're in charge, so check for cookie.
611 const char* session_id=NULL;
612 const char* cookies=ap_table_get(r->headers_in,"Cookie");
615 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: cookies found: %s",cookies);
616 if (session_id=strstr(cookies,shib_cookie.first)) {
617 // Yep, we found a cookie -- pull it out (our session_id)
618 session_id+=strlen(shib_cookie.first) + 1; /* Skip over the '=' */
619 char* cookiebuf = ap_pstrdup(r->pool,session_id);
620 char* cookieend = strchr(cookiebuf,';');
622 *cookieend = '\0'; /* Ignore anyting after a ; */
623 session_id=cookiebuf;
627 if (!session_id || !*session_id) {
628 // If no session required, bail now.
629 if (!requireSession.second)
632 // No acceptable cookie, and we require a session. Generate an AuthnRequest.
633 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: no cookie found -- redirecting to WAYF");
634 ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(targeturl)));
638 // Make sure this session is still valid.
639 RPCError* status = NULL;
640 ShibMLP markupProcessor;
641 markupProcessor.insert("requestURL", targeturl);
644 status = shire.sessionIsValid(session_id, r->connection->remote_ip);
646 catch (ShibTargetException &e) {
647 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): %s", e.what());
648 markupProcessor.insert("errorType", "Session Processing Error");
649 markupProcessor.insert("errorText", e.what());
650 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
651 return shib_error_page(r, application, "shire", markupProcessor);
655 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): caught unexpected error");
656 markupProcessor.insert("errorType", "Session Processing Error");
657 markupProcessor.insert("errorText", "Unexpected Exception");
658 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
659 return shib_error_page(r, application, "shire", markupProcessor);
664 if (status->isError()) {
665 ap_log_rerror(APLOG_MARK,APLOG_INFO|APLOG_NOERRNO,SH_AP_R(r),
666 "shib_check_user() session invalid: %s", status->getText());
668 // If no session required, bail now.
669 if (!requireSession.second)
670 return OK; // XXX: Or should this be DECLINED?
671 // Has to be OK because DECLINED will just cause Apache to fail when it can't locate
672 // anything to process the AuthType. No session plus requireSession false means
673 // do not authenticate the user.
674 else if (status->isRetryable()) {
675 // Oops, session is invalid. Generate AuthnRequest.
676 ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(targeturl)));
681 // return the error page to the user
682 markupProcessor.insert(*status);
684 return shib_error_page(r, application, "shire", markupProcessor);
690 #ifdef SHIB_APACHE_13
692 r->connection->ap_auth_type = "shibboleth";
694 r->ap_auth_type = "shibboleth";
696 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: session successfully verified");
698 // This is code transferred in from the auth check to export the attributes.
699 // We could even combine the isSessionValid/getAssertions API...?
702 vector<SAMLAssertion*> assertions;
703 SAMLAuthenticationStatement* sso_statement=NULL;
706 status = rm.getAssertions(session_id, r->connection->remote_ip, assertions, &sso_statement);
708 catch (ShibTargetException &e) {
709 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): %s", e.what());
710 markupProcessor.insert("errorType", "Attribute Processing Error");
711 markupProcessor.insert("errorText", e.what());
712 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
713 return shib_error_page(r, application, "rm", markupProcessor);
717 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): caught unexpected error");
718 markupProcessor.insert("errorType", "Attribute Processing Error");
719 markupProcessor.insert("errorText", "Unexpected Exception");
720 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
721 return shib_error_page(r, application, "rm", markupProcessor);
725 if (status->isError()) {
726 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
727 "shib_check_user() getAssertions failed: %s", status->getText());
729 markupProcessor.insert(*status);
731 return shib_error_page(r, application, "rm", markupProcessor);
735 // Do we have an access control plugin?
736 if (settings.second) {
737 Locker acllock(settings.second);
738 if (!settings.second->authorized(*sso_statement,assertions)) {
739 for (int k = 0; k < assertions.size(); k++)
740 delete assertions[k];
741 delete sso_statement;
742 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): access control provider denied access");
743 return shib_error_page(r, application, "access", markupProcessor);
747 // Get the AAP providers, which contain the attribute policy info.
748 Iterator<IAAP*> provs=application->getAAPProviders();
750 // Clear out the list of mapped attributes
751 while (provs.hasNext()) {
752 IAAP* aap=provs.next();
755 Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
756 while (rules.hasNext()) {
757 const char* header=rules.next()->getHeader();
759 ap_table_unset(r->headers_in,header);
764 for (int k = 0; k < assertions.size(); k++)
765 delete assertions[k];
766 delete sso_statement;
767 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
768 "shib_check_user(): caught unexpected error while clearing headers");
769 markupProcessor.insert("errorType", "Attribute Processing Error");
770 markupProcessor.insert("errorText", "Unexpected Exception");
771 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
772 return shib_error_page(r, application, "rm", markupProcessor);
778 // Maybe export the first assertion.
779 ap_table_unset(r->headers_in,"Shib-Attributes");
780 pair<bool,bool> exp=settings.first->getBool("exportAssertion");
781 if (!exp.first || !exp.second)
782 if (dc->bExportAssertion==1)
784 if (exp.second && assertions.size()) {
786 RM::serialize(*(assertions[0]), assertion);
787 ap_table_set(r->headers_in,"Shib-Attributes", assertion.c_str());
790 // Export the SAML AuthnMethod and the origin site name, and possibly the NameIdentifier.
791 ap_table_unset(r->headers_in,"Shib-Origin-Site");
792 ap_table_unset(r->headers_in,"Shib-Authentication-Method");
793 ap_table_unset(r->headers_in,"Shib-NameIdentifier-Format");
794 auto_ptr_char os(sso_statement->getSubject()->getNameIdentifier()->getNameQualifier());
795 auto_ptr_char am(sso_statement->getAuthMethod());
796 ap_table_set(r->headers_in,"Shib-Origin-Site", os.get());
797 ap_table_set(r->headers_in,"Shib-Authentication-Method", am.get());
800 AAP wrapper(provs,sso_statement->getSubject()->getNameIdentifier()->getFormat(),Constants::SHIB_ATTRIBUTE_NAMESPACE_URI);
801 if (!wrapper.fail() && wrapper->getHeader()) {
802 auto_ptr_char form(sso_statement->getSubject()->getNameIdentifier()->getFormat());
803 auto_ptr_char nameid(sso_statement->getSubject()->getNameIdentifier()->getName());
804 ap_table_set(r->headers_in,"Shib-NameIdentifier-Format",form.get());
805 if (!strcmp(wrapper->getHeader(),"REMOTE_USER"))
806 SH_AP_USER(r)=ap_pstrdup(r->pool,nameid.get());
808 ap_table_set(r->headers_in,wrapper->getHeader(),nameid.get());
811 ap_table_unset(r->headers_in,"Shib-Application-ID");
812 ap_table_set(r->headers_in,"Shib-Application-ID",application_id.second);
814 // Export the attributes.
815 Iterator<SAMLAssertion*> a_iter(assertions);
816 while (a_iter.hasNext()) {
817 SAMLAssertion* assert=a_iter.next();
818 Iterator<SAMLStatement*> statements=assert->getStatements();
819 while (statements.hasNext()) {
820 SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());
823 Iterator<SAMLAttribute*> attrs=astate->getAttributes();
824 while (attrs.hasNext()) {
825 SAMLAttribute* attr=attrs.next();
827 // Are we supposed to export it?
828 AAP wrapper(provs,attr->getName(),attr->getNamespace());
829 if (wrapper.fail() || !wrapper->getHeader())
832 Iterator<string> vals=attr->getSingleByteValues();
833 if (!strcmp(wrapper->getHeader(),"REMOTE_USER") && vals.hasNext())
834 SH_AP_USER(r)=ap_pstrdup(r->pool,vals.next().c_str());
837 char* header = (char*)ap_table_get(r->headers_in, wrapper->getHeader());
839 header=ap_pstrdup(r->pool, header);
843 header = ap_pstrdup(r->pool, "");
844 for (; vals.hasNext(); it++) {
845 string value = vals.next();
846 for (string::size_type pos = value.find_first_of(";", string::size_type(0));
848 pos = value.find_first_of(";", pos)) {
849 value.insert(pos, "\\");
852 header=ap_pstrcat(r->pool, header, (it ? ";" : ""), value.c_str(), NULL);
854 ap_table_setn(r->headers_in, wrapper->getHeader(), header);
861 for (int k = 0; k < assertions.size(); k++)
862 delete assertions[k];
863 delete sso_statement;
868 extern "C" int shib_post_handler(request_rec* r)
870 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
871 "shib_post_handler(%d): ENTER", (int)getpid());
872 shib_server_config* sc=(shib_server_config*)ap_get_module_config(r->server->module_config,&mod_shib);
874 #ifndef SHIB_APACHE_13
875 // With 2.x, this handler always runs, though last.
876 // We check if shib_check_user ran, because it will detect a SHIRE request
877 // and dispatch it directly.
879 apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
880 if (data==(const void*)42) {
881 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_post_handler skipped since check_user ran");
886 ostringstream threadid;
887 threadid << "[" << getpid() << "] shib_post_handler" << '\0';
888 saml::NDC ndc(threadid.str().c_str());
890 // We lock the configuration system for the duration.
891 IConfig* conf=g_Config->getINI();
894 // Map request to application and content settings.
895 IRequestMapper* mapper=conf->getRequestMapper();
896 Locker locker2(mapper);
897 IRequestMapper::Settings settings=mapper->getSettingsFromParsedURL(
898 (sc->szScheme ? sc->szScheme : ap_http_method(r)), ap_get_server_name(r), ap_get_server_port(r), r->unparsed_uri
900 pair<bool,const char*> application_id=settings.first->getString("applicationId");
901 const IApplication* application=conf->getApplication(application_id.second);
903 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
904 "shib_post_handler: unable to map request to application settings, check configuration");
908 // Declare SHIRE object for this request.
909 SHIRE shire(application);
911 return shib_handler(r, application, shire);
914 int shib_handler(request_rec* r, const IApplication* application, SHIRE& shire)
916 shib_server_config* sc=(shib_server_config*)ap_get_module_config(r->server->module_config,&mod_shib);
918 const char* targeturl=shib_get_targeturl(r,sc->szScheme);
920 const char* shireURL=shire.getShireURL(targeturl);
922 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
923 "shib_post_handler: unable to map request to proper shireURL setting, check configuration");
927 // Make sure we only process the SHIRE requests.
928 if (!strstr(targeturl,shireURL))
931 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler() running");
933 const IPropertySet* sessionProps=application->getPropertySet("Sessions");
935 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
936 "shib_post_handler: unable to map request to application session settings, check configuration");
940 pair<const char*,const char*> shib_cookie=shire.getCookieNameProps(); // always returns something
942 ShibMLP markupProcessor;
943 markupProcessor.insert("requestURL", targeturl);
945 // Process SHIRE request
946 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() Beginning SHIRE processing");
949 pair<bool,bool> shireSSL=sessionProps->getBool("shireSSL");
951 // Make sure this is SSL, if it should be
952 if ((!shireSSL.first || shireSSL.second) && strcmp(ap_http_method(r),"https"))
953 throw ShibTargetException(SHIBRPC_OK, "blocked non-SSL access to session creation service");
955 // If this is a GET, we manufacture an AuthnRequest.
956 if (!strcasecmp(r->method,"GET")) {
957 const char* areq=r->args ? shire.getLazyAuthnRequest(r->args) : NULL;
959 throw ShibTargetException(SHIBRPC_OK, "malformed arguments to request a new session");
960 ap_table_setn(r->headers_out, "Location", ap_pstrdup(r->pool,areq));
963 else if (strcasecmp(r->method,"POST")) {
964 throw ShibTargetException(SHIBRPC_OK, "blocked non-POST to SHIRE POST processor");
967 // Sure sure this POST is an appropriate content type
968 const char *ct = ap_table_get(r->headers_in, "Content-type");
969 if (!ct || strcasecmp(ct, "application/x-www-form-urlencoded"))
970 throw ShibTargetException(SHIBRPC_OK,
971 ap_psprintf(r->pool, "blocked bad content-type to SHIRE POST processor: %s", (ct ? ct : "")));
973 // Read the posted data
974 if (ap_setup_client_block(r, REQUEST_CHUNKED_ERROR))
975 throw ShibTargetException(SHIBRPC_OK, "CGI setup_client_block failed");
976 if (!ap_should_client_block(r))
977 throw ShibTargetException(SHIBRPC_OK, "CGI should_client_block failed");
978 if (r->remaining > 1024*1024)
979 throw ShibTargetException (SHIBRPC_OK, "CGI length too long...");
982 char buff[HUGE_STRING_LEN];
983 ap_hard_timeout("[mod_shib] CGI Parser", r);
984 memset(buff, 0, sizeof(buff));
985 while (ap_get_client_block(r, buff, sizeof(buff)-1) > 0) {
988 memset(buff, 0, sizeof(buff));
992 // Parse the submission.
993 pair<const char*,const char*> elements=shire.getFormSubmission(cgistr.c_str(),cgistr.length());
995 // Make sure the SAML Response parameter exists
996 if (!elements.first || !*elements.first)
997 throw ShibTargetException(SHIBRPC_OK, "SHIRE POST failed to find SAMLResponse form element");
999 // Make sure the target parameter exists
1000 if (!elements.second || !*elements.second)
1001 throw ShibTargetException(SHIBRPC_OK, "SHIRE POST failed to find TARGET form element");
1003 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1004 "shib_handler() Processing POST for target: %s", elements.second);
1008 RPCError* status = shire.sessionCreate(elements.first, r->connection->remote_ip, cookie);
1010 if (status->isError()) {
1011 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
1012 "shib_handler() POST process failed (%d): %s", status->getCode(), status->getText());
1014 if (status->isRetryable()) {
1016 ap_log_rerror(APLOG_MARK,APLOG_INFO|APLOG_NOERRNO,SH_AP_R(r),
1017 "shib_handler() retryable error, generating new AuthnRequest");
1018 ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(elements.second)));
1022 // return this error to the user.
1023 markupProcessor.insert(*status);
1025 return shib_error_page(r, application, "shire", markupProcessor);
1029 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1030 "shib_handler() POST process succeeded. New session: %s", cookie.c_str());
1032 // We've got a good session, set the cookie...
1033 char* val = ap_psprintf(r->pool,"%s=%s%s",shib_cookie.first,cookie.c_str(),shib_cookie.second);
1034 ap_table_setn(r->err_headers_out, "Set-Cookie", val);
1035 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() setting cookie: %s", val);
1037 // ... and redirect to the target
1038 ap_table_setn(r->headers_out, "Location", ap_pstrdup(r->pool,elements.second));
1041 catch (ShibTargetException &e) {
1042 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() caught exception: %s", e.what());
1043 markupProcessor.insert("errorType", "Session Creation Service Error");
1044 markupProcessor.insert("errorText", e.what());
1045 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
1046 return shib_error_page(r, application, "shire", markupProcessor);
1050 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler(): unexpected exception");
1051 markupProcessor.insert("errorType", "Session Creation Service Error");
1052 markupProcessor.insert("errorText", "Unknown Exception");
1053 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
1054 return shib_error_page(r, application, "shire", markupProcessor);
1058 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_handler() server error");
1059 return SERVER_ERROR;
1062 static int shib_error_page(request_rec* r, const IApplication* app, const char* page, ShibMLP& mlp)
1064 const IPropertySet* props=app->getPropertySet("Errors");
1066 pair<bool,const char*> p=props->getString(page);
1068 ifstream infile(p.second);
1069 if (!infile.fail()) {
1070 const char* res = mlp.run(infile,props);
1072 r->content_type = ap_psprintf(r->pool, "text/html");
1073 ap_send_http_header(r);
1081 ap_log_rerror(APLOG_MARK,APLOG_ERR,SH_AP_R(r),
1082 "shib_error_page() could not process shire error template for application %s",app->getId());
1083 return SERVER_ERROR;
1087 * shib_auth_checker() -- a simple resource manager to
1088 * process the .htaccess settings and copy attributes
1089 * into the HTTP headers.
1091 extern "C" int shib_auth_checker(request_rec* r)
1093 shib_dir_config* dc=
1094 (shib_dir_config*)ap_get_module_config(r->per_dir_config,&mod_shib);
1096 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() executing");
1098 // Regular access to arbitrary resource...check AuthType
1099 const char* auth_type=ap_auth_type(r);
1100 if (!auth_type || strcasecmp(auth_type,"shibboleth"))
1103 ostringstream threadid;
1104 threadid << "[" << getpid() << "] shibrm" << '\0';
1105 saml::NDC ndc(threadid.str().c_str());
1107 // We lock the configuration system for the duration.
1108 IConfig* conf=g_Config->getINI();
1109 Locker locker(conf);
1111 const char* application_id=ap_table_get(r->headers_in,"Shib-Application-ID");
1112 const IApplication* application=NULL;
1114 application = conf->getApplication(application_id);
1118 int m=r->method_number;
1119 bool method_restricted=false;
1122 const array_header* reqs_arr=ap_requires(r);
1126 require_line* reqs=(require_line*)reqs_arr->elts;
1128 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"REQUIRE nelts: %d", reqs_arr->nelts);
1129 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"REQUIRE all: %d", dc->bRequireAll);
1131 vector<bool> auth_OK(reqs_arr->nelts,false);
1133 #define SHIB_AP_CHECK_IS_OK { \
1134 if (dc->bRequireAll < 1) \
1136 auth_OK[x] = true; \
1140 for (int x=0; x<reqs_arr->nelts; x++) {
1142 if (!(reqs[x].method_mask & (1 << m)))
1144 method_restricted=true;
1146 t = reqs[x].requirement;
1147 w = ap_getword_white(r->pool, &t);
1149 if (!strcasecmp(w,"Shibboleth")) {
1150 // This is a dummy rule needed because Apache conflates authn and authz.
1151 // Without some require rule, AuthType is ignored and no check_user hooks run.
1152 SHIB_AP_CHECK_IS_OK;
1154 else if (!strcmp(w,"valid-user") && application_id) {
1155 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting valid-user");
1156 SHIB_AP_CHECK_IS_OK;
1158 else if (!strcmp(w,"user") && SH_AP_USER(r)) {
1161 w=ap_getword_conf(r->pool,&t);
1169 // To do regex matching, we have to convert from UTF-8.
1170 auto_ptr<XMLCh> trans(fromUTF8(w));
1171 RegularExpression re(trans.get());
1172 auto_ptr<XMLCh> trans2(fromUTF8(SH_AP_USER(r)));
1173 if (re.matches(trans2.get())) {
1174 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting user: %s",w);
1175 SHIB_AP_CHECK_IS_OK;
1178 catch (XMLException& ex) {
1179 auto_ptr_char tmp(ex.getMessage());
1180 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
1181 "shib_auth_checker caught exception while parsing regular expression (%s): %s",w,tmp.get());
1184 else if (!strcmp(SH_AP_USER(r),w)) {
1185 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting user: %s",w);
1186 SHIB_AP_CHECK_IS_OK;
1190 else if (!strcmp(w,"group")) {
1191 SH_AP_TABLE* grpstatus=NULL;
1192 if (dc->szAuthGrpFile && SH_AP_USER(r)) {
1193 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() using groups file: %s\n",dc->szAuthGrpFile);
1194 grpstatus=groups_for_user(r,SH_AP_USER(r),dc->szAuthGrpFile);
1200 w=ap_getword_conf(r->pool,&t);
1201 if (ap_table_get(grpstatus,w)) {
1202 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting group: %s",w);
1203 SHIB_AP_CHECK_IS_OK;
1208 Iterator<IAAP*> provs=application ? application->getAAPProviders() : EMPTY(IAAP*);
1209 AAP wrapper(provs,w);
1210 if (wrapper.fail()) {
1211 ap_log_rerror(APLOG_MARK,APLOG_WARNING|APLOG_NOERRNO,SH_AP_R(r),
1212 "shib_auth_checker() didn't recognize require rule: %s\n",w);
1217 const char* vals=ap_table_get(r->headers_in,wrapper->getHeader());
1218 while (*t && vals) {
1219 w=ap_getword_conf(r->pool,&t);
1226 auto_ptr<RegularExpression> re;
1228 delete re.release();
1229 auto_ptr<XMLCh> trans(fromUTF8(w));
1230 auto_ptr<RegularExpression> temp(new RegularExpression(trans.get()));
1234 string vals_str(vals);
1236 for (int i = 0; i < vals_str.length(); i++) {
1237 if (vals_str.at(i) == ';') {
1239 ap_log_rerror(APLOG_MARK,APLOG_WARNING|APLOG_NOERRNO,SH_AP_R(r),
1240 "shib_auth_checker() invalid header encoding %s: starts with semicolon", vals);
1241 return SERVER_ERROR;
1244 if (vals_str.at(i-1) == '\\') {
1245 vals_str.erase(i-1, 1);
1250 string val = vals_str.substr(j, i-j);
1253 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
1254 if (re->matches(trans.get())) {
1255 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1256 "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
1257 SHIB_AP_CHECK_IS_OK;
1260 else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
1261 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1262 "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
1263 SHIB_AP_CHECK_IS_OK;
1266 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1267 "shib_auth_checker() expecting %s, got %s: authorization not granted", w, val.c_str());
1272 string val = vals_str.substr(j, vals_str.length()-j);
1274 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
1275 if (re->matches(trans.get())) {
1276 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1277 "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
1278 SHIB_AP_CHECK_IS_OK;
1281 else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
1282 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1283 "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
1284 SHIB_AP_CHECK_IS_OK;
1287 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1288 "shib_auth_checker() expecting %s, got %s: authorization not granted", w, val.c_str());
1291 catch (XMLException& ex) {
1292 auto_ptr_char tmp(ex.getMessage());
1293 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
1294 "shib_auth_checker caught exception while parsing regular expression (%s): %s",w,tmp.get());
1300 // check if all require directives are true
1301 bool auth_all_OK = true;
1302 for (int i= 0; i<reqs_arr->nelts; i++) {
1303 auth_all_OK &= auth_OK[i];
1308 if (!method_restricted)
1311 if (!application_id) {
1312 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
1313 "shib_auth_checker: Shib-Application-ID header not found in request");
1314 return HTTP_FORBIDDEN;
1316 else if (!application) {
1317 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
1318 "shib_auth_checker: unable to map request to application settings, check configuration");
1319 return HTTP_FORBIDDEN;
1322 ShibMLP markupProcessor;
1323 markupProcessor.insert("requestURL", ap_construct_url(r->pool,r->unparsed_uri,r));
1324 return shib_error_page(r, application, "access", markupProcessor);
1328 #ifndef SHIB_APACHE_13
1331 * Empty cleanup hook, Apache 2.x doesn't check NULL very well...
1333 extern "C" apr_status_t shib_exit(void* data)
1335 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,0,NULL,"shib_exit() done\n");
1343 * Cleanup the (per-process) pool info.
1345 #ifdef SHIB_APACHE_13
1346 extern "C" void shib_child_exit(server_rec* s, SH_AP_POOL* p)
1349 extern "C" apr_status_t shib_child_exit(void* data)
1351 server_rec* s = NULL;
1354 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit(%d) dealing with g_Config..", (int)getpid());
1355 g_Config->shutdown();
1357 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit() done\n");
1359 #ifndef SHIB_APACHE_13
1365 * shire_child_init()
1366 * Things to do when the child process is initialized.
1367 * (or after the configs are read in apache-2)
1369 #ifdef SHIB_APACHE_13
1370 extern "C" void shib_child_init(server_rec* s, SH_AP_POOL* p)
1372 extern "C" void shib_child_init(apr_pool_t* p, server_rec* s)
1375 // Initialize runtime components.
1377 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init(%d) starting", (int)getpid());
1380 ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() already initialized!");
1385 g_Config=&ShibTargetConfig::getConfig();
1386 g_Config->setFeatures(
1387 ShibTargetConfig::Listener |
1388 ShibTargetConfig::Metadata |
1389 ShibTargetConfig::AAP |
1390 ShibTargetConfig::RequestMapper |
1391 ShibTargetConfig::SHIREExtensions |
1392 ShibTargetConfig::Logging
1394 if (!g_Config->init(g_szSchemaDir,g_szSHIBConfig)) {
1395 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize SHIB Target");
1400 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize SHIB Target");
1404 // Set the cleanup handler
1405 apr_pool_cleanup_register(p, NULL, &shib_exit, &shib_child_exit);
1407 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() done");
1410 typedef const char* (*config_fn_t)(void);
1412 #ifdef SHIB_APACHE_13
1414 // SHIB Module commands
1416 static command_rec shire_cmds[] = {
1417 {"SHIREConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1418 RSRC_CONF, TAKE1, "Path to shibboleth.xml config file."},
1419 {"ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1420 RSRC_CONF, TAKE1, "Path to shibboleth.xml config file."},
1421 {"ShibSchemaDir", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1422 RSRC_CONF, TAKE1, "Path to Shibboleth XML schema directory."},
1424 {"ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
1425 (void *) XtOffsetOf (shib_server_config, szScheme),
1426 RSRC_CONF, TAKE1, "URL scheme to force into generated URLs for a vhost."},
1428 {"ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1429 (void *) XtOffsetOf (shib_dir_config, bBasicHijack),
1430 OR_AUTHCFG, FLAG, "Respond to AuthType Basic and convert to shib?"},
1431 {"ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1432 (void *) XtOffsetOf (shib_dir_config, bRequireSession),
1433 OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist."},
1434 {"ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1435 (void *) XtOffsetOf (shib_dir_config, bExportAssertion),
1436 OR_AUTHCFG, FLAG, "Export SAML assertion to Shibboleth-defined header?"},
1437 {"AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
1438 (void *) XtOffsetOf (shib_dir_config, szAuthGrpFile),
1439 OR_AUTHCFG, TAKE1, "text file containing group names and member user IDs"},
1440 {"ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1441 (void *) XtOffsetOf (shib_dir_config, bRequireAll),
1442 OR_AUTHCFG, FLAG, "All require directives must match!"},
1448 handler_rec shib_handlers[] = {
1449 { "shib-shire-post", shib_post_handler },
1453 module MODULE_VAR_EXPORT mod_shib = {
1454 STANDARD_MODULE_STUFF,
1455 NULL, /* initializer */
1456 create_shib_dir_config, /* dir config creater */
1457 merge_shib_dir_config, /* dir merger --- default is to override */
1458 create_shib_server_config, /* server config */
1459 merge_shib_server_config, /* merge server config */
1460 shire_cmds, /* command table */
1461 shib_handlers, /* handlers */
1462 NULL, /* filename translation */
1463 shib_check_user, /* check_user_id */
1464 shib_auth_checker, /* check auth */
1465 NULL, /* check access */
1466 NULL, /* type_checker */
1469 NULL, /* header parser */
1470 shib_child_init, /* child_init */
1471 shib_child_exit, /* child_exit */
1472 NULL /* post read-request */
1475 #elif defined(SHIB_APACHE_20)
1477 extern "C" void shib_register_hooks (apr_pool_t *p)
1479 ap_hook_child_init(shib_child_init, NULL, NULL, APR_HOOK_MIDDLE);
1480 ap_hook_check_user_id(shib_check_user, NULL, NULL, APR_HOOK_MIDDLE);
1481 ap_hook_auth_checker(shib_auth_checker, NULL, NULL, APR_HOOK_FIRST);
1482 ap_hook_handler(shib_post_handler, NULL, NULL, APR_HOOK_LAST);
1485 // SHIB Module commands
1488 static command_rec shib_cmds[] = {
1489 AP_INIT_TAKE1("ShibConfig",
1490 (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1491 RSRC_CONF, "Path to shibboleth.xml config file."),
1492 AP_INIT_TAKE1("ShibSchemaDir",
1493 (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1494 RSRC_CONF, "Path to Shibboleth XML schema directory."),
1496 AP_INIT_TAKE1("ShibURLScheme",
1497 (config_fn_t)shib_set_server_string_slot,
1498 (void *) offsetof (shib_server_config, szScheme),
1499 RSRC_CONF, "URL scheme to force into generated URLs for a vhost."),
1501 AP_INIT_FLAG("ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1502 (void *) offsetof (shib_dir_config, bBasicHijack),
1503 OR_AUTHCFG, "Respond to AuthType Basic and convert to shib?"),
1504 AP_INIT_FLAG("ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1505 (void *) offsetof (shib_dir_config, bRequireSession),
1506 OR_AUTHCFG, "Initiates a new session if one does not exist."),
1507 AP_INIT_FLAG("ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1508 (void *) offsetof (shib_dir_config, bExportAssertion),
1509 OR_AUTHCFG, "Export SAML assertion to Shibboleth-defined header?"),
1510 AP_INIT_TAKE1("AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
1511 (void *) offsetof (shib_dir_config, szAuthGrpFile),
1512 OR_AUTHCFG, "text file containing group names and member user IDs"),
1513 AP_INIT_FLAG("ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1514 (void *) offsetof (shib_dir_config, bRequireAll),
1515 OR_AUTHCFG, "All require directives must match!"),
1520 module AP_MODULE_DECLARE_DATA mod_shib = {
1521 STANDARD20_MODULE_STUFF,
1522 create_shib_dir_config, /* create dir config */
1523 merge_shib_dir_config, /* merge dir config --- default is to override */
1524 create_shib_server_config, /* create server config */
1525 merge_shib_server_config, /* merge server config */
1526 shib_cmds, /* command table */
1527 shib_register_hooks /* register hooks */
1531 #error "undefined APACHE version"