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 ResourceAccessException("Unable to access group file ($1) for user ($2)",params(2,grpfile,user));
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);
247 m_sc->szScheme ? m_sc->szScheme : ap_http_method(req),
248 ap_get_server_name(req),
249 (int)ap_get_server_port(req),
251 ap_table_get(req->headers_in, "Content-type"),
252 req->connection->remote_ip,
258 ~ShibTargetApache() { }
260 virtual void log(ShibLogLevel level, const string &msg) {
261 ap_log_rerror(APLOG_MARK,
262 (level == LogLevelDebug ? APLOG_DEBUG :
263 (level == LogLevelInfo ? APLOG_INFO :
264 (level == LogLevelWarn ? APLOG_WARNING :
265 APLOG_ERR)))|APLOG_NOERRNO, SH_AP_R(m_req),
268 virtual string getCookies(void) {
269 const char *c = ap_table_get(m_req->headers_in, "Cookie");
270 return string(c ? c : "");
272 virtual void setCookie(const string &name, const string &value) {
273 char* val = ap_psprintf(m_req->pool, "%s=%s", name.c_str(), value.c_str());
274 ap_table_setn(m_req->err_headers_out, "Set-Cookie", val);
276 virtual string getArgs(void) { return string(m_req->args ? m_req->args : ""); }
277 virtual string getPostData(void) {
278 // Read the posted data
279 if (ap_setup_client_block(m_req, REQUEST_CHUNKED_ERROR))
280 throw FatalProfileException("Apache function (setup_client_block) failed while reading profile submission.");
281 if (!ap_should_client_block(m_req))
282 throw FatalProfileException("Apache function (should_client_block) failed while reading profile submission.");
283 if (m_req->remaining > 1024*1024)
284 throw FatalProfileException("Blocked too-large a submission to profile endpoint.");
286 char buff[HUGE_STRING_LEN];
287 ap_hard_timeout("[mod_shib] getPostData", m_req);
288 memset(buff, 0, sizeof(buff));
289 while (ap_get_client_block(m_req, buff, sizeof(buff)-1) > 0) {
290 ap_reset_timeout(m_req);
292 memset(buff, 0, sizeof(buff));
294 ap_kill_timeout(m_req);
298 virtual void clearHeader(const string &name) {
299 ap_table_unset(m_req->headers_in, name.c_str());
301 virtual void setHeader(const string &name, const string &value) {
302 ap_table_set(m_req->headers_in, name.c_str(), value.c_str());
304 virtual string getHeader(const string &name) {
305 const char *hdr = ap_table_get(m_req->headers_in, name.c_str());
306 return string(hdr ? hdr : "");
308 virtual void setRemoteUser(const string &user) {
309 SH_AP_USER(m_req) = ap_pstrdup(m_req->pool, user.c_str());
311 virtual string getRemoteUser(void) {
312 return string(SH_AP_USER(m_req) ? SH_AP_USER(m_req) : "");
314 // override so we can look at the actual auth type and maybe override it.
315 virtual string getAuthType(void) {
316 const char *auth_type=ap_auth_type(m_req);
319 if (strcasecmp(auth_type, "shibboleth")) {
320 if (!strcasecmp(auth_type, "basic") && m_dc->bBasicHijack == 1) {
321 core_dir_config* conf= (core_dir_config*)ap_get_module_config(m_req->per_dir_config,
322 ap_find_linked_module("http_core.c"));
323 auth_type = conf->ap_auth_type = "shibboleth";
326 return string(auth_type);
328 // Override this function because we want to add the Apache Directory override
329 virtual pair<bool,bool> getRequireSession(IRequestMapper::Settings &settings) {
330 pair<bool,bool> requireSession = settings.first->getBool("requireSession");
331 if (!requireSession.first || !requireSession.second)
332 if (m_dc->bRequireSession == 1)
333 requireSession.second=true;
335 return requireSession;
338 virtual HTAccessInfo* getAccessInfo(void) {
339 int m = m_req->method_number;
340 const array_header* reqs_arr = ap_requires(m_req);
344 require_line* reqs = (require_line*) reqs_arr->elts;
346 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req),
347 "REQUIRE nelts: %d", reqs_arr->nelts);
348 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req),
349 "REQUIRE all: %d", m_dc->bRequireAll);
351 HTAccessInfo* ht = new HTAccessInfo();
352 ht->requireAll = (m_dc->bRequireAll == 1);
353 ht->elements.reserve(reqs_arr->nelts);
354 for (int x = 0; x < reqs_arr->nelts; x++) {
355 HTAccessInfo::RequireLine* rline = new HTAccessInfo::RequireLine();
356 rline->use_line = (reqs[x].method_mask & (1 << m));
357 rline->tokens.reserve(6); // No reason to reserve specifically 6 tokens
358 const char* t = reqs[x].requirement;
359 const char* w = ap_getword_white(m_req->pool, &t);
360 rline->tokens.push_back(w);
362 w = ap_getword_conf(m_req->pool, &t);
363 rline->tokens.push_back(w);
365 ht->elements.push_back(rline);
369 virtual HTGroupTable* getGroupTable(string& user) {
370 if (m_dc->szAuthGrpFile && !user.empty()) {
371 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req),
372 "getGroupTable() using groups file: %s\n",
373 m_dc->szAuthGrpFile);
375 HTGroupTableApache *gt = new HTGroupTableApache(m_req, user.c_str(),
376 m_dc->szAuthGrpFile);
383 virtual void* sendPage(
386 const string& content_type="text/html",
387 const Iterator<header_t>& headers=EMPTY(header_t)
389 m_req->content_type = ap_psprintf(m_req->pool, content_type.c_str());
390 while (headers.hasNext()) {
391 const header_t& h=headers.next();
392 ap_table_setn(m_req->headers_out, h.first.c_str(), h.second.c_str());
394 ap_send_http_header(m_req);
395 ap_rprintf(m_req, msg.c_str());
396 return (void*)((code==200) ? DONE : code);
398 virtual void* sendRedirect(const string& url) {
399 ap_table_set(m_req->headers_out, "Location", url.c_str());
400 return (void*)REDIRECT;
402 virtual void* returnDecline(void) { return (void*)DECLINED; }
403 virtual void* returnOK(void) { return (void*)OK; }
406 shib_dir_config* m_dc;
407 shib_server_config* m_sc;
410 /********************************************************************************/
413 extern "C" int shib_check_user(request_rec* r)
415 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
416 "shib_check_user(%d): ENTER\n", (int)getpid());
418 ostringstream threadid;
419 threadid << "[" << getpid() << "] shib_check_user" << '\0';
420 saml::NDC ndc(threadid.str().c_str());
425 ShibTargetApache sta(r);
427 // Check user authentication, the set the post handler bypass
428 pair<bool,void*> res = sta.doCheckAuthN((sta.m_dc->bRequireSession == 1), true);
429 apr_pool_userdata_setn((const void*)42,g_UserDataKey,NULL,r->pool);
430 if (res.first) return (int)res.second;
432 // user auth was okay -- export the assertions now
433 res = sta.doExportAssertions((sta.m_dc->bExportAssertion == 1));
434 if (res.first) return (int)res.second;
436 // export happened successfully.. this user is ok.
441 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r),
442 "shib_check_user threw an uncaught exception!");
448 extern "C" int shib_post_handler(request_rec* r)
450 ostringstream threadid;
451 threadid << "[" << getpid() << "] shib_post_handler" << '\0';
452 saml::NDC ndc(threadid.str().c_str());
454 #ifndef SHIB_APACHE_13
455 // With 2.x, this handler always runs, though last.
456 // We check if shib_check_user ran, because it will detect a SHIRE request
457 // and dispatch it directly.
459 apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
460 if (data==(const void*)42) {
461 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_post_handler skipped since check_user ran");
466 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
467 "shib_post_handler(%d): ENTER", (int)getpid());
472 ShibTargetApache sta(r);
474 pair<bool,void*> res = sta.doHandleProfile();
475 if (res.first) return (int)res.second;
477 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r),
478 "doHandleProfile() did not do anything.");
483 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r),
484 "shib_post_handler threw an uncaught exception!");
491 * shib_auth_checker() -- a simple resource manager to
492 * process the .htaccess settings
494 extern "C" int shib_auth_checker(request_rec* r)
496 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
497 "shib_auth_checker(%d): ENTER", (int)getpid());
499 ostringstream threadid;
500 threadid << "[" << getpid() << "] shib_auth_checker" << '\0';
501 saml::NDC ndc(threadid.str().c_str());
506 ShibTargetApache sta(r);
508 pair<bool,void*> res = sta.doCheckAuthZ();
509 if (res.first) return (int)res.second;
516 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r),
517 "shib_auth_checker threw an uncaught exception!");
524 static char* shib_get_targeturl(request_rec* r, const char* scheme=NULL)
526 // On 1.3, this is always canonical, but on 2.0, UseCanonicalName comes into play.
527 // However, we also have a setting to forcibly replace the scheme for esoteric cases.
529 unsigned port = ap_get_server_port(r);
530 if ((!strcmp(scheme,"http") && port==80) || (!strcmp(scheme,"https") && port==443)) {
531 return ap_pstrcat(r->pool, scheme, "://", ap_get_server_name(r), r->unparsed_uri, NULL);
533 return ap_psprintf(r->pool, "%s://%s:%u%s", scheme, ap_get_server_name(r), port, r->unparsed_uri);
535 return ap_construct_url(r->pool,r->unparsed_uri,r);
538 extern "C" int shib_check_user(request_rec* r)
540 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: ENTER");
541 shib_dir_config* dc=(shib_dir_config*)ap_get_module_config(r->per_dir_config,&mod_shib);
542 shib_server_config* sc=(shib_server_config*)ap_get_module_config(r->server->module_config,&mod_shib);
544 ostringstream threadid;
545 threadid << "[" << getpid() << "] shib_check_user" << '\0';
546 saml::NDC ndc(threadid.str().c_str());
548 const char* targeturl=shib_get_targeturl(r,sc->szScheme);
550 // We lock the configuration system for the duration.
551 IConfig* conf=g_Config->getINI();
554 // Map request to application and content settings.
555 IRequestMapper* mapper=conf->getRequestMapper();
556 Locker locker2(mapper);
557 IRequestMapper::Settings settings=mapper->getSettingsFromParsedURL(
558 (sc-> szScheme ? sc-> szScheme : ap_http_method(r)), ap_get_server_name(r), ap_get_server_port(r), r->unparsed_uri
560 pair<bool,const char*> application_id=settings.first->getString("applicationId");
561 const IApplication* application=conf->getApplication(application_id.second);
563 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
564 "shib_check_user: unable to map request to application settings, check configuration");
568 // Declare SHIRE object for this request.
569 SHIRE shire(application);
571 const char* shireURL=shire.getShireURL(targeturl);
573 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
574 "shib_check_user: unable to map request to proper shireURL setting, check configuration");
578 // Get location of this application's assertion consumer service and see if this is it.
579 if (strstr(targeturl,shireURL)) {
580 return shib_handler(r,application,shire);
583 // We can short circuit the handler if we run this...
584 apr_pool_userdata_setn((const void*)42,g_UserDataKey,NULL,r->pool);
586 // Regular access to arbitrary resource...check AuthType
587 const char *auth_type=ap_auth_type(r);
591 if (strcasecmp(auth_type,"shibboleth")) {
592 if (!strcasecmp(auth_type,"basic") && dc->bBasicHijack==1) {
593 core_dir_config* conf=
594 (core_dir_config*)ap_get_module_config(r->per_dir_config,
595 ap_find_linked_module("http_core.c"));
596 conf->ap_auth_type="shibboleth";
602 pair<bool,bool> requireSession = settings.first->getBool("requireSession");
603 if (!requireSession.first || !requireSession.second)
604 if (dc->bRequireSession==1)
605 requireSession.second=true;
607 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: session check for %s",targeturl);
609 pair<const char*,const char*> shib_cookie=shire.getCookieNameProps(); // always returns *something*
611 // We're in charge, so check for cookie.
612 const char* session_id=NULL;
613 const char* cookies=ap_table_get(r->headers_in,"Cookie");
616 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: cookies found: %s",cookies);
617 if (session_id=strstr(cookies,shib_cookie.first)) {
618 // Yep, we found a cookie -- pull it out (our session_id)
619 session_id+=strlen(shib_cookie.first) + 1; /* Skip over the '=' */
620 char* cookiebuf = ap_pstrdup(r->pool,session_id);
621 char* cookieend = strchr(cookiebuf,';');
623 *cookieend = '\0'; /* Ignore anyting after a ; */
624 session_id=cookiebuf;
628 if (!session_id || !*session_id) {
629 // If no session required, bail now.
630 if (!requireSession.second)
633 // No acceptable cookie, and we require a session. Generate an AuthnRequest.
634 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: no cookie found -- redirecting to WAYF");
635 ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(targeturl)));
639 // Make sure this session is still valid.
640 RPCError* status = NULL;
641 ShibMLP markupProcessor;
642 markupProcessor.insert("requestURL", targeturl);
645 status = shire.sessionIsValid(session_id, r->connection->remote_ip);
647 catch (ShibTargetException &e) {
648 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): %s", e.what());
649 markupProcessor.insert("errorType", "Session Processing Error");
650 markupProcessor.insert("errorText", e.what());
651 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
652 return shib_error_page(r, application, "shire", markupProcessor);
656 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): caught unexpected error");
657 markupProcessor.insert("errorType", "Session Processing Error");
658 markupProcessor.insert("errorText", "Unexpected Exception");
659 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
660 return shib_error_page(r, application, "shire", markupProcessor);
665 if (status->isError()) {
666 ap_log_rerror(APLOG_MARK,APLOG_INFO|APLOG_NOERRNO,SH_AP_R(r),
667 "shib_check_user() session invalid: %s", status->getText());
669 // If no session required, bail now.
670 if (!requireSession.second)
671 return OK; // XXX: Or should this be DECLINED?
672 // Has to be OK because DECLINED will just cause Apache to fail when it can't locate
673 // anything to process the AuthType. No session plus requireSession false means
674 // do not authenticate the user.
675 else if (status->isRetryable()) {
676 // Oops, session is invalid. Generate AuthnRequest.
677 ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(targeturl)));
682 // return the error page to the user
683 markupProcessor.insert(*status);
685 return shib_error_page(r, application, "shire", markupProcessor);
691 #ifdef SHIB_APACHE_13
693 r->connection->ap_auth_type = "shibboleth";
695 r->ap_auth_type = "shibboleth";
697 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: session successfully verified");
699 // This is code transferred in from the auth check to export the attributes.
700 // We could even combine the isSessionValid/getAssertions API...?
703 vector<SAMLAssertion*> assertions;
704 SAMLAuthenticationStatement* sso_statement=NULL;
707 status = rm.getAssertions(session_id, r->connection->remote_ip, assertions, &sso_statement);
709 catch (ShibTargetException &e) {
710 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): %s", e.what());
711 markupProcessor.insert("errorType", "Attribute Processing Error");
712 markupProcessor.insert("errorText", e.what());
713 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
714 return shib_error_page(r, application, "rm", markupProcessor);
718 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): caught unexpected error");
719 markupProcessor.insert("errorType", "Attribute Processing Error");
720 markupProcessor.insert("errorText", "Unexpected Exception");
721 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
722 return shib_error_page(r, application, "rm", markupProcessor);
726 if (status->isError()) {
727 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
728 "shib_check_user() getAssertions failed: %s", status->getText());
730 markupProcessor.insert(*status);
732 return shib_error_page(r, application, "rm", markupProcessor);
736 // Do we have an access control plugin?
737 if (settings.second) {
738 Locker acllock(settings.second);
739 if (!settings.second->authorized(*sso_statement,assertions)) {
740 for (int k = 0; k < assertions.size(); k++)
741 delete assertions[k];
742 delete sso_statement;
743 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): access control provider denied access");
744 return shib_error_page(r, application, "access", markupProcessor);
748 // Get the AAP providers, which contain the attribute policy info.
749 Iterator<IAAP*> provs=application->getAAPProviders();
751 // Clear out the list of mapped attributes
752 while (provs.hasNext()) {
753 IAAP* aap=provs.next();
756 Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
757 while (rules.hasNext()) {
758 const char* header=rules.next()->getHeader();
760 ap_table_unset(r->headers_in,header);
765 for (int k = 0; k < assertions.size(); k++)
766 delete assertions[k];
767 delete sso_statement;
768 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
769 "shib_check_user(): caught unexpected error while clearing headers");
770 markupProcessor.insert("errorType", "Attribute Processing Error");
771 markupProcessor.insert("errorText", "Unexpected Exception");
772 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
773 return shib_error_page(r, application, "rm", markupProcessor);
779 // Maybe export the first assertion.
780 ap_table_unset(r->headers_in,"Shib-Attributes");
781 pair<bool,bool> exp=settings.first->getBool("exportAssertion");
782 if (!exp.first || !exp.second)
783 if (dc->bExportAssertion==1)
785 if (exp.second && assertions.size()) {
787 RM::serialize(*(assertions[0]), assertion);
788 ap_table_set(r->headers_in,"Shib-Attributes", assertion.c_str());
791 // Export the SAML AuthnMethod and the origin site name, and possibly the NameIdentifier.
792 ap_table_unset(r->headers_in,"Shib-Origin-Site");
793 ap_table_unset(r->headers_in,"Shib-Authentication-Method");
794 ap_table_unset(r->headers_in,"Shib-NameIdentifier-Format");
795 auto_ptr_char os(sso_statement->getSubject()->getNameIdentifier()->getNameQualifier());
796 auto_ptr_char am(sso_statement->getAuthMethod());
797 ap_table_set(r->headers_in,"Shib-Origin-Site", os.get());
798 ap_table_set(r->headers_in,"Shib-Authentication-Method", am.get());
801 AAP wrapper(provs,sso_statement->getSubject()->getNameIdentifier()->getFormat(),Constants::SHIB_ATTRIBUTE_NAMESPACE_URI);
802 if (!wrapper.fail() && wrapper->getHeader()) {
803 auto_ptr_char form(sso_statement->getSubject()->getNameIdentifier()->getFormat());
804 auto_ptr_char nameid(sso_statement->getSubject()->getNameIdentifier()->getName());
805 ap_table_set(r->headers_in,"Shib-NameIdentifier-Format",form.get());
806 if (!strcmp(wrapper->getHeader(),"REMOTE_USER"))
807 SH_AP_USER(r)=ap_pstrdup(r->pool,nameid.get());
809 ap_table_set(r->headers_in,wrapper->getHeader(),nameid.get());
812 ap_table_unset(r->headers_in,"Shib-Application-ID");
813 ap_table_set(r->headers_in,"Shib-Application-ID",application_id.second);
815 // Export the attributes.
816 Iterator<SAMLAssertion*> a_iter(assertions);
817 while (a_iter.hasNext()) {
818 SAMLAssertion* assert=a_iter.next();
819 Iterator<SAMLStatement*> statements=assert->getStatements();
820 while (statements.hasNext()) {
821 SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());
824 Iterator<SAMLAttribute*> attrs=astate->getAttributes();
825 while (attrs.hasNext()) {
826 SAMLAttribute* attr=attrs.next();
828 // Are we supposed to export it?
829 AAP wrapper(provs,attr->getName(),attr->getNamespace());
830 if (wrapper.fail() || !wrapper->getHeader())
833 Iterator<string> vals=attr->getSingleByteValues();
834 if (!strcmp(wrapper->getHeader(),"REMOTE_USER") && vals.hasNext())
835 SH_AP_USER(r)=ap_pstrdup(r->pool,vals.next().c_str());
838 char* header = (char*)ap_table_get(r->headers_in, wrapper->getHeader());
840 header=ap_pstrdup(r->pool, header);
844 header = ap_pstrdup(r->pool, "");
845 for (; vals.hasNext(); it++) {
846 string value = vals.next();
847 for (string::size_type pos = value.find_first_of(";", string::size_type(0));
849 pos = value.find_first_of(";", pos)) {
850 value.insert(pos, "\\");
853 header=ap_pstrcat(r->pool, header, (it ? ";" : ""), value.c_str(), NULL);
855 ap_table_setn(r->headers_in, wrapper->getHeader(), header);
862 for (int k = 0; k < assertions.size(); k++)
863 delete assertions[k];
864 delete sso_statement;
869 extern "C" int shib_post_handler(request_rec* r)
871 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
872 "shib_post_handler(%d): ENTER", (int)getpid());
873 shib_server_config* sc=(shib_server_config*)ap_get_module_config(r->server->module_config,&mod_shib);
875 #ifndef SHIB_APACHE_13
876 // With 2.x, this handler always runs, though last.
877 // We check if shib_check_user ran, because it will detect a SHIRE request
878 // and dispatch it directly.
880 apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
881 if (data==(const void*)42) {
882 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_post_handler skipped since check_user ran");
887 ostringstream threadid;
888 threadid << "[" << getpid() << "] shib_post_handler" << '\0';
889 saml::NDC ndc(threadid.str().c_str());
891 // We lock the configuration system for the duration.
892 IConfig* conf=g_Config->getINI();
895 // Map request to application and content settings.
896 IRequestMapper* mapper=conf->getRequestMapper();
897 Locker locker2(mapper);
898 IRequestMapper::Settings settings=mapper->getSettingsFromParsedURL(
899 (sc->szScheme ? sc->szScheme : ap_http_method(r)), ap_get_server_name(r), ap_get_server_port(r), r->unparsed_uri
901 pair<bool,const char*> application_id=settings.first->getString("applicationId");
902 const IApplication* application=conf->getApplication(application_id.second);
904 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
905 "shib_post_handler: unable to map request to application settings, check configuration");
909 // Declare SHIRE object for this request.
910 SHIRE shire(application);
912 return shib_handler(r, application, shire);
915 int shib_handler(request_rec* r, const IApplication* application, SHIRE& shire)
917 shib_server_config* sc=(shib_server_config*)ap_get_module_config(r->server->module_config,&mod_shib);
919 const char* targeturl=shib_get_targeturl(r,sc->szScheme);
921 const char* shireURL=shire.getShireURL(targeturl);
923 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
924 "shib_post_handler: unable to map request to proper shireURL setting, check configuration");
928 // Make sure we only process the SHIRE requests.
929 if (!strstr(targeturl,shireURL))
932 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler() running");
934 const IPropertySet* sessionProps=application->getPropertySet("Sessions");
936 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
937 "shib_post_handler: unable to map request to application session settings, check configuration");
941 pair<const char*,const char*> shib_cookie=shire.getCookieNameProps(); // always returns something
943 ShibMLP markupProcessor;
944 markupProcessor.insert("requestURL", targeturl);
946 // Process SHIRE request
947 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() Beginning SHIRE processing");
950 pair<bool,bool> shireSSL=sessionProps->getBool("shireSSL");
952 // Make sure this is SSL, if it should be
953 if ((!shireSSL.first || shireSSL.second) && strcmp(ap_http_method(r),"https"))
954 throw ShibTargetException(SHIBRPC_OK, "blocked non-SSL access to session creation service");
956 // If this is a GET, we manufacture an AuthnRequest.
957 if (!strcasecmp(r->method,"GET")) {
958 const char* areq=r->args ? shire.getLazyAuthnRequest(r->args) : NULL;
960 throw ShibTargetException(SHIBRPC_OK, "malformed arguments to request a new session");
961 ap_table_setn(r->headers_out, "Location", ap_pstrdup(r->pool,areq));
964 else if (strcasecmp(r->method,"POST")) {
965 throw ShibTargetException(SHIBRPC_OK, "blocked non-POST to SHIRE POST processor");
968 // Sure sure this POST is an appropriate content type
969 const char *ct = ap_table_get(r->headers_in, "Content-type");
970 if (!ct || strcasecmp(ct, "application/x-www-form-urlencoded"))
971 throw ShibTargetException(SHIBRPC_OK,
972 ap_psprintf(r->pool, "blocked bad content-type to SHIRE POST processor: %s", (ct ? ct : "")));
974 // Read the posted data
975 if (ap_setup_client_block(r, REQUEST_CHUNKED_ERROR))
976 throw ShibTargetException(SHIBRPC_OK, "CGI setup_client_block failed");
977 if (!ap_should_client_block(r))
978 throw ShibTargetException(SHIBRPC_OK, "CGI should_client_block failed");
979 if (r->remaining > 1024*1024)
980 throw ShibTargetException (SHIBRPC_OK, "CGI length too long...");
983 char buff[HUGE_STRING_LEN];
984 ap_hard_timeout("[mod_shib] CGI Parser", r);
985 memset(buff, 0, sizeof(buff));
986 while (ap_get_client_block(r, buff, sizeof(buff)-1) > 0) {
989 memset(buff, 0, sizeof(buff));
993 // Parse the submission.
994 pair<const char*,const char*> elements=shire.getFormSubmission(cgistr.c_str(),cgistr.length());
996 // Make sure the SAML Response parameter exists
997 if (!elements.first || !*elements.first)
998 throw ShibTargetException(SHIBRPC_OK, "SHIRE POST failed to find SAMLResponse form element");
1000 // Make sure the target parameter exists
1001 if (!elements.second || !*elements.second)
1002 throw ShibTargetException(SHIBRPC_OK, "SHIRE POST failed to find TARGET form element");
1004 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1005 "shib_handler() Processing POST for target: %s", elements.second);
1009 RPCError* status = shire.sessionCreate(elements.first, r->connection->remote_ip, cookie);
1011 if (status->isError()) {
1012 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
1013 "shib_handler() POST process failed (%d): %s", status->getCode(), status->getText());
1015 if (status->isRetryable()) {
1017 ap_log_rerror(APLOG_MARK,APLOG_INFO|APLOG_NOERRNO,SH_AP_R(r),
1018 "shib_handler() retryable error, generating new AuthnRequest");
1019 ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(elements.second)));
1023 // return this error to the user.
1024 markupProcessor.insert(*status);
1026 return shib_error_page(r, application, "shire", markupProcessor);
1030 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1031 "shib_handler() POST process succeeded. New session: %s", cookie.c_str());
1033 // We've got a good session, set the cookie...
1034 char* val = ap_psprintf(r->pool,"%s=%s%s",shib_cookie.first,cookie.c_str(),shib_cookie.second);
1035 ap_table_setn(r->err_headers_out, "Set-Cookie", val);
1036 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() setting cookie: %s", val);
1038 // ... and redirect to the target
1039 ap_table_setn(r->headers_out, "Location", ap_pstrdup(r->pool,elements.second));
1042 catch (ShibTargetException &e) {
1043 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() caught exception: %s", e.what());
1044 markupProcessor.insert("errorType", "Session Creation Service Error");
1045 markupProcessor.insert("errorText", e.what());
1046 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
1047 return shib_error_page(r, application, "shire", markupProcessor);
1051 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler(): unexpected exception");
1052 markupProcessor.insert("errorType", "Session Creation Service Error");
1053 markupProcessor.insert("errorText", "Unknown Exception");
1054 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
1055 return shib_error_page(r, application, "shire", markupProcessor);
1059 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_handler() server error");
1060 return SERVER_ERROR;
1063 static int shib_error_page(request_rec* r, const IApplication* app, const char* page, ShibMLP& mlp)
1065 const IPropertySet* props=app->getPropertySet("Errors");
1067 pair<bool,const char*> p=props->getString(page);
1069 ifstream infile(p.second);
1070 if (!infile.fail()) {
1071 const char* res = mlp.run(infile,props);
1073 r->content_type = ap_psprintf(r->pool, "text/html");
1074 ap_send_http_header(r);
1082 ap_log_rerror(APLOG_MARK,APLOG_ERR,SH_AP_R(r),
1083 "shib_error_page() could not process shire error template for application %s",app->getId());
1084 return SERVER_ERROR;
1088 * shib_auth_checker() -- a simple resource manager to
1089 * process the .htaccess settings and copy attributes
1090 * into the HTTP headers.
1092 extern "C" int shib_auth_checker(request_rec* r)
1094 shib_dir_config* dc=
1095 (shib_dir_config*)ap_get_module_config(r->per_dir_config,&mod_shib);
1097 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() executing");
1099 // Regular access to arbitrary resource...check AuthType
1100 const char* auth_type=ap_auth_type(r);
1101 if (!auth_type || strcasecmp(auth_type,"shibboleth"))
1104 ostringstream threadid;
1105 threadid << "[" << getpid() << "] shibrm" << '\0';
1106 saml::NDC ndc(threadid.str().c_str());
1108 // We lock the configuration system for the duration.
1109 IConfig* conf=g_Config->getINI();
1110 Locker locker(conf);
1112 const char* application_id=ap_table_get(r->headers_in,"Shib-Application-ID");
1113 const IApplication* application=NULL;
1115 application = conf->getApplication(application_id);
1119 int m=r->method_number;
1120 bool method_restricted=false;
1123 const array_header* reqs_arr=ap_requires(r);
1127 require_line* reqs=(require_line*)reqs_arr->elts;
1129 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"REQUIRE nelts: %d", reqs_arr->nelts);
1130 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"REQUIRE all: %d", dc->bRequireAll);
1132 vector<bool> auth_OK(reqs_arr->nelts,false);
1134 #define SHIB_AP_CHECK_IS_OK { \
1135 if (dc->bRequireAll < 1) \
1137 auth_OK[x] = true; \
1141 for (int x=0; x<reqs_arr->nelts; x++) {
1143 if (!(reqs[x].method_mask & (1 << m)))
1145 method_restricted=true;
1147 t = reqs[x].requirement;
1148 w = ap_getword_white(r->pool, &t);
1150 if (!strcasecmp(w,"Shibboleth")) {
1151 // This is a dummy rule needed because Apache conflates authn and authz.
1152 // Without some require rule, AuthType is ignored and no check_user hooks run.
1153 SHIB_AP_CHECK_IS_OK;
1155 else if (!strcmp(w,"valid-user") && application_id) {
1156 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting valid-user");
1157 SHIB_AP_CHECK_IS_OK;
1159 else if (!strcmp(w,"user") && SH_AP_USER(r)) {
1162 w=ap_getword_conf(r->pool,&t);
1170 // To do regex matching, we have to convert from UTF-8.
1171 auto_ptr<XMLCh> trans(fromUTF8(w));
1172 RegularExpression re(trans.get());
1173 auto_ptr<XMLCh> trans2(fromUTF8(SH_AP_USER(r)));
1174 if (re.matches(trans2.get())) {
1175 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting user: %s",w);
1176 SHIB_AP_CHECK_IS_OK;
1179 catch (XMLException& ex) {
1180 auto_ptr_char tmp(ex.getMessage());
1181 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
1182 "shib_auth_checker caught exception while parsing regular expression (%s): %s",w,tmp.get());
1185 else if (!strcmp(SH_AP_USER(r),w)) {
1186 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting user: %s",w);
1187 SHIB_AP_CHECK_IS_OK;
1191 else if (!strcmp(w,"group")) {
1192 SH_AP_TABLE* grpstatus=NULL;
1193 if (dc->szAuthGrpFile && SH_AP_USER(r)) {
1194 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() using groups file: %s\n",dc->szAuthGrpFile);
1195 grpstatus=groups_for_user(r,SH_AP_USER(r),dc->szAuthGrpFile);
1201 w=ap_getword_conf(r->pool,&t);
1202 if (ap_table_get(grpstatus,w)) {
1203 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting group: %s",w);
1204 SHIB_AP_CHECK_IS_OK;
1209 Iterator<IAAP*> provs=application ? application->getAAPProviders() : EMPTY(IAAP*);
1210 AAP wrapper(provs,w);
1211 if (wrapper.fail()) {
1212 ap_log_rerror(APLOG_MARK,APLOG_WARNING|APLOG_NOERRNO,SH_AP_R(r),
1213 "shib_auth_checker() didn't recognize require rule: %s\n",w);
1218 const char* vals=ap_table_get(r->headers_in,wrapper->getHeader());
1219 while (*t && vals) {
1220 w=ap_getword_conf(r->pool,&t);
1227 auto_ptr<RegularExpression> re;
1229 delete re.release();
1230 auto_ptr<XMLCh> trans(fromUTF8(w));
1231 auto_ptr<RegularExpression> temp(new RegularExpression(trans.get()));
1235 string vals_str(vals);
1237 for (int i = 0; i < vals_str.length(); i++) {
1238 if (vals_str.at(i) == ';') {
1240 ap_log_rerror(APLOG_MARK,APLOG_WARNING|APLOG_NOERRNO,SH_AP_R(r),
1241 "shib_auth_checker() invalid header encoding %s: starts with semicolon", vals);
1242 return SERVER_ERROR;
1245 if (vals_str.at(i-1) == '\\') {
1246 vals_str.erase(i-1, 1);
1251 string val = vals_str.substr(j, i-j);
1254 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
1255 if (re->matches(trans.get())) {
1256 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1257 "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
1258 SHIB_AP_CHECK_IS_OK;
1261 else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
1262 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1263 "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
1264 SHIB_AP_CHECK_IS_OK;
1267 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1268 "shib_auth_checker() expecting %s, got %s: authorization not granted", w, val.c_str());
1273 string val = vals_str.substr(j, vals_str.length()-j);
1275 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
1276 if (re->matches(trans.get())) {
1277 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1278 "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
1279 SHIB_AP_CHECK_IS_OK;
1282 else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
1283 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1284 "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
1285 SHIB_AP_CHECK_IS_OK;
1288 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1289 "shib_auth_checker() expecting %s, got %s: authorization not granted", w, val.c_str());
1292 catch (XMLException& ex) {
1293 auto_ptr_char tmp(ex.getMessage());
1294 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
1295 "shib_auth_checker caught exception while parsing regular expression (%s): %s",w,tmp.get());
1301 // check if all require directives are true
1302 bool auth_all_OK = true;
1303 for (int i= 0; i<reqs_arr->nelts; i++) {
1304 auth_all_OK &= auth_OK[i];
1309 if (!method_restricted)
1312 if (!application_id) {
1313 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
1314 "shib_auth_checker: Shib-Application-ID header not found in request");
1315 return HTTP_FORBIDDEN;
1317 else if (!application) {
1318 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
1319 "shib_auth_checker: unable to map request to application settings, check configuration");
1320 return HTTP_FORBIDDEN;
1323 ShibMLP markupProcessor;
1324 markupProcessor.insert("requestURL", ap_construct_url(r->pool,r->unparsed_uri,r));
1325 return shib_error_page(r, application, "access", markupProcessor);
1329 #ifndef SHIB_APACHE_13
1332 * Empty cleanup hook, Apache 2.x doesn't check NULL very well...
1334 extern "C" apr_status_t shib_exit(void* data)
1336 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,0,NULL,"shib_exit() done\n");
1344 * Cleanup the (per-process) pool info.
1346 #ifdef SHIB_APACHE_13
1347 extern "C" void shib_child_exit(server_rec* s, SH_AP_POOL* p)
1350 extern "C" apr_status_t shib_child_exit(void* data)
1352 server_rec* s = NULL;
1355 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit(%d) dealing with g_Config..", (int)getpid());
1356 g_Config->shutdown();
1358 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit() done\n");
1360 #ifndef SHIB_APACHE_13
1366 * shire_child_init()
1367 * Things to do when the child process is initialized.
1368 * (or after the configs are read in apache-2)
1370 #ifdef SHIB_APACHE_13
1371 extern "C" void shib_child_init(server_rec* s, SH_AP_POOL* p)
1373 extern "C" void shib_child_init(apr_pool_t* p, server_rec* s)
1376 // Initialize runtime components.
1378 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init(%d) starting", (int)getpid());
1381 ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() already initialized!");
1386 g_Config=&ShibTargetConfig::getConfig();
1387 g_Config->setFeatures(
1388 ShibTargetConfig::Listener |
1389 ShibTargetConfig::Metadata |
1390 ShibTargetConfig::AAP |
1391 ShibTargetConfig::RequestMapper |
1392 ShibTargetConfig::LocalExtensions |
1393 ShibTargetConfig::Logging
1395 if (!g_Config->init(g_szSchemaDir,g_szSHIBConfig)) {
1396 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize SHIB Target");
1401 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize SHIB Target");
1405 // Set the cleanup handler
1406 apr_pool_cleanup_register(p, NULL, &shib_exit, &shib_child_exit);
1408 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() done");
1411 typedef const char* (*config_fn_t)(void);
1413 #ifdef SHIB_APACHE_13
1415 // SHIB Module commands
1417 static command_rec shire_cmds[] = {
1418 {"SHIREConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1419 RSRC_CONF, TAKE1, "Path to shibboleth.xml config file."},
1420 {"ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1421 RSRC_CONF, TAKE1, "Path to shibboleth.xml config file."},
1422 {"ShibSchemaDir", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1423 RSRC_CONF, TAKE1, "Path to Shibboleth XML schema directory."},
1425 {"ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
1426 (void *) XtOffsetOf (shib_server_config, szScheme),
1427 RSRC_CONF, TAKE1, "URL scheme to force into generated URLs for a vhost."},
1429 {"ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1430 (void *) XtOffsetOf (shib_dir_config, bBasicHijack),
1431 OR_AUTHCFG, FLAG, "Respond to AuthType Basic and convert to shib?"},
1432 {"ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1433 (void *) XtOffsetOf (shib_dir_config, bRequireSession),
1434 OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist."},
1435 {"ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1436 (void *) XtOffsetOf (shib_dir_config, bExportAssertion),
1437 OR_AUTHCFG, FLAG, "Export SAML assertion to Shibboleth-defined header?"},
1438 {"AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
1439 (void *) XtOffsetOf (shib_dir_config, szAuthGrpFile),
1440 OR_AUTHCFG, TAKE1, "text file containing group names and member user IDs"},
1441 {"ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1442 (void *) XtOffsetOf (shib_dir_config, bRequireAll),
1443 OR_AUTHCFG, FLAG, "All require directives must match!"},
1449 handler_rec shib_handlers[] = {
1450 { "shib-shire-post", shib_post_handler },
1454 module MODULE_VAR_EXPORT mod_shib = {
1455 STANDARD_MODULE_STUFF,
1456 NULL, /* initializer */
1457 create_shib_dir_config, /* dir config creater */
1458 merge_shib_dir_config, /* dir merger --- default is to override */
1459 create_shib_server_config, /* server config */
1460 merge_shib_server_config, /* merge server config */
1461 shire_cmds, /* command table */
1462 shib_handlers, /* handlers */
1463 NULL, /* filename translation */
1464 shib_check_user, /* check_user_id */
1465 shib_auth_checker, /* check auth */
1466 NULL, /* check access */
1467 NULL, /* type_checker */
1470 NULL, /* header parser */
1471 shib_child_init, /* child_init */
1472 shib_child_exit, /* child_exit */
1473 NULL /* post read-request */
1476 #elif defined(SHIB_APACHE_20)
1478 extern "C" void shib_register_hooks (apr_pool_t *p)
1480 ap_hook_child_init(shib_child_init, NULL, NULL, APR_HOOK_MIDDLE);
1481 ap_hook_check_user_id(shib_check_user, NULL, NULL, APR_HOOK_MIDDLE);
1482 ap_hook_auth_checker(shib_auth_checker, NULL, NULL, APR_HOOK_FIRST);
1483 ap_hook_handler(shib_post_handler, NULL, NULL, APR_HOOK_LAST);
1486 // SHIB Module commands
1489 static command_rec shib_cmds[] = {
1490 AP_INIT_TAKE1("ShibConfig",
1491 (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1492 RSRC_CONF, "Path to shibboleth.xml config file."),
1493 AP_INIT_TAKE1("ShibSchemaDir",
1494 (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1495 RSRC_CONF, "Path to Shibboleth XML schema directory."),
1497 AP_INIT_TAKE1("ShibURLScheme",
1498 (config_fn_t)shib_set_server_string_slot,
1499 (void *) offsetof (shib_server_config, szScheme),
1500 RSRC_CONF, "URL scheme to force into generated URLs for a vhost."),
1502 AP_INIT_FLAG("ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1503 (void *) offsetof (shib_dir_config, bBasicHijack),
1504 OR_AUTHCFG, "Respond to AuthType Basic and convert to shib?"),
1505 AP_INIT_FLAG("ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1506 (void *) offsetof (shib_dir_config, bRequireSession),
1507 OR_AUTHCFG, "Initiates a new session if one does not exist."),
1508 AP_INIT_FLAG("ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1509 (void *) offsetof (shib_dir_config, bExportAssertion),
1510 OR_AUTHCFG, "Export SAML assertion to Shibboleth-defined header?"),
1511 AP_INIT_TAKE1("AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
1512 (void *) offsetof (shib_dir_config, szAuthGrpFile),
1513 OR_AUTHCFG, "text file containing group names and member user IDs"),
1514 AP_INIT_FLAG("ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1515 (void *) offsetof (shib_dir_config, bRequireAll),
1516 OR_AUTHCFG, "All require directives must match!"),
1521 module AP_MODULE_DECLARE_DATA mod_shib = {
1522 STANDARD20_MODULE_STUFF,
1523 create_shib_dir_config, /* create dir config */
1524 merge_shib_dir_config, /* merge dir config --- default is to override */
1525 create_shib_server_config, /* create server config */
1526 merge_shib_server_config, /* merge server config */
1527 shib_cmds, /* command table */
1528 shib_register_hooks /* register hooks */
1532 #error "undefined APACHE version"