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);
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 FatalProfileException("Apache function (setup_client_block) failed while reading profile submission.");
277 if (!ap_should_client_block(m_req))
278 throw FatalProfileException("Apache function (should_client_block) failed while reading profile submission.");
279 if (m_req->remaining > 1024*1024)
280 throw FatalProfileException("Blocked too-large a submission to profile endpoint.");
282 char buff[HUGE_STRING_LEN];
283 ap_hard_timeout("[mod_shib] getPostData", m_req);
284 memset(buff, 0, sizeof(buff));
285 while (ap_get_client_block(m_req, buff, sizeof(buff)-1) > 0) {
286 ap_reset_timeout(m_req);
288 memset(buff, 0, sizeof(buff));
290 ap_kill_timeout(m_req);
294 virtual void clearHeader(const string &name) {
295 ap_table_unset(m_req->headers_in, name.c_str());
297 virtual void setHeader(const string &name, const string &value) {
298 ap_table_set(m_req->headers_in, name.c_str(), value.c_str());
300 virtual string getHeader(const string &name) {
301 const char *hdr = ap_table_get(m_req->headers_in, name.c_str());
302 return string(hdr ? hdr : "");
304 virtual void setRemoteUser(const string &user) {
305 SH_AP_USER(m_req) = ap_pstrdup(m_req->pool, user.c_str());
307 virtual string getRemoteUser(void) {
308 return string(SH_AP_USER(m_req) ? SH_AP_USER(m_req) : "");
310 // override so we can look at the actual auth type and maybe override it.
311 virtual string getAuthType(void) {
312 const char *auth_type=ap_auth_type(m_req);
315 if (strcasecmp(auth_type, "shibboleth")) {
316 if (!strcasecmp(auth_type, "basic") && m_dc->bBasicHijack == 1) {
317 core_dir_config* conf= (core_dir_config*)
318 ap_get_module_config(m_req->per_dir_config,
319 ap_find_linked_module("http_core.c"));
320 auth_type = conf->ap_auth_type = "shibboleth";
323 return string(auth_type);
325 // Override this function because we want to add the Apache Directory override
326 virtual pair<bool,bool> getRequireSession(IRequestMapper::Settings &settings) {
327 pair<bool,bool> requireSession = settings.first->getBool("requireSession");
328 if (!requireSession.first || !requireSession.second)
329 if (m_dc->bRequireSession == 1)
330 requireSession.second=true;
332 return requireSession;
335 virtual HTAccessInfo* getAccessInfo(void) {
336 int m = m_req->method_number;
337 const array_header* reqs_arr = ap_requires(m_req);
341 require_line* reqs = (require_line*) reqs_arr->elts;
343 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req),
344 "REQUIRE nelts: %d", reqs_arr->nelts);
345 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req),
346 "REQUIRE all: %d", m_dc->bRequireAll);
348 HTAccessInfo* ht = new HTAccessInfo();
349 ht->requireAll = (m_dc->bRequireAll >= 0);
350 ht->elements.reserve(reqs_arr->nelts);
351 for (int x = 0; x < reqs_arr->nelts; x++) {
352 HTAccessInfo::RequireLine* rline = new HTAccessInfo::RequireLine();
353 rline->use_line = (reqs[x].method_mask & (1 << m));
354 rline->tokens.reserve(6); // No reason to reserve specifically 6 tokens
355 const char* t = reqs[x].requirement;
356 const char* w = ap_getword_white(m_req->pool, &t);
357 rline->tokens.push_back(w);
359 w = ap_getword_conf(m_req->pool, &t);
360 rline->tokens.push_back(w);
362 ht->elements.push_back(rline);
366 virtual HTGroupTable* getGroupTable(string &user) {
367 if (m_dc->szAuthGrpFile && !user.empty()) {
368 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req),
369 "getGroupTable() using groups file: %s\n",
370 m_dc->szAuthGrpFile);
372 HTGroupTableApache *gt = new HTGroupTableApache(m_req, user.c_str(),
373 m_dc->szAuthGrpFile);
380 virtual void* sendPage(
382 const string content_type,
383 const saml::Iterator<header_t>& headers=EMPTY(header_t),
386 m_req->content_type = ap_psprintf(m_req->pool, content_type.c_str());
387 while (headers.hasNext()) {
388 const header_t& h=headers.next();
389 ap_table_setn(m_req->headers_out, h.first.c_str(), h.second.c_str());
391 ap_send_http_header(m_req);
392 ap_rprintf(m_req, msg.c_str());
395 virtual void* sendRedirect(const string url) {
396 ap_table_set(m_req->headers_out, "Location", url.c_str());
397 return (void*)REDIRECT;
399 virtual void* returnDecline(void) { return (void*)DECLINED; }
400 virtual void* returnOK(void) { return (void*)OK; }
403 shib_dir_config* m_dc;
404 shib_server_config* m_sc;
407 /********************************************************************************/
410 extern "C" int shib_check_user(request_rec* r)
412 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
413 "shib_check_user(%d): ENTER\n", (int)getpid());
415 ostringstream threadid;
416 threadid << "[" << getpid() << "] shib_check_user" << '\0';
417 saml::NDC ndc(threadid.str().c_str());
422 ShibTargetApache sta(r);
424 // Check user authentication, the set the post handler bypass
425 pair<bool,void*> res = sta.doCheckAuthN((sta.m_dc->bRequireSession == 1), true);
426 apr_pool_userdata_setn((const void*)42,g_UserDataKey,NULL,r->pool);
427 if (res.first) return (int)res.second;
429 // user auth was okay -- export the assertions now
430 res = sta.doExportAssertions((sta.m_dc->bExportAssertion == 1));
431 if (res.first) return (int)res.second;
433 // export happened successfully.. this user is ok.
438 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r),
439 "shib_check_user threw an uncaught exception!");
445 extern "C" int shib_post_handler(request_rec* r)
447 ostringstream threadid;
448 threadid << "[" << getpid() << "] shib_post_handler" << '\0';
449 saml::NDC ndc(threadid.str().c_str());
451 #ifndef SHIB_APACHE_13
452 // With 2.x, this handler always runs, though last.
453 // We check if shib_check_user ran, because it will detect a SHIRE request
454 // and dispatch it directly.
456 apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
457 if (data==(const void*)42) {
458 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_post_handler skipped since check_user ran");
463 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
464 "shib_post_handler(%d): ENTER", (int)getpid());
469 ShibTargetApache sta(r);
471 pair<bool,void*> res = sta.doHandleProfile();
472 if (res.first) return (int)res.second;
474 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r),
475 "doHandleProfile() did not do anything.");
480 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r),
481 "shib_post_handler threw an uncaught exception!");
488 * shib_auth_checker() -- a simple resource manager to
489 * process the .htaccess settings and copy attributes
490 * into the HTTP headers.
492 extern "C" int shib_auth_checker(request_rec* r)
494 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
495 "shib_check_user(%d): ENTER", (int)getpid());
497 ostringstream threadid;
498 threadid << "[" << getpid() << "] shib_auth_checker" << '\0';
499 saml::NDC ndc(threadid.str().c_str());
504 ShibTargetApache sta(r);
506 pair<bool,void*> res = sta.doCheckAuthZ();
507 if (res.first) return (int)res.second;
514 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r),
515 "shib_auth_checker threw an uncaught exception!");
522 static char* shib_get_targeturl(request_rec* r, const char* scheme=NULL)
524 // On 1.3, this is always canonical, but on 2.0, UseCanonicalName comes into play.
525 // However, we also have a setting to forcibly replace the scheme for esoteric cases.
527 unsigned port = ap_get_server_port(r);
528 if ((!strcmp(scheme,"http") && port==80) || (!strcmp(scheme,"https") && port==443)) {
529 return ap_pstrcat(r->pool, scheme, "://", ap_get_server_name(r), r->unparsed_uri, NULL);
531 return ap_psprintf(r->pool, "%s://%s:%u%s", scheme, ap_get_server_name(r), port, r->unparsed_uri);
533 return ap_construct_url(r->pool,r->unparsed_uri,r);
536 extern "C" int shib_check_user(request_rec* r)
538 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: ENTER");
539 shib_dir_config* dc=(shib_dir_config*)ap_get_module_config(r->per_dir_config,&mod_shib);
540 shib_server_config* sc=(shib_server_config*)ap_get_module_config(r->server->module_config,&mod_shib);
542 ostringstream threadid;
543 threadid << "[" << getpid() << "] shib_check_user" << '\0';
544 saml::NDC ndc(threadid.str().c_str());
546 const char* targeturl=shib_get_targeturl(r,sc->szScheme);
548 // We lock the configuration system for the duration.
549 IConfig* conf=g_Config->getINI();
552 // Map request to application and content settings.
553 IRequestMapper* mapper=conf->getRequestMapper();
554 Locker locker2(mapper);
555 IRequestMapper::Settings settings=mapper->getSettingsFromParsedURL(
556 (sc-> szScheme ? sc-> szScheme : ap_http_method(r)), ap_get_server_name(r), ap_get_server_port(r), r->unparsed_uri
558 pair<bool,const char*> application_id=settings.first->getString("applicationId");
559 const IApplication* application=conf->getApplication(application_id.second);
561 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
562 "shib_check_user: unable to map request to application settings, check configuration");
566 // Declare SHIRE object for this request.
567 SHIRE shire(application);
569 const char* shireURL=shire.getShireURL(targeturl);
571 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
572 "shib_check_user: unable to map request to proper shireURL setting, check configuration");
576 // Get location of this application's assertion consumer service and see if this is it.
577 if (strstr(targeturl,shireURL)) {
578 return shib_handler(r,application,shire);
581 // We can short circuit the handler if we run this...
582 apr_pool_userdata_setn((const void*)42,g_UserDataKey,NULL,r->pool);
584 // Regular access to arbitrary resource...check AuthType
585 const char *auth_type=ap_auth_type(r);
589 if (strcasecmp(auth_type,"shibboleth")) {
590 if (!strcasecmp(auth_type,"basic") && dc->bBasicHijack==1) {
591 core_dir_config* conf=
592 (core_dir_config*)ap_get_module_config(r->per_dir_config,
593 ap_find_linked_module("http_core.c"));
594 conf->ap_auth_type="shibboleth";
600 pair<bool,bool> requireSession = settings.first->getBool("requireSession");
601 if (!requireSession.first || !requireSession.second)
602 if (dc->bRequireSession==1)
603 requireSession.second=true;
605 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: session check for %s",targeturl);
607 pair<const char*,const char*> shib_cookie=shire.getCookieNameProps(); // always returns *something*
609 // We're in charge, so check for cookie.
610 const char* session_id=NULL;
611 const char* cookies=ap_table_get(r->headers_in,"Cookie");
614 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: cookies found: %s",cookies);
615 if (session_id=strstr(cookies,shib_cookie.first)) {
616 // Yep, we found a cookie -- pull it out (our session_id)
617 session_id+=strlen(shib_cookie.first) + 1; /* Skip over the '=' */
618 char* cookiebuf = ap_pstrdup(r->pool,session_id);
619 char* cookieend = strchr(cookiebuf,';');
621 *cookieend = '\0'; /* Ignore anyting after a ; */
622 session_id=cookiebuf;
626 if (!session_id || !*session_id) {
627 // If no session required, bail now.
628 if (!requireSession.second)
631 // No acceptable cookie, and we require a session. Generate an AuthnRequest.
632 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: no cookie found -- redirecting to WAYF");
633 ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(targeturl)));
637 // Make sure this session is still valid.
638 RPCError* status = NULL;
639 ShibMLP markupProcessor;
640 markupProcessor.insert("requestURL", targeturl);
643 status = shire.sessionIsValid(session_id, r->connection->remote_ip);
645 catch (ShibTargetException &e) {
646 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): %s", e.what());
647 markupProcessor.insert("errorType", "Session Processing Error");
648 markupProcessor.insert("errorText", e.what());
649 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
650 return shib_error_page(r, application, "shire", markupProcessor);
654 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): caught unexpected error");
655 markupProcessor.insert("errorType", "Session Processing Error");
656 markupProcessor.insert("errorText", "Unexpected Exception");
657 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
658 return shib_error_page(r, application, "shire", markupProcessor);
663 if (status->isError()) {
664 ap_log_rerror(APLOG_MARK,APLOG_INFO|APLOG_NOERRNO,SH_AP_R(r),
665 "shib_check_user() session invalid: %s", status->getText());
667 // If no session required, bail now.
668 if (!requireSession.second)
669 return OK; // XXX: Or should this be DECLINED?
670 // Has to be OK because DECLINED will just cause Apache to fail when it can't locate
671 // anything to process the AuthType. No session plus requireSession false means
672 // do not authenticate the user.
673 else if (status->isRetryable()) {
674 // Oops, session is invalid. Generate AuthnRequest.
675 ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(targeturl)));
680 // return the error page to the user
681 markupProcessor.insert(*status);
683 return shib_error_page(r, application, "shire", markupProcessor);
689 #ifdef SHIB_APACHE_13
691 r->connection->ap_auth_type = "shibboleth";
693 r->ap_auth_type = "shibboleth";
695 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: session successfully verified");
697 // This is code transferred in from the auth check to export the attributes.
698 // We could even combine the isSessionValid/getAssertions API...?
701 vector<SAMLAssertion*> assertions;
702 SAMLAuthenticationStatement* sso_statement=NULL;
705 status = rm.getAssertions(session_id, r->connection->remote_ip, assertions, &sso_statement);
707 catch (ShibTargetException &e) {
708 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): %s", e.what());
709 markupProcessor.insert("errorType", "Attribute Processing Error");
710 markupProcessor.insert("errorText", e.what());
711 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
712 return shib_error_page(r, application, "rm", markupProcessor);
716 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): caught unexpected error");
717 markupProcessor.insert("errorType", "Attribute Processing Error");
718 markupProcessor.insert("errorText", "Unexpected Exception");
719 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
720 return shib_error_page(r, application, "rm", markupProcessor);
724 if (status->isError()) {
725 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
726 "shib_check_user() getAssertions failed: %s", status->getText());
728 markupProcessor.insert(*status);
730 return shib_error_page(r, application, "rm", markupProcessor);
734 // Do we have an access control plugin?
735 if (settings.second) {
736 Locker acllock(settings.second);
737 if (!settings.second->authorized(*sso_statement,assertions)) {
738 for (int k = 0; k < assertions.size(); k++)
739 delete assertions[k];
740 delete sso_statement;
741 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): access control provider denied access");
742 return shib_error_page(r, application, "access", markupProcessor);
746 // Get the AAP providers, which contain the attribute policy info.
747 Iterator<IAAP*> provs=application->getAAPProviders();
749 // Clear out the list of mapped attributes
750 while (provs.hasNext()) {
751 IAAP* aap=provs.next();
754 Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
755 while (rules.hasNext()) {
756 const char* header=rules.next()->getHeader();
758 ap_table_unset(r->headers_in,header);
763 for (int k = 0; k < assertions.size(); k++)
764 delete assertions[k];
765 delete sso_statement;
766 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
767 "shib_check_user(): caught unexpected error while clearing headers");
768 markupProcessor.insert("errorType", "Attribute Processing Error");
769 markupProcessor.insert("errorText", "Unexpected Exception");
770 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
771 return shib_error_page(r, application, "rm", markupProcessor);
777 // Maybe export the first assertion.
778 ap_table_unset(r->headers_in,"Shib-Attributes");
779 pair<bool,bool> exp=settings.first->getBool("exportAssertion");
780 if (!exp.first || !exp.second)
781 if (dc->bExportAssertion==1)
783 if (exp.second && assertions.size()) {
785 RM::serialize(*(assertions[0]), assertion);
786 ap_table_set(r->headers_in,"Shib-Attributes", assertion.c_str());
789 // Export the SAML AuthnMethod and the origin site name, and possibly the NameIdentifier.
790 ap_table_unset(r->headers_in,"Shib-Origin-Site");
791 ap_table_unset(r->headers_in,"Shib-Authentication-Method");
792 ap_table_unset(r->headers_in,"Shib-NameIdentifier-Format");
793 auto_ptr_char os(sso_statement->getSubject()->getNameIdentifier()->getNameQualifier());
794 auto_ptr_char am(sso_statement->getAuthMethod());
795 ap_table_set(r->headers_in,"Shib-Origin-Site", os.get());
796 ap_table_set(r->headers_in,"Shib-Authentication-Method", am.get());
799 AAP wrapper(provs,sso_statement->getSubject()->getNameIdentifier()->getFormat(),Constants::SHIB_ATTRIBUTE_NAMESPACE_URI);
800 if (!wrapper.fail() && wrapper->getHeader()) {
801 auto_ptr_char form(sso_statement->getSubject()->getNameIdentifier()->getFormat());
802 auto_ptr_char nameid(sso_statement->getSubject()->getNameIdentifier()->getName());
803 ap_table_set(r->headers_in,"Shib-NameIdentifier-Format",form.get());
804 if (!strcmp(wrapper->getHeader(),"REMOTE_USER"))
805 SH_AP_USER(r)=ap_pstrdup(r->pool,nameid.get());
807 ap_table_set(r->headers_in,wrapper->getHeader(),nameid.get());
810 ap_table_unset(r->headers_in,"Shib-Application-ID");
811 ap_table_set(r->headers_in,"Shib-Application-ID",application_id.second);
813 // Export the attributes.
814 Iterator<SAMLAssertion*> a_iter(assertions);
815 while (a_iter.hasNext()) {
816 SAMLAssertion* assert=a_iter.next();
817 Iterator<SAMLStatement*> statements=assert->getStatements();
818 while (statements.hasNext()) {
819 SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());
822 Iterator<SAMLAttribute*> attrs=astate->getAttributes();
823 while (attrs.hasNext()) {
824 SAMLAttribute* attr=attrs.next();
826 // Are we supposed to export it?
827 AAP wrapper(provs,attr->getName(),attr->getNamespace());
828 if (wrapper.fail() || !wrapper->getHeader())
831 Iterator<string> vals=attr->getSingleByteValues();
832 if (!strcmp(wrapper->getHeader(),"REMOTE_USER") && vals.hasNext())
833 SH_AP_USER(r)=ap_pstrdup(r->pool,vals.next().c_str());
836 char* header = (char*)ap_table_get(r->headers_in, wrapper->getHeader());
838 header=ap_pstrdup(r->pool, header);
842 header = ap_pstrdup(r->pool, "");
843 for (; vals.hasNext(); it++) {
844 string value = vals.next();
845 for (string::size_type pos = value.find_first_of(";", string::size_type(0));
847 pos = value.find_first_of(";", pos)) {
848 value.insert(pos, "\\");
851 header=ap_pstrcat(r->pool, header, (it ? ";" : ""), value.c_str(), NULL);
853 ap_table_setn(r->headers_in, wrapper->getHeader(), header);
860 for (int k = 0; k < assertions.size(); k++)
861 delete assertions[k];
862 delete sso_statement;
867 extern "C" int shib_post_handler(request_rec* r)
869 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
870 "shib_post_handler(%d): ENTER", (int)getpid());
871 shib_server_config* sc=(shib_server_config*)ap_get_module_config(r->server->module_config,&mod_shib);
873 #ifndef SHIB_APACHE_13
874 // With 2.x, this handler always runs, though last.
875 // We check if shib_check_user ran, because it will detect a SHIRE request
876 // and dispatch it directly.
878 apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
879 if (data==(const void*)42) {
880 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_post_handler skipped since check_user ran");
885 ostringstream threadid;
886 threadid << "[" << getpid() << "] shib_post_handler" << '\0';
887 saml::NDC ndc(threadid.str().c_str());
889 // We lock the configuration system for the duration.
890 IConfig* conf=g_Config->getINI();
893 // Map request to application and content settings.
894 IRequestMapper* mapper=conf->getRequestMapper();
895 Locker locker2(mapper);
896 IRequestMapper::Settings settings=mapper->getSettingsFromParsedURL(
897 (sc->szScheme ? sc->szScheme : ap_http_method(r)), ap_get_server_name(r), ap_get_server_port(r), r->unparsed_uri
899 pair<bool,const char*> application_id=settings.first->getString("applicationId");
900 const IApplication* application=conf->getApplication(application_id.second);
902 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
903 "shib_post_handler: unable to map request to application settings, check configuration");
907 // Declare SHIRE object for this request.
908 SHIRE shire(application);
910 return shib_handler(r, application, shire);
913 int shib_handler(request_rec* r, const IApplication* application, SHIRE& shire)
915 shib_server_config* sc=(shib_server_config*)ap_get_module_config(r->server->module_config,&mod_shib);
917 const char* targeturl=shib_get_targeturl(r,sc->szScheme);
919 const char* shireURL=shire.getShireURL(targeturl);
921 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
922 "shib_post_handler: unable to map request to proper shireURL setting, check configuration");
926 // Make sure we only process the SHIRE requests.
927 if (!strstr(targeturl,shireURL))
930 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler() running");
932 const IPropertySet* sessionProps=application->getPropertySet("Sessions");
934 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
935 "shib_post_handler: unable to map request to application session settings, check configuration");
939 pair<const char*,const char*> shib_cookie=shire.getCookieNameProps(); // always returns something
941 ShibMLP markupProcessor;
942 markupProcessor.insert("requestURL", targeturl);
944 // Process SHIRE request
945 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() Beginning SHIRE processing");
948 pair<bool,bool> shireSSL=sessionProps->getBool("shireSSL");
950 // Make sure this is SSL, if it should be
951 if ((!shireSSL.first || shireSSL.second) && strcmp(ap_http_method(r),"https"))
952 throw ShibTargetException(SHIBRPC_OK, "blocked non-SSL access to session creation service");
954 // If this is a GET, we manufacture an AuthnRequest.
955 if (!strcasecmp(r->method,"GET")) {
956 const char* areq=r->args ? shire.getLazyAuthnRequest(r->args) : NULL;
958 throw ShibTargetException(SHIBRPC_OK, "malformed arguments to request a new session");
959 ap_table_setn(r->headers_out, "Location", ap_pstrdup(r->pool,areq));
962 else if (strcasecmp(r->method,"POST")) {
963 throw ShibTargetException(SHIBRPC_OK, "blocked non-POST to SHIRE POST processor");
966 // Sure sure this POST is an appropriate content type
967 const char *ct = ap_table_get(r->headers_in, "Content-type");
968 if (!ct || strcasecmp(ct, "application/x-www-form-urlencoded"))
969 throw ShibTargetException(SHIBRPC_OK,
970 ap_psprintf(r->pool, "blocked bad content-type to SHIRE POST processor: %s", (ct ? ct : "")));
972 // Read the posted data
973 if (ap_setup_client_block(r, REQUEST_CHUNKED_ERROR))
974 throw ShibTargetException(SHIBRPC_OK, "CGI setup_client_block failed");
975 if (!ap_should_client_block(r))
976 throw ShibTargetException(SHIBRPC_OK, "CGI should_client_block failed");
977 if (r->remaining > 1024*1024)
978 throw ShibTargetException (SHIBRPC_OK, "CGI length too long...");
981 char buff[HUGE_STRING_LEN];
982 ap_hard_timeout("[mod_shib] CGI Parser", r);
983 memset(buff, 0, sizeof(buff));
984 while (ap_get_client_block(r, buff, sizeof(buff)-1) > 0) {
987 memset(buff, 0, sizeof(buff));
991 // Parse the submission.
992 pair<const char*,const char*> elements=shire.getFormSubmission(cgistr.c_str(),cgistr.length());
994 // Make sure the SAML Response parameter exists
995 if (!elements.first || !*elements.first)
996 throw ShibTargetException(SHIBRPC_OK, "SHIRE POST failed to find SAMLResponse form element");
998 // Make sure the target parameter exists
999 if (!elements.second || !*elements.second)
1000 throw ShibTargetException(SHIBRPC_OK, "SHIRE POST failed to find TARGET form element");
1002 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1003 "shib_handler() Processing POST for target: %s", elements.second);
1007 RPCError* status = shire.sessionCreate(elements.first, r->connection->remote_ip, cookie);
1009 if (status->isError()) {
1010 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
1011 "shib_handler() POST process failed (%d): %s", status->getCode(), status->getText());
1013 if (status->isRetryable()) {
1015 ap_log_rerror(APLOG_MARK,APLOG_INFO|APLOG_NOERRNO,SH_AP_R(r),
1016 "shib_handler() retryable error, generating new AuthnRequest");
1017 ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(elements.second)));
1021 // return this error to the user.
1022 markupProcessor.insert(*status);
1024 return shib_error_page(r, application, "shire", markupProcessor);
1028 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1029 "shib_handler() POST process succeeded. New session: %s", cookie.c_str());
1031 // We've got a good session, set the cookie...
1032 char* val = ap_psprintf(r->pool,"%s=%s%s",shib_cookie.first,cookie.c_str(),shib_cookie.second);
1033 ap_table_setn(r->err_headers_out, "Set-Cookie", val);
1034 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() setting cookie: %s", val);
1036 // ... and redirect to the target
1037 ap_table_setn(r->headers_out, "Location", ap_pstrdup(r->pool,elements.second));
1040 catch (ShibTargetException &e) {
1041 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() caught exception: %s", e.what());
1042 markupProcessor.insert("errorType", "Session Creation Service Error");
1043 markupProcessor.insert("errorText", e.what());
1044 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
1045 return shib_error_page(r, application, "shire", markupProcessor);
1049 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler(): unexpected exception");
1050 markupProcessor.insert("errorType", "Session Creation Service Error");
1051 markupProcessor.insert("errorText", "Unknown Exception");
1052 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
1053 return shib_error_page(r, application, "shire", markupProcessor);
1057 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_handler() server error");
1058 return SERVER_ERROR;
1061 static int shib_error_page(request_rec* r, const IApplication* app, const char* page, ShibMLP& mlp)
1063 const IPropertySet* props=app->getPropertySet("Errors");
1065 pair<bool,const char*> p=props->getString(page);
1067 ifstream infile(p.second);
1068 if (!infile.fail()) {
1069 const char* res = mlp.run(infile,props);
1071 r->content_type = ap_psprintf(r->pool, "text/html");
1072 ap_send_http_header(r);
1080 ap_log_rerror(APLOG_MARK,APLOG_ERR,SH_AP_R(r),
1081 "shib_error_page() could not process shire error template for application %s",app->getId());
1082 return SERVER_ERROR;
1086 * shib_auth_checker() -- a simple resource manager to
1087 * process the .htaccess settings and copy attributes
1088 * into the HTTP headers.
1090 extern "C" int shib_auth_checker(request_rec* r)
1092 shib_dir_config* dc=
1093 (shib_dir_config*)ap_get_module_config(r->per_dir_config,&mod_shib);
1095 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() executing");
1097 // Regular access to arbitrary resource...check AuthType
1098 const char* auth_type=ap_auth_type(r);
1099 if (!auth_type || strcasecmp(auth_type,"shibboleth"))
1102 ostringstream threadid;
1103 threadid << "[" << getpid() << "] shibrm" << '\0';
1104 saml::NDC ndc(threadid.str().c_str());
1106 // We lock the configuration system for the duration.
1107 IConfig* conf=g_Config->getINI();
1108 Locker locker(conf);
1110 const char* application_id=ap_table_get(r->headers_in,"Shib-Application-ID");
1111 const IApplication* application=NULL;
1113 application = conf->getApplication(application_id);
1117 int m=r->method_number;
1118 bool method_restricted=false;
1121 const array_header* reqs_arr=ap_requires(r);
1125 require_line* reqs=(require_line*)reqs_arr->elts;
1127 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"REQUIRE nelts: %d", reqs_arr->nelts);
1128 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"REQUIRE all: %d", dc->bRequireAll);
1130 vector<bool> auth_OK(reqs_arr->nelts,false);
1132 #define SHIB_AP_CHECK_IS_OK { \
1133 if (dc->bRequireAll < 1) \
1135 auth_OK[x] = true; \
1139 for (int x=0; x<reqs_arr->nelts; x++) {
1141 if (!(reqs[x].method_mask & (1 << m)))
1143 method_restricted=true;
1145 t = reqs[x].requirement;
1146 w = ap_getword_white(r->pool, &t);
1148 if (!strcasecmp(w,"Shibboleth")) {
1149 // This is a dummy rule needed because Apache conflates authn and authz.
1150 // Without some require rule, AuthType is ignored and no check_user hooks run.
1151 SHIB_AP_CHECK_IS_OK;
1153 else if (!strcmp(w,"valid-user") && application_id) {
1154 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting valid-user");
1155 SHIB_AP_CHECK_IS_OK;
1157 else if (!strcmp(w,"user") && SH_AP_USER(r)) {
1160 w=ap_getword_conf(r->pool,&t);
1168 // To do regex matching, we have to convert from UTF-8.
1169 auto_ptr<XMLCh> trans(fromUTF8(w));
1170 RegularExpression re(trans.get());
1171 auto_ptr<XMLCh> trans2(fromUTF8(SH_AP_USER(r)));
1172 if (re.matches(trans2.get())) {
1173 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting user: %s",w);
1174 SHIB_AP_CHECK_IS_OK;
1177 catch (XMLException& ex) {
1178 auto_ptr_char tmp(ex.getMessage());
1179 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
1180 "shib_auth_checker caught exception while parsing regular expression (%s): %s",w,tmp.get());
1183 else if (!strcmp(SH_AP_USER(r),w)) {
1184 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting user: %s",w);
1185 SHIB_AP_CHECK_IS_OK;
1189 else if (!strcmp(w,"group")) {
1190 SH_AP_TABLE* grpstatus=NULL;
1191 if (dc->szAuthGrpFile && SH_AP_USER(r)) {
1192 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() using groups file: %s\n",dc->szAuthGrpFile);
1193 grpstatus=groups_for_user(r,SH_AP_USER(r),dc->szAuthGrpFile);
1199 w=ap_getword_conf(r->pool,&t);
1200 if (ap_table_get(grpstatus,w)) {
1201 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting group: %s",w);
1202 SHIB_AP_CHECK_IS_OK;
1207 Iterator<IAAP*> provs=application ? application->getAAPProviders() : EMPTY(IAAP*);
1208 AAP wrapper(provs,w);
1209 if (wrapper.fail()) {
1210 ap_log_rerror(APLOG_MARK,APLOG_WARNING|APLOG_NOERRNO,SH_AP_R(r),
1211 "shib_auth_checker() didn't recognize require rule: %s\n",w);
1216 const char* vals=ap_table_get(r->headers_in,wrapper->getHeader());
1217 while (*t && vals) {
1218 w=ap_getword_conf(r->pool,&t);
1225 auto_ptr<RegularExpression> re;
1227 delete re.release();
1228 auto_ptr<XMLCh> trans(fromUTF8(w));
1229 auto_ptr<RegularExpression> temp(new RegularExpression(trans.get()));
1233 string vals_str(vals);
1235 for (int i = 0; i < vals_str.length(); i++) {
1236 if (vals_str.at(i) == ';') {
1238 ap_log_rerror(APLOG_MARK,APLOG_WARNING|APLOG_NOERRNO,SH_AP_R(r),
1239 "shib_auth_checker() invalid header encoding %s: starts with semicolon", vals);
1240 return SERVER_ERROR;
1243 if (vals_str.at(i-1) == '\\') {
1244 vals_str.erase(i-1, 1);
1249 string val = vals_str.substr(j, i-j);
1252 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
1253 if (re->matches(trans.get())) {
1254 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1255 "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
1256 SHIB_AP_CHECK_IS_OK;
1259 else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
1260 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1261 "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
1262 SHIB_AP_CHECK_IS_OK;
1265 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1266 "shib_auth_checker() expecting %s, got %s: authorization not granted", w, val.c_str());
1271 string val = vals_str.substr(j, vals_str.length()-j);
1273 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
1274 if (re->matches(trans.get())) {
1275 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1276 "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
1277 SHIB_AP_CHECK_IS_OK;
1280 else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
1281 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1282 "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
1283 SHIB_AP_CHECK_IS_OK;
1286 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1287 "shib_auth_checker() expecting %s, got %s: authorization not granted", w, val.c_str());
1290 catch (XMLException& ex) {
1291 auto_ptr_char tmp(ex.getMessage());
1292 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
1293 "shib_auth_checker caught exception while parsing regular expression (%s): %s",w,tmp.get());
1299 // check if all require directives are true
1300 bool auth_all_OK = true;
1301 for (int i= 0; i<reqs_arr->nelts; i++) {
1302 auth_all_OK &= auth_OK[i];
1307 if (!method_restricted)
1310 if (!application_id) {
1311 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
1312 "shib_auth_checker: Shib-Application-ID header not found in request");
1313 return HTTP_FORBIDDEN;
1315 else if (!application) {
1316 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
1317 "shib_auth_checker: unable to map request to application settings, check configuration");
1318 return HTTP_FORBIDDEN;
1321 ShibMLP markupProcessor;
1322 markupProcessor.insert("requestURL", ap_construct_url(r->pool,r->unparsed_uri,r));
1323 return shib_error_page(r, application, "access", markupProcessor);
1327 #ifndef SHIB_APACHE_13
1330 * Empty cleanup hook, Apache 2.x doesn't check NULL very well...
1332 extern "C" apr_status_t shib_exit(void* data)
1334 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,0,NULL,"shib_exit() done\n");
1342 * Cleanup the (per-process) pool info.
1344 #ifdef SHIB_APACHE_13
1345 extern "C" void shib_child_exit(server_rec* s, SH_AP_POOL* p)
1348 extern "C" apr_status_t shib_child_exit(void* data)
1350 server_rec* s = NULL;
1353 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit(%d) dealing with g_Config..", (int)getpid());
1354 g_Config->shutdown();
1356 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit() done\n");
1358 #ifndef SHIB_APACHE_13
1364 * shire_child_init()
1365 * Things to do when the child process is initialized.
1366 * (or after the configs are read in apache-2)
1368 #ifdef SHIB_APACHE_13
1369 extern "C" void shib_child_init(server_rec* s, SH_AP_POOL* p)
1371 extern "C" void shib_child_init(apr_pool_t* p, server_rec* s)
1374 // Initialize runtime components.
1376 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init(%d) starting", (int)getpid());
1379 ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() already initialized!");
1384 g_Config=&ShibTargetConfig::getConfig();
1385 g_Config->setFeatures(
1386 ShibTargetConfig::Listener |
1387 ShibTargetConfig::Metadata |
1388 ShibTargetConfig::AAP |
1389 ShibTargetConfig::RequestMapper |
1390 ShibTargetConfig::LocalExtensions |
1391 ShibTargetConfig::Logging
1393 if (!g_Config->init(g_szSchemaDir,g_szSHIBConfig)) {
1394 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize SHIB Target");
1399 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize SHIB Target");
1403 // Set the cleanup handler
1404 apr_pool_cleanup_register(p, NULL, &shib_exit, &shib_child_exit);
1406 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() done");
1409 typedef const char* (*config_fn_t)(void);
1411 #ifdef SHIB_APACHE_13
1413 // SHIB Module commands
1415 static command_rec shire_cmds[] = {
1416 {"SHIREConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1417 RSRC_CONF, TAKE1, "Path to shibboleth.xml config file."},
1418 {"ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1419 RSRC_CONF, TAKE1, "Path to shibboleth.xml config file."},
1420 {"ShibSchemaDir", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1421 RSRC_CONF, TAKE1, "Path to Shibboleth XML schema directory."},
1423 {"ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
1424 (void *) XtOffsetOf (shib_server_config, szScheme),
1425 RSRC_CONF, TAKE1, "URL scheme to force into generated URLs for a vhost."},
1427 {"ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1428 (void *) XtOffsetOf (shib_dir_config, bBasicHijack),
1429 OR_AUTHCFG, FLAG, "Respond to AuthType Basic and convert to shib?"},
1430 {"ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1431 (void *) XtOffsetOf (shib_dir_config, bRequireSession),
1432 OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist."},
1433 {"ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1434 (void *) XtOffsetOf (shib_dir_config, bExportAssertion),
1435 OR_AUTHCFG, FLAG, "Export SAML assertion to Shibboleth-defined header?"},
1436 {"AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
1437 (void *) XtOffsetOf (shib_dir_config, szAuthGrpFile),
1438 OR_AUTHCFG, TAKE1, "text file containing group names and member user IDs"},
1439 {"ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1440 (void *) XtOffsetOf (shib_dir_config, bRequireAll),
1441 OR_AUTHCFG, FLAG, "All require directives must match!"},
1447 handler_rec shib_handlers[] = {
1448 { "shib-shire-post", shib_post_handler },
1452 module MODULE_VAR_EXPORT mod_shib = {
1453 STANDARD_MODULE_STUFF,
1454 NULL, /* initializer */
1455 create_shib_dir_config, /* dir config creater */
1456 merge_shib_dir_config, /* dir merger --- default is to override */
1457 create_shib_server_config, /* server config */
1458 merge_shib_server_config, /* merge server config */
1459 shire_cmds, /* command table */
1460 shib_handlers, /* handlers */
1461 NULL, /* filename translation */
1462 shib_check_user, /* check_user_id */
1463 shib_auth_checker, /* check auth */
1464 NULL, /* check access */
1465 NULL, /* type_checker */
1468 NULL, /* header parser */
1469 shib_child_init, /* child_init */
1470 shib_child_exit, /* child_exit */
1471 NULL /* post read-request */
1474 #elif defined(SHIB_APACHE_20)
1476 extern "C" void shib_register_hooks (apr_pool_t *p)
1478 ap_hook_child_init(shib_child_init, NULL, NULL, APR_HOOK_MIDDLE);
1479 ap_hook_check_user_id(shib_check_user, NULL, NULL, APR_HOOK_MIDDLE);
1480 ap_hook_auth_checker(shib_auth_checker, NULL, NULL, APR_HOOK_FIRST);
1481 ap_hook_handler(shib_post_handler, NULL, NULL, APR_HOOK_LAST);
1484 // SHIB Module commands
1487 static command_rec shib_cmds[] = {
1488 AP_INIT_TAKE1("ShibConfig",
1489 (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1490 RSRC_CONF, "Path to shibboleth.xml config file."),
1491 AP_INIT_TAKE1("ShibSchemaDir",
1492 (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1493 RSRC_CONF, "Path to Shibboleth XML schema directory."),
1495 AP_INIT_TAKE1("ShibURLScheme",
1496 (config_fn_t)shib_set_server_string_slot,
1497 (void *) offsetof (shib_server_config, szScheme),
1498 RSRC_CONF, "URL scheme to force into generated URLs for a vhost."),
1500 AP_INIT_FLAG("ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1501 (void *) offsetof (shib_dir_config, bBasicHijack),
1502 OR_AUTHCFG, "Respond to AuthType Basic and convert to shib?"),
1503 AP_INIT_FLAG("ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1504 (void *) offsetof (shib_dir_config, bRequireSession),
1505 OR_AUTHCFG, "Initiates a new session if one does not exist."),
1506 AP_INIT_FLAG("ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1507 (void *) offsetof (shib_dir_config, bExportAssertion),
1508 OR_AUTHCFG, "Export SAML assertion to Shibboleth-defined header?"),
1509 AP_INIT_TAKE1("AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
1510 (void *) offsetof (shib_dir_config, szAuthGrpFile),
1511 OR_AUTHCFG, "text file containing group names and member user IDs"),
1512 AP_INIT_FLAG("ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1513 (void *) offsetof (shib_dir_config, bRequireAll),
1514 OR_AUTHCFG, "All require directives must match!"),
1519 module AP_MODULE_DECLARE_DATA mod_shib = {
1520 STANDARD20_MODULE_STUFF,
1521 create_shib_dir_config, /* create dir config */
1522 merge_shib_dir_config, /* merge dir config --- default is to override */
1523 create_shib_server_config, /* create server config */
1524 merge_shib_server_config, /* merge server config */
1525 shib_cmds, /* command table */
1526 shib_register_hooks /* register hooks */
1530 #error "undefined APACHE version"