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 /********************************************************************************/
158 // Some other useful helper function(s)
160 static SH_AP_TABLE* groups_for_user(request_rec* r, const char* user, char* grpfile)
163 SH_AP_TABLE* grps=ap_make_table(r->pool,15);
164 char l[MAX_STRING_LEN];
165 const char *group_name, *ll, *w;
167 #ifdef SHIB_APACHE_13
168 if (!(f=ap_pcfg_openfile(r->pool,grpfile))) {
170 if (ap_pcfg_openfile(&f,r->pool,grpfile) != APR_SUCCESS) {
172 ap_log_rerror(APLOG_MARK,APLOG_DEBUG,SH_AP_R(r),"groups_for_user() could not open group file: %s\n",grpfile);
177 #ifdef SHIB_APACHE_13
178 sp=ap_make_sub_pool(r->pool);
180 if (apr_pool_create(&sp,r->pool) != APR_SUCCESS) {
181 ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,
182 "groups_for_user() could not create a subpool");
187 while (!(ap_cfg_getline(l,MAX_STRING_LEN,f))) {
188 if ((*l=='#') || (!*l))
193 group_name=ap_getword(sp,&ll,':');
196 w=ap_getword_conf(sp,&ll);
197 if (!strcmp(w,user)) {
198 ap_table_setn(grps,ap_pstrdup(r->pool,group_name),"in");
208 /********************************************************************************/
209 // Apache ShibTarget subclass(es) here.
211 class HTGroupTableApache : public HTGroupTable
214 HTGroupTableApache(request_rec* r, const char *user, char *grpfile) {
215 groups = groups_for_user(r, user, grpfile);
217 throw ShibTargetException(SHIBRPC_OK, "EEP");
219 ~HTGroupTableApache() {}
220 bool lookup(const char *entry) { return (ap_table_get(groups, entry)!=NULL); }
224 class ShibTargetApache : public ShibTarget
227 ShibTargetApache(request_rec* req) {
228 m_sc = (shib_server_config*)
229 ap_get_module_config(req->server->module_config, &mod_shib);
231 m_dc = (shib_dir_config*)ap_get_module_config(req->per_dir_config, &mod_shib);
233 const char* ct = ap_table_get(req->headers_in, "Content-type");
235 init(g_Config, string(m_sc->szScheme ? m_sc->szScheme : ap_http_method(req)),
236 string(ap_get_server_name(req)), (int)ap_get_server_port(req),
237 string(req->unparsed_uri), string(ct ? ct : ""),
238 string(req->connection->remote_ip), string(req->method));
242 ~ShibTargetApache() { }
244 virtual void log(ShibLogLevel level, const string &msg) {
245 ap_log_rerror(APLOG_MARK,
246 (level == LogLevelDebug ? APLOG_DEBUG :
247 (level == LogLevelInfo ? APLOG_INFO :
248 (level == LogLevelWarn ? APLOG_WARNING :
249 APLOG_ERR)))|APLOG_NOERRNO, SH_AP_R(m_req),
252 virtual string getCookies(void) {
253 const char *c = ap_table_get(m_req->headers_in, "Cookie");
254 return string(c ? c : "");
256 virtual void setCookie(const string &name, const string &value) {
257 char* val = ap_psprintf(m_req->pool, "%s=%s", name.c_str(), value.c_str());
258 ap_table_setn(m_req->err_headers_out, "Set-Cookie", val);
260 virtual string getArgs(void) { return string(m_req->args ? m_req->args : ""); }
261 virtual string getPostData(void) {
262 // Read the posted data
263 if (ap_setup_client_block(m_req, REQUEST_CHUNKED_ERROR))
264 throw ShibTargetException(SHIBRPC_OK, "CGI setup_client_block failed");
265 if (!ap_should_client_block(m_req))
266 throw ShibTargetException(SHIBRPC_OK, "CGI should_client_block failed");
267 if (m_req->remaining > 1024*1024)
268 throw ShibTargetException (SHIBRPC_OK, "CGI length too long...");
271 char buff[HUGE_STRING_LEN];
272 ap_hard_timeout("[mod_shib] getPostData", m_req);
273 memset(buff, 0, sizeof(buff));
274 while (ap_get_client_block(m_req, buff, sizeof(buff)-1) > 0) {
275 ap_reset_timeout(m_req);
277 memset(buff, 0, sizeof(buff));
279 ap_kill_timeout(m_req);
283 virtual void clearHeader(const string &name) {
284 ap_table_unset(m_req->headers_in, name.c_str());
286 virtual void setHeader(const string &name, const string &value) {
287 ap_table_set(m_req->headers_in, name.c_str(), value.c_str());
289 virtual string getHeader(const string &name) {
290 const char *hdr = ap_table_get(m_req->headers_in, name.c_str());
291 return string(hdr ? hdr : "");
293 virtual void setRemoteUser(const string &user) {
294 SH_AP_USER(m_req) = ap_pstrdup(m_req->pool, user.c_str());
296 virtual string getRemoteUser(void) {
297 return string(SH_AP_USER(m_req) ? SH_AP_USER(m_req) : "");
299 // override so we can look at the actual auth type and maybe override it.
300 virtual string getAuthType(void) {
301 const char *auth_type=ap_auth_type(m_req);
304 if (strcasecmp(auth_type, "shibboleth")) {
305 if (!strcasecmp(auth_type, "basic") && m_dc->bBasicHijack == 1) {
306 core_dir_config* conf= (core_dir_config*)
307 ap_get_module_config(m_req->per_dir_config,
308 ap_find_linked_module("http_core.c"));
309 auth_type = conf->ap_auth_type = "shibboleth";
312 return string(auth_type);
314 // Override this function because we want to add the Apache Directory override
315 virtual pair<bool,bool> getRequireSession(IRequestMapper::Settings &settings) {
316 pair<bool,bool> requireSession = settings.first->getBool("requireSession");
317 if (!requireSession.first || !requireSession.second)
318 if (m_dc->bRequireSession == 1)
319 requireSession.second=true;
321 return requireSession;
324 virtual HTAccessInfo* getAccessInfo(void) {
325 int m = m_req->method_number;
326 const array_header* reqs_arr = ap_requires(m_req);
330 require_line* reqs = (require_line*) reqs_arr->elts;
332 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req),
333 "REQUIRE nelts: %d", reqs_arr->nelts);
334 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req),
335 "REQUIRE all: %d", m_dc->bRequireAll);
337 HTAccessInfo* ht = new HTAccessInfo();
338 ht->requireAll = (m_dc->bRequireAll >= 0);
339 ht->elements.reserve(reqs_arr->nelts);
340 for (int x = 0; x < reqs_arr->nelts; x++) {
341 HTAccessInfo::RequireLine* rline = new HTAccessInfo::RequireLine();
342 rline->use_line = (reqs[x].method_mask & (1 << m));
343 rline->tokens.reserve(6); // No reason to reserve specifically 6 tokens
344 const char* t = reqs[x].requirement;
345 const char* w = ap_getword_white(m_req->pool, &t);
346 rline->tokens.push_back(w);
348 w = ap_getword_conf(m_req->pool, &t);
349 rline->tokens.push_back(w);
351 ht->elements.push_back(rline);
355 virtual HTGroupTable* getGroupTable(string &user) {
356 if (m_dc->szAuthGrpFile && !user.empty()) {
357 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req),
358 "getGroupTable() using groups file: %s\n",
359 m_dc->szAuthGrpFile);
361 HTGroupTableApache *gt = new HTGroupTableApache(m_req, user.c_str(),
362 m_dc->szAuthGrpFile);
369 virtual void* sendPage(const string &msg, const string content_type,
370 const pair<string, string> headers[], int code) {
371 m_req->content_type = ap_psprintf(m_req->pool, content_type.c_str());
372 // XXX: push headers and code into the response
373 ap_send_http_header(m_req);
374 ap_rprintf(m_req, msg.c_str());
377 virtual void* sendRedirect(const string url) {
378 ap_table_set(m_req->headers_out, "Location", url.c_str());
379 return (void*)REDIRECT;
381 virtual void* returnDecline(void) { return (void*)DECLINED; }
382 virtual void* returnOK(void) { return (void*)OK; }
385 shib_dir_config* m_dc;
386 shib_server_config* m_sc;
389 /********************************************************************************/
392 extern "C" int shib_check_user(request_rec* r)
394 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
395 "shib_check_user(%d): ENTER\n", (int)getpid());
397 ostringstream threadid;
398 threadid << "[" << getpid() << "] shib_check_user" << '\0';
399 saml::NDC ndc(threadid.str().c_str());
404 ShibTargetApache sta(r);
406 // Check user authentication, the set the post handler bypass
407 pair<bool,void*> res = sta.doCheckAuthN((sta.m_dc->bRequireSession == 1), true);
408 apr_pool_userdata_setn((const void*)42,g_UserDataKey,NULL,r->pool);
409 if (res.first) return (int)res.second;
411 // user auth was okay -- export the assertions now
412 res = sta.doExportAssertions((sta.m_dc->bExportAssertion == 1));
413 if (res.first) return (int)res.second;
415 // export happened successfully.. this user is ok.
420 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r),
421 "shib_check_user threw an uncaught exception!");
427 extern "C" int shib_post_handler(request_rec* r)
429 ostringstream threadid;
430 threadid << "[" << getpid() << "] shib_post_handler" << '\0';
431 saml::NDC ndc(threadid.str().c_str());
433 #ifndef SHIB_APACHE_13
434 // With 2.x, this handler always runs, though last.
435 // We check if shib_check_user ran, because it will detect a SHIRE request
436 // and dispatch it directly.
438 apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
439 if (data==(const void*)42) {
440 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_post_handler skipped since check_user ran");
445 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
446 "shib_post_handler(%d): ENTER", (int)getpid());
451 ShibTargetApache sta(r);
453 pair<bool,void*> res = sta.doHandlePOST();
454 if (res.first) return (int)res.second;
456 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r),
457 "doHandlePOST() did not do anything.");
462 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r),
463 "shib_post_handler threw an uncaught exception!");
470 * shib_auth_checker() -- a simple resource manager to
471 * process the .htaccess settings and copy attributes
472 * into the HTTP headers.
474 extern "C" int shib_auth_checker(request_rec* r)
476 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
477 "shib_check_user(%d): ENTER", (int)getpid());
479 ostringstream threadid;
480 threadid << "[" << getpid() << "] shib_auth_checker" << '\0';
481 saml::NDC ndc(threadid.str().c_str());
486 ShibTargetApache sta(r);
488 pair<bool,void*> res = sta.doCheckAuthZ();
489 if (res.first) return (int)res.second;
496 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r),
497 "shib_auth_checker threw an uncaught exception!");
504 static char* shib_get_targeturl(request_rec* r, const char* scheme=NULL)
506 // On 1.3, this is always canonical, but on 2.0, UseCanonicalName comes into play.
507 // However, we also have a setting to forcibly replace the scheme for esoteric cases.
509 unsigned port = ap_get_server_port(r);
510 if ((!strcmp(scheme,"http") && port==80) || (!strcmp(scheme,"https") && port==443)) {
511 return ap_pstrcat(r->pool, scheme, "://", ap_get_server_name(r), r->unparsed_uri, NULL);
513 return ap_psprintf(r->pool, "%s://%s:%u%s", scheme, ap_get_server_name(r), port, r->unparsed_uri);
515 return ap_construct_url(r->pool,r->unparsed_uri,r);
518 extern "C" int shib_check_user(request_rec* r)
520 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: ENTER");
521 shib_dir_config* dc=(shib_dir_config*)ap_get_module_config(r->per_dir_config,&mod_shib);
522 shib_server_config* sc=(shib_server_config*)ap_get_module_config(r->server->module_config,&mod_shib);
524 ostringstream threadid;
525 threadid << "[" << getpid() << "] shib_check_user" << '\0';
526 saml::NDC ndc(threadid.str().c_str());
528 const char* targeturl=shib_get_targeturl(r,sc->szScheme);
530 // We lock the configuration system for the duration.
531 IConfig* conf=g_Config->getINI();
534 // Map request to application and content settings.
535 IRequestMapper* mapper=conf->getRequestMapper();
536 Locker locker2(mapper);
537 IRequestMapper::Settings settings=mapper->getSettingsFromParsedURL(
538 (sc-> szScheme ? sc-> szScheme : ap_http_method(r)), ap_get_server_name(r), ap_get_server_port(r), r->unparsed_uri
540 pair<bool,const char*> application_id=settings.first->getString("applicationId");
541 const IApplication* application=conf->getApplication(application_id.second);
543 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
544 "shib_check_user: unable to map request to application settings, check configuration");
548 // Declare SHIRE object for this request.
549 SHIRE shire(application);
551 const char* shireURL=shire.getShireURL(targeturl);
553 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
554 "shib_check_user: unable to map request to proper shireURL setting, check configuration");
558 // Get location of this application's assertion consumer service and see if this is it.
559 if (strstr(targeturl,shireURL)) {
560 return shib_handler(r,application,shire);
563 // We can short circuit the handler if we run this...
564 apr_pool_userdata_setn((const void*)42,g_UserDataKey,NULL,r->pool);
566 // Regular access to arbitrary resource...check AuthType
567 const char *auth_type=ap_auth_type(r);
571 if (strcasecmp(auth_type,"shibboleth")) {
572 if (!strcasecmp(auth_type,"basic") && dc->bBasicHijack==1) {
573 core_dir_config* conf=
574 (core_dir_config*)ap_get_module_config(r->per_dir_config,
575 ap_find_linked_module("http_core.c"));
576 conf->ap_auth_type="shibboleth";
582 pair<bool,bool> requireSession = settings.first->getBool("requireSession");
583 if (!requireSession.first || !requireSession.second)
584 if (dc->bRequireSession==1)
585 requireSession.second=true;
587 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: session check for %s",targeturl);
589 pair<const char*,const char*> shib_cookie=shire.getCookieNameProps(); // always returns *something*
591 // We're in charge, so check for cookie.
592 const char* session_id=NULL;
593 const char* cookies=ap_table_get(r->headers_in,"Cookie");
596 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: cookies found: %s",cookies);
597 if (session_id=strstr(cookies,shib_cookie.first)) {
598 // Yep, we found a cookie -- pull it out (our session_id)
599 session_id+=strlen(shib_cookie.first) + 1; /* Skip over the '=' */
600 char* cookiebuf = ap_pstrdup(r->pool,session_id);
601 char* cookieend = strchr(cookiebuf,';');
603 *cookieend = '\0'; /* Ignore anyting after a ; */
604 session_id=cookiebuf;
608 if (!session_id || !*session_id) {
609 // If no session required, bail now.
610 if (!requireSession.second)
613 // No acceptable cookie, and we require a session. Generate an AuthnRequest.
614 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: no cookie found -- redirecting to WAYF");
615 ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(targeturl)));
619 // Make sure this session is still valid.
620 RPCError* status = NULL;
621 ShibMLP markupProcessor;
622 markupProcessor.insert("requestURL", targeturl);
625 status = shire.sessionIsValid(session_id, r->connection->remote_ip);
627 catch (ShibTargetException &e) {
628 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): %s", e.what());
629 markupProcessor.insert("errorType", "Session Processing Error");
630 markupProcessor.insert("errorText", e.what());
631 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
632 return shib_error_page(r, application, "shire", markupProcessor);
636 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): caught unexpected error");
637 markupProcessor.insert("errorType", "Session Processing Error");
638 markupProcessor.insert("errorText", "Unexpected Exception");
639 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
640 return shib_error_page(r, application, "shire", markupProcessor);
645 if (status->isError()) {
646 ap_log_rerror(APLOG_MARK,APLOG_INFO|APLOG_NOERRNO,SH_AP_R(r),
647 "shib_check_user() session invalid: %s", status->getText());
649 // If no session required, bail now.
650 if (!requireSession.second)
651 return OK; // XXX: Or should this be DECLINED?
652 // Has to be OK because DECLINED will just cause Apache to fail when it can't locate
653 // anything to process the AuthType. No session plus requireSession false means
654 // do not authenticate the user.
655 else if (status->isRetryable()) {
656 // Oops, session is invalid. Generate AuthnRequest.
657 ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(targeturl)));
662 // return the error page to the user
663 markupProcessor.insert(*status);
665 return shib_error_page(r, application, "shire", markupProcessor);
671 #ifdef SHIB_APACHE_13
673 r->connection->ap_auth_type = "shibboleth";
675 r->ap_auth_type = "shibboleth";
677 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: session successfully verified");
679 // This is code transferred in from the auth check to export the attributes.
680 // We could even combine the isSessionValid/getAssertions API...?
683 vector<SAMLAssertion*> assertions;
684 SAMLAuthenticationStatement* sso_statement=NULL;
687 status = rm.getAssertions(session_id, r->connection->remote_ip, assertions, &sso_statement);
689 catch (ShibTargetException &e) {
690 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): %s", e.what());
691 markupProcessor.insert("errorType", "Attribute Processing Error");
692 markupProcessor.insert("errorText", e.what());
693 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
694 return shib_error_page(r, application, "rm", markupProcessor);
698 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): caught unexpected error");
699 markupProcessor.insert("errorType", "Attribute Processing Error");
700 markupProcessor.insert("errorText", "Unexpected Exception");
701 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
702 return shib_error_page(r, application, "rm", markupProcessor);
706 if (status->isError()) {
707 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
708 "shib_check_user() getAssertions failed: %s", status->getText());
710 markupProcessor.insert(*status);
712 return shib_error_page(r, application, "rm", markupProcessor);
716 // Do we have an access control plugin?
717 if (settings.second) {
718 Locker acllock(settings.second);
719 if (!settings.second->authorized(*sso_statement,assertions)) {
720 for (int k = 0; k < assertions.size(); k++)
721 delete assertions[k];
722 delete sso_statement;
723 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): access control provider denied access");
724 return shib_error_page(r, application, "access", markupProcessor);
728 // Get the AAP providers, which contain the attribute policy info.
729 Iterator<IAAP*> provs=application->getAAPProviders();
731 // Clear out the list of mapped attributes
732 while (provs.hasNext()) {
733 IAAP* aap=provs.next();
736 Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
737 while (rules.hasNext()) {
738 const char* header=rules.next()->getHeader();
740 ap_table_unset(r->headers_in,header);
745 for (int k = 0; k < assertions.size(); k++)
746 delete assertions[k];
747 delete sso_statement;
748 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
749 "shib_check_user(): caught unexpected error while clearing headers");
750 markupProcessor.insert("errorType", "Attribute Processing Error");
751 markupProcessor.insert("errorText", "Unexpected Exception");
752 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
753 return shib_error_page(r, application, "rm", markupProcessor);
759 // Maybe export the first assertion.
760 ap_table_unset(r->headers_in,"Shib-Attributes");
761 pair<bool,bool> exp=settings.first->getBool("exportAssertion");
762 if (!exp.first || !exp.second)
763 if (dc->bExportAssertion==1)
765 if (exp.second && assertions.size()) {
767 RM::serialize(*(assertions[0]), assertion);
768 ap_table_set(r->headers_in,"Shib-Attributes", assertion.c_str());
771 // Export the SAML AuthnMethod and the origin site name, and possibly the NameIdentifier.
772 ap_table_unset(r->headers_in,"Shib-Origin-Site");
773 ap_table_unset(r->headers_in,"Shib-Authentication-Method");
774 ap_table_unset(r->headers_in,"Shib-NameIdentifier-Format");
775 auto_ptr_char os(sso_statement->getSubject()->getNameIdentifier()->getNameQualifier());
776 auto_ptr_char am(sso_statement->getAuthMethod());
777 ap_table_set(r->headers_in,"Shib-Origin-Site", os.get());
778 ap_table_set(r->headers_in,"Shib-Authentication-Method", am.get());
781 AAP wrapper(provs,sso_statement->getSubject()->getNameIdentifier()->getFormat(),Constants::SHIB_ATTRIBUTE_NAMESPACE_URI);
782 if (!wrapper.fail() && wrapper->getHeader()) {
783 auto_ptr_char form(sso_statement->getSubject()->getNameIdentifier()->getFormat());
784 auto_ptr_char nameid(sso_statement->getSubject()->getNameIdentifier()->getName());
785 ap_table_set(r->headers_in,"Shib-NameIdentifier-Format",form.get());
786 if (!strcmp(wrapper->getHeader(),"REMOTE_USER"))
787 SH_AP_USER(r)=ap_pstrdup(r->pool,nameid.get());
789 ap_table_set(r->headers_in,wrapper->getHeader(),nameid.get());
792 ap_table_unset(r->headers_in,"Shib-Application-ID");
793 ap_table_set(r->headers_in,"Shib-Application-ID",application_id.second);
795 // Export the attributes.
796 Iterator<SAMLAssertion*> a_iter(assertions);
797 while (a_iter.hasNext()) {
798 SAMLAssertion* assert=a_iter.next();
799 Iterator<SAMLStatement*> statements=assert->getStatements();
800 while (statements.hasNext()) {
801 SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());
804 Iterator<SAMLAttribute*> attrs=astate->getAttributes();
805 while (attrs.hasNext()) {
806 SAMLAttribute* attr=attrs.next();
808 // Are we supposed to export it?
809 AAP wrapper(provs,attr->getName(),attr->getNamespace());
810 if (wrapper.fail() || !wrapper->getHeader())
813 Iterator<string> vals=attr->getSingleByteValues();
814 if (!strcmp(wrapper->getHeader(),"REMOTE_USER") && vals.hasNext())
815 SH_AP_USER(r)=ap_pstrdup(r->pool,vals.next().c_str());
818 char* header = (char*)ap_table_get(r->headers_in, wrapper->getHeader());
820 header=ap_pstrdup(r->pool, header);
824 header = ap_pstrdup(r->pool, "");
825 for (; vals.hasNext(); it++) {
826 string value = vals.next();
827 for (string::size_type pos = value.find_first_of(";", string::size_type(0));
829 pos = value.find_first_of(";", pos)) {
830 value.insert(pos, "\\");
833 header=ap_pstrcat(r->pool, header, (it ? ";" : ""), value.c_str(), NULL);
835 ap_table_setn(r->headers_in, wrapper->getHeader(), header);
842 for (int k = 0; k < assertions.size(); k++)
843 delete assertions[k];
844 delete sso_statement;
849 extern "C" int shib_post_handler(request_rec* r)
851 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
852 "shib_post_handler(%d): ENTER", (int)getpid());
853 shib_server_config* sc=(shib_server_config*)ap_get_module_config(r->server->module_config,&mod_shib);
855 #ifndef SHIB_APACHE_13
856 // With 2.x, this handler always runs, though last.
857 // We check if shib_check_user ran, because it will detect a SHIRE request
858 // and dispatch it directly.
860 apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
861 if (data==(const void*)42) {
862 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_post_handler skipped since check_user ran");
867 ostringstream threadid;
868 threadid << "[" << getpid() << "] shib_post_handler" << '\0';
869 saml::NDC ndc(threadid.str().c_str());
871 // We lock the configuration system for the duration.
872 IConfig* conf=g_Config->getINI();
875 // Map request to application and content settings.
876 IRequestMapper* mapper=conf->getRequestMapper();
877 Locker locker2(mapper);
878 IRequestMapper::Settings settings=mapper->getSettingsFromParsedURL(
879 (sc->szScheme ? sc->szScheme : ap_http_method(r)), ap_get_server_name(r), ap_get_server_port(r), r->unparsed_uri
881 pair<bool,const char*> application_id=settings.first->getString("applicationId");
882 const IApplication* application=conf->getApplication(application_id.second);
884 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
885 "shib_post_handler: unable to map request to application settings, check configuration");
889 // Declare SHIRE object for this request.
890 SHIRE shire(application);
892 return shib_handler(r, application, shire);
895 int shib_handler(request_rec* r, const IApplication* application, SHIRE& shire)
897 shib_server_config* sc=(shib_server_config*)ap_get_module_config(r->server->module_config,&mod_shib);
899 const char* targeturl=shib_get_targeturl(r,sc->szScheme);
901 const char* shireURL=shire.getShireURL(targeturl);
903 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
904 "shib_post_handler: unable to map request to proper shireURL setting, check configuration");
908 // Make sure we only process the SHIRE requests.
909 if (!strstr(targeturl,shireURL))
912 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler() running");
914 const IPropertySet* sessionProps=application->getPropertySet("Sessions");
916 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
917 "shib_post_handler: unable to map request to application session settings, check configuration");
921 pair<const char*,const char*> shib_cookie=shire.getCookieNameProps(); // always returns something
923 ShibMLP markupProcessor;
924 markupProcessor.insert("requestURL", targeturl);
926 // Process SHIRE request
927 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() Beginning SHIRE processing");
930 pair<bool,bool> shireSSL=sessionProps->getBool("shireSSL");
932 // Make sure this is SSL, if it should be
933 if ((!shireSSL.first || shireSSL.second) && strcmp(ap_http_method(r),"https"))
934 throw ShibTargetException(SHIBRPC_OK, "blocked non-SSL access to session creation service");
936 // If this is a GET, we manufacture an AuthnRequest.
937 if (!strcasecmp(r->method,"GET")) {
938 const char* areq=r->args ? shire.getLazyAuthnRequest(r->args) : NULL;
940 throw ShibTargetException(SHIBRPC_OK, "malformed arguments to request a new session");
941 ap_table_setn(r->headers_out, "Location", ap_pstrdup(r->pool,areq));
944 else if (strcasecmp(r->method,"POST")) {
945 throw ShibTargetException(SHIBRPC_OK, "blocked non-POST to SHIRE POST processor");
948 // Sure sure this POST is an appropriate content type
949 const char *ct = ap_table_get(r->headers_in, "Content-type");
950 if (!ct || strcasecmp(ct, "application/x-www-form-urlencoded"))
951 throw ShibTargetException(SHIBRPC_OK,
952 ap_psprintf(r->pool, "blocked bad content-type to SHIRE POST processor: %s", (ct ? ct : "")));
954 // Read the posted data
955 if (ap_setup_client_block(r, REQUEST_CHUNKED_ERROR))
956 throw ShibTargetException(SHIBRPC_OK, "CGI setup_client_block failed");
957 if (!ap_should_client_block(r))
958 throw ShibTargetException(SHIBRPC_OK, "CGI should_client_block failed");
959 if (r->remaining > 1024*1024)
960 throw ShibTargetException (SHIBRPC_OK, "CGI length too long...");
963 char buff[HUGE_STRING_LEN];
964 ap_hard_timeout("[mod_shib] CGI Parser", r);
965 memset(buff, 0, sizeof(buff));
966 while (ap_get_client_block(r, buff, sizeof(buff)-1) > 0) {
969 memset(buff, 0, sizeof(buff));
973 // Parse the submission.
974 pair<const char*,const char*> elements=shire.getFormSubmission(cgistr.c_str(),cgistr.length());
976 // Make sure the SAML Response parameter exists
977 if (!elements.first || !*elements.first)
978 throw ShibTargetException(SHIBRPC_OK, "SHIRE POST failed to find SAMLResponse form element");
980 // Make sure the target parameter exists
981 if (!elements.second || !*elements.second)
982 throw ShibTargetException(SHIBRPC_OK, "SHIRE POST failed to find TARGET form element");
984 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
985 "shib_handler() Processing POST for target: %s", elements.second);
989 RPCError* status = shire.sessionCreate(elements.first, r->connection->remote_ip, cookie);
991 if (status->isError()) {
992 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
993 "shib_handler() POST process failed (%d): %s", status->getCode(), status->getText());
995 if (status->isRetryable()) {
997 ap_log_rerror(APLOG_MARK,APLOG_INFO|APLOG_NOERRNO,SH_AP_R(r),
998 "shib_handler() retryable error, generating new AuthnRequest");
999 ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(elements.second)));
1003 // return this error to the user.
1004 markupProcessor.insert(*status);
1006 return shib_error_page(r, application, "shire", markupProcessor);
1010 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1011 "shib_handler() POST process succeeded. New session: %s", cookie.c_str());
1013 // We've got a good session, set the cookie...
1014 char* val = ap_psprintf(r->pool,"%s=%s%s",shib_cookie.first,cookie.c_str(),shib_cookie.second);
1015 ap_table_setn(r->err_headers_out, "Set-Cookie", val);
1016 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() setting cookie: %s", val);
1018 // ... and redirect to the target
1019 ap_table_setn(r->headers_out, "Location", ap_pstrdup(r->pool,elements.second));
1022 catch (ShibTargetException &e) {
1023 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() caught exception: %s", e.what());
1024 markupProcessor.insert("errorType", "Session Creation Service Error");
1025 markupProcessor.insert("errorText", e.what());
1026 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
1027 return shib_error_page(r, application, "shire", markupProcessor);
1031 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler(): unexpected exception");
1032 markupProcessor.insert("errorType", "Session Creation Service Error");
1033 markupProcessor.insert("errorText", "Unknown Exception");
1034 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
1035 return shib_error_page(r, application, "shire", markupProcessor);
1039 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_handler() server error");
1040 return SERVER_ERROR;
1043 static int shib_error_page(request_rec* r, const IApplication* app, const char* page, ShibMLP& mlp)
1045 const IPropertySet* props=app->getPropertySet("Errors");
1047 pair<bool,const char*> p=props->getString(page);
1049 ifstream infile(p.second);
1050 if (!infile.fail()) {
1051 const char* res = mlp.run(infile,props);
1053 r->content_type = ap_psprintf(r->pool, "text/html");
1054 ap_send_http_header(r);
1062 ap_log_rerror(APLOG_MARK,APLOG_ERR,SH_AP_R(r),
1063 "shib_error_page() could not process shire error template for application %s",app->getId());
1064 return SERVER_ERROR;
1068 * shib_auth_checker() -- a simple resource manager to
1069 * process the .htaccess settings and copy attributes
1070 * into the HTTP headers.
1072 extern "C" int shib_auth_checker(request_rec* r)
1074 shib_dir_config* dc=
1075 (shib_dir_config*)ap_get_module_config(r->per_dir_config,&mod_shib);
1077 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() executing");
1079 // Regular access to arbitrary resource...check AuthType
1080 const char* auth_type=ap_auth_type(r);
1081 if (!auth_type || strcasecmp(auth_type,"shibboleth"))
1084 ostringstream threadid;
1085 threadid << "[" << getpid() << "] shibrm" << '\0';
1086 saml::NDC ndc(threadid.str().c_str());
1088 // We lock the configuration system for the duration.
1089 IConfig* conf=g_Config->getINI();
1090 Locker locker(conf);
1092 const char* application_id=ap_table_get(r->headers_in,"Shib-Application-ID");
1093 const IApplication* application=NULL;
1095 application = conf->getApplication(application_id);
1099 int m=r->method_number;
1100 bool method_restricted=false;
1103 const array_header* reqs_arr=ap_requires(r);
1107 require_line* reqs=(require_line*)reqs_arr->elts;
1109 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"REQUIRE nelts: %d", reqs_arr->nelts);
1110 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"REQUIRE all: %d", dc->bRequireAll);
1112 vector<bool> auth_OK(reqs_arr->nelts,false);
1114 #define SHIB_AP_CHECK_IS_OK { \
1115 if (dc->bRequireAll < 1) \
1117 auth_OK[x] = true; \
1121 for (int x=0; x<reqs_arr->nelts; x++) {
1123 if (!(reqs[x].method_mask & (1 << m)))
1125 method_restricted=true;
1127 t = reqs[x].requirement;
1128 w = ap_getword_white(r->pool, &t);
1130 if (!strcasecmp(w,"Shibboleth")) {
1131 // This is a dummy rule needed because Apache conflates authn and authz.
1132 // Without some require rule, AuthType is ignored and no check_user hooks run.
1133 SHIB_AP_CHECK_IS_OK;
1135 else if (!strcmp(w,"valid-user") && application_id) {
1136 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting valid-user");
1137 SHIB_AP_CHECK_IS_OK;
1139 else if (!strcmp(w,"user") && SH_AP_USER(r)) {
1142 w=ap_getword_conf(r->pool,&t);
1150 // To do regex matching, we have to convert from UTF-8.
1151 auto_ptr<XMLCh> trans(fromUTF8(w));
1152 RegularExpression re(trans.get());
1153 auto_ptr<XMLCh> trans2(fromUTF8(SH_AP_USER(r)));
1154 if (re.matches(trans2.get())) {
1155 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting user: %s",w);
1156 SHIB_AP_CHECK_IS_OK;
1159 catch (XMLException& ex) {
1160 auto_ptr_char tmp(ex.getMessage());
1161 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
1162 "shib_auth_checker caught exception while parsing regular expression (%s): %s",w,tmp.get());
1165 else if (!strcmp(SH_AP_USER(r),w)) {
1166 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting user: %s",w);
1167 SHIB_AP_CHECK_IS_OK;
1171 else if (!strcmp(w,"group")) {
1172 SH_AP_TABLE* grpstatus=NULL;
1173 if (dc->szAuthGrpFile && SH_AP_USER(r)) {
1174 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() using groups file: %s\n",dc->szAuthGrpFile);
1175 grpstatus=groups_for_user(r,SH_AP_USER(r),dc->szAuthGrpFile);
1181 w=ap_getword_conf(r->pool,&t);
1182 if (ap_table_get(grpstatus,w)) {
1183 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting group: %s",w);
1184 SHIB_AP_CHECK_IS_OK;
1189 Iterator<IAAP*> provs=application ? application->getAAPProviders() : EMPTY(IAAP*);
1190 AAP wrapper(provs,w);
1191 if (wrapper.fail()) {
1192 ap_log_rerror(APLOG_MARK,APLOG_WARNING|APLOG_NOERRNO,SH_AP_R(r),
1193 "shib_auth_checker() didn't recognize require rule: %s\n",w);
1198 const char* vals=ap_table_get(r->headers_in,wrapper->getHeader());
1199 while (*t && vals) {
1200 w=ap_getword_conf(r->pool,&t);
1207 auto_ptr<RegularExpression> re;
1209 delete re.release();
1210 auto_ptr<XMLCh> trans(fromUTF8(w));
1211 auto_ptr<RegularExpression> temp(new RegularExpression(trans.get()));
1215 string vals_str(vals);
1217 for (int i = 0; i < vals_str.length(); i++) {
1218 if (vals_str.at(i) == ';') {
1220 ap_log_rerror(APLOG_MARK,APLOG_WARNING|APLOG_NOERRNO,SH_AP_R(r),
1221 "shib_auth_checker() invalid header encoding %s: starts with semicolon", vals);
1222 return SERVER_ERROR;
1225 if (vals_str.at(i-1) == '\\') {
1226 vals_str.erase(i-1, 1);
1231 string val = vals_str.substr(j, i-j);
1234 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
1235 if (re->matches(trans.get())) {
1236 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1237 "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
1238 SHIB_AP_CHECK_IS_OK;
1241 else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
1242 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1243 "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
1244 SHIB_AP_CHECK_IS_OK;
1247 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1248 "shib_auth_checker() expecting %s, got %s: authorization not granted", w, val.c_str());
1253 string val = vals_str.substr(j, vals_str.length()-j);
1255 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
1256 if (re->matches(trans.get())) {
1257 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1258 "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
1259 SHIB_AP_CHECK_IS_OK;
1262 else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
1263 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1264 "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
1265 SHIB_AP_CHECK_IS_OK;
1268 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1269 "shib_auth_checker() expecting %s, got %s: authorization not granted", w, val.c_str());
1272 catch (XMLException& ex) {
1273 auto_ptr_char tmp(ex.getMessage());
1274 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
1275 "shib_auth_checker caught exception while parsing regular expression (%s): %s",w,tmp.get());
1281 // check if all require directives are true
1282 bool auth_all_OK = true;
1283 for (int i= 0; i<reqs_arr->nelts; i++) {
1284 auth_all_OK &= auth_OK[i];
1289 if (!method_restricted)
1292 if (!application_id) {
1293 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
1294 "shib_auth_checker: Shib-Application-ID header not found in request");
1295 return HTTP_FORBIDDEN;
1297 else if (!application) {
1298 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
1299 "shib_auth_checker: unable to map request to application settings, check configuration");
1300 return HTTP_FORBIDDEN;
1303 ShibMLP markupProcessor;
1304 markupProcessor.insert("requestURL", ap_construct_url(r->pool,r->unparsed_uri,r));
1305 return shib_error_page(r, application, "access", markupProcessor);
1309 #ifndef SHIB_APACHE_13
1312 * Empty cleanup hook, Apache 2.x doesn't check NULL very well...
1314 extern "C" apr_status_t shib_exit(void* data)
1316 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,0,NULL,"shib_exit() done\n");
1324 * Cleanup the (per-process) pool info.
1326 #ifdef SHIB_APACHE_13
1327 extern "C" void shib_child_exit(server_rec* s, SH_AP_POOL* p)
1330 extern "C" apr_status_t shib_child_exit(void* data)
1332 server_rec* s = NULL;
1335 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit(%d) dealing with g_Config..", (int)getpid());
1336 g_Config->shutdown();
1338 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit() done\n");
1340 #ifndef SHIB_APACHE_13
1346 * shire_child_init()
1347 * Things to do when the child process is initialized.
1348 * (or after the configs are read in apache-2)
1350 #ifdef SHIB_APACHE_13
1351 extern "C" void shib_child_init(server_rec* s, SH_AP_POOL* p)
1353 extern "C" void shib_child_init(apr_pool_t* p, server_rec* s)
1356 // Initialize runtime components.
1358 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init(%d) starting", (int)getpid());
1361 ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() already initialized!");
1366 g_Config=&ShibTargetConfig::getConfig();
1367 g_Config->setFeatures(
1368 ShibTargetConfig::Listener |
1369 ShibTargetConfig::Metadata |
1370 ShibTargetConfig::AAP |
1371 ShibTargetConfig::RequestMapper |
1372 ShibTargetConfig::SHIREExtensions |
1373 ShibTargetConfig::Logging
1375 if (!g_Config->init(g_szSchemaDir,g_szSHIBConfig)) {
1376 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize SHIB Target");
1381 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize SHIB Target");
1385 // Set the cleanup handler
1386 apr_pool_cleanup_register(p, NULL, &shib_exit, &shib_child_exit);
1388 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() done");
1391 typedef const char* (*config_fn_t)(void);
1393 #ifdef SHIB_APACHE_13
1395 // SHIB Module commands
1397 static command_rec shire_cmds[] = {
1398 {"SHIREConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1399 RSRC_CONF, TAKE1, "Path to shibboleth.xml config file."},
1400 {"ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1401 RSRC_CONF, TAKE1, "Path to shibboleth.xml config file."},
1402 {"ShibSchemaDir", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1403 RSRC_CONF, TAKE1, "Path to Shibboleth XML schema directory."},
1405 {"ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
1406 (void *) XtOffsetOf (shib_server_config, szScheme),
1407 RSRC_CONF, TAKE1, "URL scheme to force into generated URLs for a vhost."},
1409 {"ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1410 (void *) XtOffsetOf (shib_dir_config, bBasicHijack),
1411 OR_AUTHCFG, FLAG, "Respond to AuthType Basic and convert to shib?"},
1412 {"ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1413 (void *) XtOffsetOf (shib_dir_config, bRequireSession),
1414 OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist."},
1415 {"ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1416 (void *) XtOffsetOf (shib_dir_config, bExportAssertion),
1417 OR_AUTHCFG, FLAG, "Export SAML assertion to Shibboleth-defined header?"},
1418 {"AuthGroupFile", (config_fn_t)ap_set_file_slot,
1419 (void *) XtOffsetOf (shib_dir_config, szAuthGrpFile),
1420 OR_AUTHCFG, TAKE1, "text file containing group names and member user IDs"},
1421 {"ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1422 (void *) XtOffsetOf (shib_dir_config, bRequireAll),
1423 OR_AUTHCFG, FLAG, "All require directives must match!"},
1429 handler_rec shib_handlers[] = {
1430 { "shib-shire-post", shib_post_handler },
1434 module MODULE_VAR_EXPORT mod_shib = {
1435 STANDARD_MODULE_STUFF,
1436 NULL, /* initializer */
1437 create_shib_dir_config, /* dir config creater */
1438 merge_shib_dir_config, /* dir merger --- default is to override */
1439 create_shib_server_config, /* server config */
1440 merge_shib_server_config, /* merge server config */
1441 shire_cmds, /* command table */
1442 shib_handlers, /* handlers */
1443 NULL, /* filename translation */
1444 shib_check_user, /* check_user_id */
1445 shib_auth_checker, /* check auth */
1446 NULL, /* check access */
1447 NULL, /* type_checker */
1450 NULL, /* header parser */
1451 shib_child_init, /* child_init */
1452 shib_child_exit, /* child_exit */
1453 NULL /* post read-request */
1456 #elif defined(SHIB_APACHE_20)
1458 extern "C" void shib_register_hooks (apr_pool_t *p)
1460 ap_hook_child_init(shib_child_init, NULL, NULL, APR_HOOK_MIDDLE);
1461 ap_hook_check_user_id(shib_check_user, NULL, NULL, APR_HOOK_MIDDLE);
1462 ap_hook_auth_checker(shib_auth_checker, NULL, NULL, APR_HOOK_FIRST);
1463 ap_hook_handler(shib_post_handler, NULL, NULL, APR_HOOK_LAST);
1466 // SHIB Module commands
1469 static command_rec shib_cmds[] = {
1470 AP_INIT_TAKE1("ShibConfig",
1471 (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1472 RSRC_CONF, "Path to shibboleth.xml config file."),
1473 AP_INIT_TAKE1("ShibSchemaDir",
1474 (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1475 RSRC_CONF, "Path to Shibboleth XML schema directory."),
1477 AP_INIT_TAKE1("ShibURLScheme",
1478 (config_fn_t)shib_set_server_string_slot,
1479 (void *) offsetof (shib_server_config, szScheme),
1480 RSRC_CONF, "URL scheme to force into generated URLs for a vhost."),
1482 AP_INIT_FLAG("ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1483 (void *) offsetof (shib_dir_config, bBasicHijack),
1484 OR_AUTHCFG, "Respond to AuthType Basic and convert to shib?"),
1485 AP_INIT_FLAG("ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1486 (void *) offsetof (shib_dir_config, bRequireSession),
1487 OR_AUTHCFG, "Initiates a new session if one does not exist."),
1488 AP_INIT_FLAG("ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1489 (void *) offsetof (shib_dir_config, bExportAssertion),
1490 OR_AUTHCFG, "Export SAML assertion to Shibboleth-defined header?"),
1491 AP_INIT_TAKE1("AuthGroupFile", (config_fn_t)ap_set_file_slot,
1492 (void *) offsetof (shib_dir_config, szAuthGrpFile),
1493 OR_AUTHCFG, "text file containing group names and member user IDs"),
1494 AP_INIT_FLAG("ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1495 (void *) offsetof (shib_dir_config, bRequireAll),
1496 OR_AUTHCFG, "All require directives must match!"),
1501 module AP_MODULE_DECLARE_DATA mod_shib = {
1502 STANDARD20_MODULE_STUFF,
1503 create_shib_dir_config, /* create dir config */
1504 merge_shib_dir_config, /* merge dir config --- default is to override */
1505 create_shib_server_config, /* create server config */
1506 merge_shib_server_config, /* merge server config */
1507 shib_cmds, /* command table */
1508 shib_register_hooks /* register hooks */
1512 #error "undefined APACHE version"