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;
50 int shib_handler(request_rec* r, const IApplication* application, SHIRE& shire);
53 char* g_szSHIBConfig = NULL;
54 char* g_szSchemaDir = NULL;
55 ShibTargetConfig* g_Config = NULL;
56 static const char* g_UserDataKey = "_shib_check_user_";
59 /********************************************************************************/
60 // Basic Apache Configuration code.
63 // per-server module configuration structure
64 struct shib_server_config
69 // creates the per-server configuration
70 extern "C" void* create_shib_server_config(SH_AP_POOL* p, server_rec* s)
72 shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
77 // overrides server configuration in virtual servers
78 extern "C" void* merge_shib_server_config (SH_AP_POOL* p, void* base, void* sub)
80 shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
81 shib_server_config* parent=(shib_server_config*)base;
82 shib_server_config* child=(shib_server_config*)sub;
85 sc->szScheme=ap_pstrdup(p,child->szScheme);
86 else if (parent->szScheme)
87 sc->szScheme=ap_pstrdup(p,parent->szScheme);
94 // per-dir module configuration structure
95 struct shib_dir_config
98 char* szAuthGrpFile; // Auth GroupFile name
99 int bRequireAll; // all require directives must match, otherwise OR logic
101 // SHIRE Configuration
102 int bBasicHijack; // activate for AuthType Basic?
103 int bRequireSession; // require a session?
104 int bExportAssertion; // export SAML assertion to the environment?
107 // creates per-directory config structure
108 extern "C" void* create_shib_dir_config (SH_AP_POOL* p, char* d)
110 shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
111 dc->bBasicHijack = -1;
112 dc->bRequireSession = -1;
113 dc->bExportAssertion = -1;
114 dc->bRequireAll = -1;
115 dc->szAuthGrpFile = NULL;
119 // overrides server configuration in directories
120 extern "C" void* merge_shib_dir_config (SH_AP_POOL* p, void* base, void* sub)
122 shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
123 shib_dir_config* parent=(shib_dir_config*)base;
124 shib_dir_config* child=(shib_dir_config*)sub;
126 if (child->szAuthGrpFile)
127 dc->szAuthGrpFile=ap_pstrdup(p,child->szAuthGrpFile);
128 else if (parent->szAuthGrpFile)
129 dc->szAuthGrpFile=ap_pstrdup(p,parent->szAuthGrpFile);
131 dc->szAuthGrpFile=NULL;
133 dc->bBasicHijack=((child->bBasicHijack==-1) ? parent->bBasicHijack : child->bBasicHijack);
134 dc->bRequireSession=((child->bRequireSession==-1) ? parent->bRequireSession : child->bRequireSession);
135 dc->bExportAssertion=((child->bExportAssertion==-1) ? parent->bExportAssertion : child->bExportAssertion);
136 dc->bRequireAll=((child->bRequireAll==-1) ? parent->bRequireAll : child->bRequireAll);
140 // generic global slot handlers
141 extern "C" const char* ap_set_global_string_slot(cmd_parms* parms, void*, const char* arg)
143 *((char**)(parms->info))=ap_pstrdup(parms->pool,arg);
147 extern "C" const char* shib_set_server_string_slot(cmd_parms* parms, void*, const char* arg)
149 char* base=(char*)ap_get_module_config(parms->server->module_config,&mod_shib);
150 int offset=(int)parms->info;
151 *((char**)(base + offset))=ap_pstrdup(parms->pool,arg);
155 /********************************************************************************/
156 // Some other useful helper function(s)
158 static SH_AP_TABLE* groups_for_user(request_rec* r, const char* user, char* grpfile)
161 SH_AP_TABLE* grps=ap_make_table(r->pool,15);
162 char l[MAX_STRING_LEN];
163 const char *group_name, *ll, *w;
165 #ifdef SHIB_APACHE_13
166 if (!(f=ap_pcfg_openfile(r->pool,grpfile))) {
168 if (ap_pcfg_openfile(&f,r->pool,grpfile) != APR_SUCCESS) {
170 ap_log_rerror(APLOG_MARK,APLOG_DEBUG,SH_AP_R(r),"groups_for_user() could not open group file: %s\n",grpfile);
175 #ifdef SHIB_APACHE_13
176 sp=ap_make_sub_pool(r->pool);
178 if (apr_pool_create(&sp,r->pool) != APR_SUCCESS) {
179 ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,
180 "groups_for_user() could not create a subpool");
185 while (!(ap_cfg_getline(l,MAX_STRING_LEN,f))) {
186 if ((*l=='#') || (!*l))
191 group_name=ap_getword(sp,&ll,':');
194 w=ap_getword_conf(sp,&ll);
195 if (!strcmp(w,user)) {
196 ap_table_setn(grps,ap_pstrdup(r->pool,group_name),"in");
206 /********************************************************************************/
207 // Apache ShibTarget subclass(es) here.
209 class HTGroupTableApache : public HTGroupTable
212 HTGroupTableApache(request_rec* r, const char *user, char *grpfile) {
213 groups = groups_for_user(r, user, grpfile);
215 throw ShibTargetException(SHIBRPC_OK, "EEP");
217 ~HTGroupTableApache() {}
218 bool lookup(const char *entry) { return (ap_table_get(groups, entry)!=NULL); }
222 class ShibTargetApache : public ShibTarget
225 ShibTargetApache(request_rec* req) {
226 m_sc = (shib_server_config*)
227 ap_get_module_config(req->server->module_config, &mod_shib);
229 m_dc = (shib_dir_config*)ap_get_module_config(req->per_dir_config, &mod_shib);
231 const char* ct = ap_table_get(req->headers_in, "Content-type");
233 init(g_Config, string(m_sc->szScheme ? m_sc->szScheme : ap_http_method(req)),
234 string(ap_get_server_name(req)), (int)ap_get_server_port(req),
235 string(req->unparsed_uri), string(ct ? ct : ""),
236 string(req->connection->remote_ip), string(req->method));
240 ~ShibTargetApache() { }
242 virtual void log(ShibLogLevel level, const string &msg) {
243 ap_log_rerror(APLOG_MARK,
244 (level == LogLevelDebug ? APLOG_DEBUG :
245 (level == LogLevelInfo ? APLOG_INFO :
246 (level == LogLevelWarn ? APLOG_WARNING :
247 APLOG_ERR)))|APLOG_NOERRNO, SH_AP_R(m_req),
250 virtual string getCookies(void) {
251 const char *c = ap_table_get(m_req->headers_in, "Cookie");
252 return string(c ? c : "");
254 virtual void setCookie(const string &name, const string &value) {
255 char* val = ap_psprintf(m_req->pool, "%s=%s", name.c_str(), value.c_str());
256 ap_table_setn(m_req->err_headers_out, "Set-Cookie", val);
258 virtual string getArgs(void) { return string(m_req->args ? m_req->args : ""); }
259 virtual string getPostData(void) {
260 // Read the posted data
261 if (ap_setup_client_block(m_req, REQUEST_CHUNKED_ERROR))
262 throw ShibTargetException(SHIBRPC_OK, "CGI setup_client_block failed");
263 if (!ap_should_client_block(m_req))
264 throw ShibTargetException(SHIBRPC_OK, "CGI should_client_block failed");
265 if (m_req->remaining > 1024*1024)
266 throw ShibTargetException (SHIBRPC_OK, "CGI length too long...");
269 char buff[HUGE_STRING_LEN];
270 ap_hard_timeout("[mod_shib] getPostData", m_req);
271 memset(buff, 0, sizeof(buff));
272 while (ap_get_client_block(m_req, buff, sizeof(buff)-1) > 0) {
273 ap_reset_timeout(m_req);
275 memset(buff, 0, sizeof(buff));
277 ap_kill_timeout(m_req);
281 virtual void clearHeader(const string &name) {
282 ap_table_unset(m_req->headers_in, name.c_str());
284 virtual void setHeader(const string &name, const string &value) {
285 ap_table_set(m_req->headers_in, name.c_str(), value.c_str());
287 virtual string getHeader(const string &name) {
288 const char *hdr = ap_table_get(m_req->headers_in, name.c_str());
289 return string(hdr ? hdr : "");
291 virtual void setRemoteUser(const string &user) {
292 SH_AP_USER(m_req) = ap_pstrdup(m_req->pool, user.c_str());
294 virtual string getRemoteUser(void) {
295 return string(SH_AP_USER(m_req) ? SH_AP_USER(m_req) : "");
297 // override so we can look at the actual auth type and maybe override it.
298 virtual string getAuthType(void) {
299 const char *auth_type=ap_auth_type(m_req);
302 if (strcasecmp(auth_type, "shibboleth")) {
303 if (!strcasecmp(auth_type, "basic") && m_dc->bBasicHijack == 1) {
304 core_dir_config* conf= (core_dir_config*)
305 ap_get_module_config(m_req->per_dir_config,
306 ap_find_linked_module("http_core.c"));
307 auth_type = conf->ap_auth_type = "shibboleth";
310 return string(auth_type);
312 // Override this function because we want to add the Apache Directory override
313 virtual pair<bool,bool> getRequireSession(IRequestMapper::Settings &settings) {
314 pair<bool,bool> requireSession = settings.first->getBool("requireSession");
315 if (!requireSession.first || !requireSession.second)
316 if (m_dc->bRequireSession == 1)
317 requireSession.second=true;
319 return requireSession;
322 virtual HTAccessInfo* getAccessInfo(void) {
323 int m = m_req->method_number;
324 const array_header* reqs_arr = ap_requires(m_req);
328 require_line* reqs = (require_line*) reqs_arr->elts;
330 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req),
331 "REQUIRE nelts: %d", reqs_arr->nelts);
332 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req),
333 "REQUIRE all: %d", m_dc->bRequireAll);
335 HTAccessInfo* ht = new HTAccessInfo();
336 ht->requireAll = (m_dc->bRequireAll >= 0);
337 ht->elements.reserve(reqs_arr->nelts);
338 for (int x = 0; x < reqs_arr->nelts; x++) {
339 HTAccessInfo::RequireLine* rline = new HTAccessInfo::RequireLine();
340 rline->use_line = (reqs[x].method_mask & (1 << m));
341 rline->tokens.reserve(6); // No reason to reserve specifically 6 tokens
342 const char* t = reqs[x].requirement;
343 const char* w = ap_getword_white(m_req->pool, &t);
344 rline->tokens.push_back(w);
346 w = ap_getword_conf(m_req->pool, &t);
347 rline->tokens.push_back(w);
349 ht->elements.push_back(rline);
353 virtual HTGroupTable* getGroupTable(string &user) {
354 if (m_dc->szAuthGrpFile && !user.empty()) {
355 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req),
356 "getGroupTable() using groups file: %s\n",
357 m_dc->szAuthGrpFile);
359 HTGroupTableApache *gt = new HTGroupTableApache(m_req, user.c_str(),
360 m_dc->szAuthGrpFile);
367 virtual void* sendPage(const string &msg, const string content_type,
368 const pair<string, string> headers[], int code) {
369 m_req->content_type = ap_psprintf(m_req->pool, content_type.c_str());
370 // XXX: push headers and code into the response
371 ap_send_http_header(m_req);
372 ap_rprintf(m_req, msg.c_str());
375 virtual void* sendRedirect(const string url) {
376 ap_table_set(m_req->headers_out, "Location", url.c_str());
377 return (void*)REDIRECT;
379 virtual void* returnDecline(void) { return (void*)DECLINED; }
380 virtual void* returnOK(void) { return (void*)OK; }
383 shib_dir_config* m_dc;
384 shib_server_config* m_sc;
387 /********************************************************************************/
390 extern "C" int shib_check_user(request_rec* r)
392 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
393 "shib_check_user(%d): ENTER\n", (int)getpid());
395 ostringstream threadid;
396 threadid << "[" << getpid() << "] shib_check_user" << '\0';
397 saml::NDC ndc(threadid.str().c_str());
402 ShibTargetApache sta(r);
404 // Check user authentication, the set the post handler bypass
405 pair<bool,void*> res = sta.doCheckAuthN((sta.m_dc->bRequireSession == 1), true);
406 apr_pool_userdata_setn((const void*)42,g_UserDataKey,NULL,r->pool);
407 if (res.first) return (int)res.second;
409 // user auth was okay -- export the assertions now
410 res = sta.doExportAssertions((sta.m_dc->bExportAssertion == 1));
411 if (res.first) return (int)res.second;
413 // export happened successfully.. this user is ok.
418 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r),
419 "shib_check_user threw an uncaught exception!");
425 extern "C" int shib_post_handler(request_rec* r)
427 ostringstream threadid;
428 threadid << "[" << getpid() << "] shib_post_handler" << '\0';
429 saml::NDC ndc(threadid.str().c_str());
431 #ifndef SHIB_APACHE_13
432 // With 2.x, this handler always runs, though last.
433 // We check if shib_check_user ran, because it will detect a SHIRE request
434 // and dispatch it directly.
436 apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
437 if (data==(const void*)42) {
438 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_post_handler skipped since check_user ran");
443 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
444 "shib_post_handler(%d): ENTER", (int)getpid());
449 ShibTargetApache sta(r);
451 pair<bool,void*> res = sta.doHandlePOST();
452 if (res.first) return (int)res.second;
454 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r),
455 "doHandlePOST() did not do anything.");
460 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r),
461 "shib_post_handler threw an uncaught exception!");
468 * shib_auth_checker() -- a simple resource manager to
469 * process the .htaccess settings and copy attributes
470 * into the HTTP headers.
472 extern "C" int shib_auth_checker(request_rec* r)
474 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
475 "shib_check_user(%d): ENTER", (int)getpid());
477 ostringstream threadid;
478 threadid << "[" << getpid() << "] shib_auth_checker" << '\0';
479 saml::NDC ndc(threadid.str().c_str());
484 ShibTargetApache sta(r);
486 pair<bool,void*> res = sta.doCheckAuthZ();
487 if (res.first) return (int)res.second;
494 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r),
495 "shib_auth_checker threw an uncaught exception!");
502 static char* shib_get_targeturl(request_rec* r, const char* scheme=NULL)
504 // On 1.3, this is always canonical, but on 2.0, UseCanonicalName comes into play.
505 // However, we also have a setting to forcibly replace the scheme for esoteric cases.
507 unsigned port = ap_get_server_port(r);
508 if ((!strcmp(scheme,"http") && port==80) || (!strcmp(scheme,"https") && port==443)) {
509 return ap_pstrcat(r->pool, scheme, "://", ap_get_server_name(r), r->unparsed_uri, NULL);
511 return ap_psprintf(r->pool, "%s://%s:%u%s", scheme, ap_get_server_name(r), port, r->unparsed_uri);
513 return ap_construct_url(r->pool,r->unparsed_uri,r);
516 extern "C" int shib_check_user(request_rec* r)
518 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: ENTER");
519 shib_dir_config* dc=(shib_dir_config*)ap_get_module_config(r->per_dir_config,&mod_shib);
520 shib_server_config* sc=(shib_server_config*)ap_get_module_config(r->server->module_config,&mod_shib);
522 ostringstream threadid;
523 threadid << "[" << getpid() << "] shib_check_user" << '\0';
524 saml::NDC ndc(threadid.str().c_str());
526 const char* targeturl=shib_get_targeturl(r,sc->szScheme);
528 // We lock the configuration system for the duration.
529 IConfig* conf=g_Config->getINI();
532 // Map request to application and content settings.
533 IRequestMapper* mapper=conf->getRequestMapper();
534 Locker locker2(mapper);
535 IRequestMapper::Settings settings=mapper->getSettingsFromParsedURL(
536 (sc-> szScheme ? sc-> szScheme : ap_http_method(r)), ap_get_server_name(r), ap_get_server_port(r), r->unparsed_uri
538 pair<bool,const char*> application_id=settings.first->getString("applicationId");
539 const IApplication* application=conf->getApplication(application_id.second);
541 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
542 "shib_check_user: unable to map request to application settings, check configuration");
546 // Declare SHIRE object for this request.
547 SHIRE shire(application);
549 const char* shireURL=shire.getShireURL(targeturl);
551 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
552 "shib_check_user: unable to map request to proper shireURL setting, check configuration");
556 // Get location of this application's assertion consumer service and see if this is it.
557 if (strstr(targeturl,shireURL)) {
558 return shib_handler(r,application,shire);
561 // We can short circuit the handler if we run this...
562 apr_pool_userdata_setn((const void*)42,g_UserDataKey,NULL,r->pool);
564 // Regular access to arbitrary resource...check AuthType
565 const char *auth_type=ap_auth_type(r);
569 if (strcasecmp(auth_type,"shibboleth")) {
570 if (!strcasecmp(auth_type,"basic") && dc->bBasicHijack==1) {
571 core_dir_config* conf=
572 (core_dir_config*)ap_get_module_config(r->per_dir_config,
573 ap_find_linked_module("http_core.c"));
574 conf->ap_auth_type="shibboleth";
580 pair<bool,bool> requireSession = settings.first->getBool("requireSession");
581 if (!requireSession.first || !requireSession.second)
582 if (dc->bRequireSession==1)
583 requireSession.second=true;
585 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: session check for %s",targeturl);
587 pair<const char*,const char*> shib_cookie=shire.getCookieNameProps(); // always returns *something*
589 // We're in charge, so check for cookie.
590 const char* session_id=NULL;
591 const char* cookies=ap_table_get(r->headers_in,"Cookie");
594 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: cookies found: %s",cookies);
595 if (session_id=strstr(cookies,shib_cookie.first)) {
596 // Yep, we found a cookie -- pull it out (our session_id)
597 session_id+=strlen(shib_cookie.first) + 1; /* Skip over the '=' */
598 char* cookiebuf = ap_pstrdup(r->pool,session_id);
599 char* cookieend = strchr(cookiebuf,';');
601 *cookieend = '\0'; /* Ignore anyting after a ; */
602 session_id=cookiebuf;
606 if (!session_id || !*session_id) {
607 // If no session required, bail now.
608 if (!requireSession.second)
611 // No acceptable cookie, and we require a session. Generate an AuthnRequest.
612 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: no cookie found -- redirecting to WAYF");
613 ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(targeturl)));
617 // Make sure this session is still valid.
618 RPCError* status = NULL;
619 ShibMLP markupProcessor;
620 markupProcessor.insert("requestURL", targeturl);
623 status = shire.sessionIsValid(session_id, r->connection->remote_ip);
625 catch (ShibTargetException &e) {
626 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): %s", e.what());
627 markupProcessor.insert("errorType", "Session Processing Error");
628 markupProcessor.insert("errorText", e.what());
629 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
630 return shib_error_page(r, application, "shire", markupProcessor);
634 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): caught unexpected error");
635 markupProcessor.insert("errorType", "Session Processing Error");
636 markupProcessor.insert("errorText", "Unexpected Exception");
637 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
638 return shib_error_page(r, application, "shire", markupProcessor);
643 if (status->isError()) {
644 ap_log_rerror(APLOG_MARK,APLOG_INFO|APLOG_NOERRNO,SH_AP_R(r),
645 "shib_check_user() session invalid: %s", status->getText());
647 // If no session required, bail now.
648 if (!requireSession.second)
649 return OK; // XXX: Or should this be DECLINED?
650 // Has to be OK because DECLINED will just cause Apache to fail when it can't locate
651 // anything to process the AuthType. No session plus requireSession false means
652 // do not authenticate the user.
653 else if (status->isRetryable()) {
654 // Oops, session is invalid. Generate AuthnRequest.
655 ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(targeturl)));
660 // return the error page to the user
661 markupProcessor.insert(*status);
663 return shib_error_page(r, application, "shire", markupProcessor);
669 #ifdef SHIB_APACHE_13
671 r->connection->ap_auth_type = "shibboleth";
673 r->ap_auth_type = "shibboleth";
675 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: session successfully verified");
677 // This is code transferred in from the auth check to export the attributes.
678 // We could even combine the isSessionValid/getAssertions API...?
681 vector<SAMLAssertion*> assertions;
682 SAMLAuthenticationStatement* sso_statement=NULL;
685 status = rm.getAssertions(session_id, r->connection->remote_ip, assertions, &sso_statement);
687 catch (ShibTargetException &e) {
688 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): %s", e.what());
689 markupProcessor.insert("errorType", "Attribute Processing Error");
690 markupProcessor.insert("errorText", e.what());
691 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
692 return shib_error_page(r, application, "rm", markupProcessor);
696 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): caught unexpected error");
697 markupProcessor.insert("errorType", "Attribute Processing Error");
698 markupProcessor.insert("errorText", "Unexpected Exception");
699 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
700 return shib_error_page(r, application, "rm", markupProcessor);
704 if (status->isError()) {
705 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
706 "shib_check_user() getAssertions failed: %s", status->getText());
708 markupProcessor.insert(*status);
710 return shib_error_page(r, application, "rm", markupProcessor);
714 // Do we have an access control plugin?
715 if (settings.second) {
716 Locker acllock(settings.second);
717 if (!settings.second->authorized(*sso_statement,assertions)) {
718 for (int k = 0; k < assertions.size(); k++)
719 delete assertions[k];
720 delete sso_statement;
721 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): access control provider denied access");
722 return shib_error_page(r, application, "access", markupProcessor);
726 // Get the AAP providers, which contain the attribute policy info.
727 Iterator<IAAP*> provs=application->getAAPProviders();
729 // Clear out the list of mapped attributes
730 while (provs.hasNext()) {
731 IAAP* aap=provs.next();
734 Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
735 while (rules.hasNext()) {
736 const char* header=rules.next()->getHeader();
738 ap_table_unset(r->headers_in,header);
743 for (int k = 0; k < assertions.size(); k++)
744 delete assertions[k];
745 delete sso_statement;
746 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
747 "shib_check_user(): caught unexpected error while clearing headers");
748 markupProcessor.insert("errorType", "Attribute Processing Error");
749 markupProcessor.insert("errorText", "Unexpected Exception");
750 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
751 return shib_error_page(r, application, "rm", markupProcessor);
757 // Maybe export the first assertion.
758 ap_table_unset(r->headers_in,"Shib-Attributes");
759 pair<bool,bool> exp=settings.first->getBool("exportAssertion");
760 if (!exp.first || !exp.second)
761 if (dc->bExportAssertion==1)
763 if (exp.second && assertions.size()) {
765 RM::serialize(*(assertions[0]), assertion);
766 ap_table_set(r->headers_in,"Shib-Attributes", assertion.c_str());
769 // Export the SAML AuthnMethod and the origin site name, and possibly the NameIdentifier.
770 ap_table_unset(r->headers_in,"Shib-Origin-Site");
771 ap_table_unset(r->headers_in,"Shib-Authentication-Method");
772 ap_table_unset(r->headers_in,"Shib-NameIdentifier-Format");
773 auto_ptr_char os(sso_statement->getSubject()->getNameIdentifier()->getNameQualifier());
774 auto_ptr_char am(sso_statement->getAuthMethod());
775 ap_table_set(r->headers_in,"Shib-Origin-Site", os.get());
776 ap_table_set(r->headers_in,"Shib-Authentication-Method", am.get());
779 AAP wrapper(provs,sso_statement->getSubject()->getNameIdentifier()->getFormat(),Constants::SHIB_ATTRIBUTE_NAMESPACE_URI);
780 if (!wrapper.fail() && wrapper->getHeader()) {
781 auto_ptr_char form(sso_statement->getSubject()->getNameIdentifier()->getFormat());
782 auto_ptr_char nameid(sso_statement->getSubject()->getNameIdentifier()->getName());
783 ap_table_set(r->headers_in,"Shib-NameIdentifier-Format",form.get());
784 if (!strcmp(wrapper->getHeader(),"REMOTE_USER"))
785 SH_AP_USER(r)=ap_pstrdup(r->pool,nameid.get());
787 ap_table_set(r->headers_in,wrapper->getHeader(),nameid.get());
790 ap_table_unset(r->headers_in,"Shib-Application-ID");
791 ap_table_set(r->headers_in,"Shib-Application-ID",application_id.second);
793 // Export the attributes.
794 Iterator<SAMLAssertion*> a_iter(assertions);
795 while (a_iter.hasNext()) {
796 SAMLAssertion* assert=a_iter.next();
797 Iterator<SAMLStatement*> statements=assert->getStatements();
798 while (statements.hasNext()) {
799 SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());
802 Iterator<SAMLAttribute*> attrs=astate->getAttributes();
803 while (attrs.hasNext()) {
804 SAMLAttribute* attr=attrs.next();
806 // Are we supposed to export it?
807 AAP wrapper(provs,attr->getName(),attr->getNamespace());
808 if (wrapper.fail() || !wrapper->getHeader())
811 Iterator<string> vals=attr->getSingleByteValues();
812 if (!strcmp(wrapper->getHeader(),"REMOTE_USER") && vals.hasNext())
813 SH_AP_USER(r)=ap_pstrdup(r->pool,vals.next().c_str());
816 char* header = (char*)ap_table_get(r->headers_in, wrapper->getHeader());
818 header=ap_pstrdup(r->pool, header);
822 header = ap_pstrdup(r->pool, "");
823 for (; vals.hasNext(); it++) {
824 string value = vals.next();
825 for (string::size_type pos = value.find_first_of(";", string::size_type(0));
827 pos = value.find_first_of(";", pos)) {
828 value.insert(pos, "\\");
831 header=ap_pstrcat(r->pool, header, (it ? ";" : ""), value.c_str(), NULL);
833 ap_table_setn(r->headers_in, wrapper->getHeader(), header);
840 for (int k = 0; k < assertions.size(); k++)
841 delete assertions[k];
842 delete sso_statement;
847 extern "C" int shib_post_handler(request_rec* r)
849 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
850 "shib_post_handler(%d): ENTER", (int)getpid());
851 shib_server_config* sc=(shib_server_config*)ap_get_module_config(r->server->module_config,&mod_shib);
853 #ifndef SHIB_APACHE_13
854 // With 2.x, this handler always runs, though last.
855 // We check if shib_check_user ran, because it will detect a SHIRE request
856 // and dispatch it directly.
858 apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
859 if (data==(const void*)42) {
860 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_post_handler skipped since check_user ran");
865 ostringstream threadid;
866 threadid << "[" << getpid() << "] shib_post_handler" << '\0';
867 saml::NDC ndc(threadid.str().c_str());
869 // We lock the configuration system for the duration.
870 IConfig* conf=g_Config->getINI();
873 // Map request to application and content settings.
874 IRequestMapper* mapper=conf->getRequestMapper();
875 Locker locker2(mapper);
876 IRequestMapper::Settings settings=mapper->getSettingsFromParsedURL(
877 (sc->szScheme ? sc->szScheme : ap_http_method(r)), ap_get_server_name(r), ap_get_server_port(r), r->unparsed_uri
879 pair<bool,const char*> application_id=settings.first->getString("applicationId");
880 const IApplication* application=conf->getApplication(application_id.second);
882 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
883 "shib_post_handler: unable to map request to application settings, check configuration");
887 // Declare SHIRE object for this request.
888 SHIRE shire(application);
890 return shib_handler(r, application, shire);
893 int shib_handler(request_rec* r, const IApplication* application, SHIRE& shire)
895 shib_server_config* sc=(shib_server_config*)ap_get_module_config(r->server->module_config,&mod_shib);
897 const char* targeturl=shib_get_targeturl(r,sc->szScheme);
899 const char* shireURL=shire.getShireURL(targeturl);
901 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
902 "shib_post_handler: unable to map request to proper shireURL setting, check configuration");
906 // Make sure we only process the SHIRE requests.
907 if (!strstr(targeturl,shireURL))
910 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler() running");
912 const IPropertySet* sessionProps=application->getPropertySet("Sessions");
914 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
915 "shib_post_handler: unable to map request to application session settings, check configuration");
919 pair<const char*,const char*> shib_cookie=shire.getCookieNameProps(); // always returns something
921 ShibMLP markupProcessor;
922 markupProcessor.insert("requestURL", targeturl);
924 // Process SHIRE request
925 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() Beginning SHIRE processing");
928 pair<bool,bool> shireSSL=sessionProps->getBool("shireSSL");
930 // Make sure this is SSL, if it should be
931 if ((!shireSSL.first || shireSSL.second) && strcmp(ap_http_method(r),"https"))
932 throw ShibTargetException(SHIBRPC_OK, "blocked non-SSL access to session creation service");
934 // If this is a GET, we manufacture an AuthnRequest.
935 if (!strcasecmp(r->method,"GET")) {
936 const char* areq=r->args ? shire.getLazyAuthnRequest(r->args) : NULL;
938 throw ShibTargetException(SHIBRPC_OK, "malformed arguments to request a new session");
939 ap_table_setn(r->headers_out, "Location", ap_pstrdup(r->pool,areq));
942 else if (strcasecmp(r->method,"POST")) {
943 throw ShibTargetException(SHIBRPC_OK, "blocked non-POST to SHIRE POST processor");
946 // Sure sure this POST is an appropriate content type
947 const char *ct = ap_table_get(r->headers_in, "Content-type");
948 if (!ct || strcasecmp(ct, "application/x-www-form-urlencoded"))
949 throw ShibTargetException(SHIBRPC_OK,
950 ap_psprintf(r->pool, "blocked bad content-type to SHIRE POST processor: %s", (ct ? ct : "")));
952 // Read the posted data
953 if (ap_setup_client_block(r, REQUEST_CHUNKED_ERROR))
954 throw ShibTargetException(SHIBRPC_OK, "CGI setup_client_block failed");
955 if (!ap_should_client_block(r))
956 throw ShibTargetException(SHIBRPC_OK, "CGI should_client_block failed");
957 if (r->remaining > 1024*1024)
958 throw ShibTargetException (SHIBRPC_OK, "CGI length too long...");
961 char buff[HUGE_STRING_LEN];
962 ap_hard_timeout("[mod_shib] CGI Parser", r);
963 memset(buff, 0, sizeof(buff));
964 while (ap_get_client_block(r, buff, sizeof(buff)-1) > 0) {
967 memset(buff, 0, sizeof(buff));
971 // Parse the submission.
972 pair<const char*,const char*> elements=shire.getFormSubmission(cgistr.c_str(),cgistr.length());
974 // Make sure the SAML Response parameter exists
975 if (!elements.first || !*elements.first)
976 throw ShibTargetException(SHIBRPC_OK, "SHIRE POST failed to find SAMLResponse form element");
978 // Make sure the target parameter exists
979 if (!elements.second || !*elements.second)
980 throw ShibTargetException(SHIBRPC_OK, "SHIRE POST failed to find TARGET form element");
982 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
983 "shib_handler() Processing POST for target: %s", elements.second);
987 RPCError* status = shire.sessionCreate(elements.first, r->connection->remote_ip, cookie);
989 if (status->isError()) {
990 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
991 "shib_handler() POST process failed (%d): %s", status->getCode(), status->getText());
993 if (status->isRetryable()) {
995 ap_log_rerror(APLOG_MARK,APLOG_INFO|APLOG_NOERRNO,SH_AP_R(r),
996 "shib_handler() retryable error, generating new AuthnRequest");
997 ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(elements.second)));
1001 // return this error to the user.
1002 markupProcessor.insert(*status);
1004 return shib_error_page(r, application, "shire", markupProcessor);
1008 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1009 "shib_handler() POST process succeeded. New session: %s", cookie.c_str());
1011 // We've got a good session, set the cookie...
1012 char* val = ap_psprintf(r->pool,"%s=%s%s",shib_cookie.first,cookie.c_str(),shib_cookie.second);
1013 ap_table_setn(r->err_headers_out, "Set-Cookie", val);
1014 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() setting cookie: %s", val);
1016 // ... and redirect to the target
1017 ap_table_setn(r->headers_out, "Location", ap_pstrdup(r->pool,elements.second));
1020 catch (ShibTargetException &e) {
1021 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() caught exception: %s", e.what());
1022 markupProcessor.insert("errorType", "Session Creation Service Error");
1023 markupProcessor.insert("errorText", e.what());
1024 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
1025 return shib_error_page(r, application, "shire", markupProcessor);
1029 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler(): unexpected exception");
1030 markupProcessor.insert("errorType", "Session Creation Service Error");
1031 markupProcessor.insert("errorText", "Unknown Exception");
1032 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
1033 return shib_error_page(r, application, "shire", markupProcessor);
1037 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_handler() server error");
1038 return SERVER_ERROR;
1041 static int shib_error_page(request_rec* r, const IApplication* app, const char* page, ShibMLP& mlp)
1043 const IPropertySet* props=app->getPropertySet("Errors");
1045 pair<bool,const char*> p=props->getString(page);
1047 ifstream infile(p.second);
1048 if (!infile.fail()) {
1049 const char* res = mlp.run(infile,props);
1051 r->content_type = ap_psprintf(r->pool, "text/html");
1052 ap_send_http_header(r);
1060 ap_log_rerror(APLOG_MARK,APLOG_ERR,SH_AP_R(r),
1061 "shib_error_page() could not process shire error template for application %s",app->getId());
1062 return SERVER_ERROR;
1066 * shib_auth_checker() -- a simple resource manager to
1067 * process the .htaccess settings and copy attributes
1068 * into the HTTP headers.
1070 extern "C" int shib_auth_checker(request_rec* r)
1072 shib_dir_config* dc=
1073 (shib_dir_config*)ap_get_module_config(r->per_dir_config,&mod_shib);
1075 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() executing");
1077 // Regular access to arbitrary resource...check AuthType
1078 const char* auth_type=ap_auth_type(r);
1079 if (!auth_type || strcasecmp(auth_type,"shibboleth"))
1082 ostringstream threadid;
1083 threadid << "[" << getpid() << "] shibrm" << '\0';
1084 saml::NDC ndc(threadid.str().c_str());
1086 // We lock the configuration system for the duration.
1087 IConfig* conf=g_Config->getINI();
1088 Locker locker(conf);
1090 const char* application_id=ap_table_get(r->headers_in,"Shib-Application-ID");
1091 const IApplication* application=NULL;
1093 application = conf->getApplication(application_id);
1097 int m=r->method_number;
1098 bool method_restricted=false;
1101 const array_header* reqs_arr=ap_requires(r);
1105 require_line* reqs=(require_line*)reqs_arr->elts;
1107 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"REQUIRE nelts: %d", reqs_arr->nelts);
1108 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"REQUIRE all: %d", dc->bRequireAll);
1110 vector<bool> auth_OK(reqs_arr->nelts,false);
1112 #define SHIB_AP_CHECK_IS_OK { \
1113 if (dc->bRequireAll < 1) \
1115 auth_OK[x] = true; \
1119 for (int x=0; x<reqs_arr->nelts; x++) {
1121 if (!(reqs[x].method_mask & (1 << m)))
1123 method_restricted=true;
1125 t = reqs[x].requirement;
1126 w = ap_getword_white(r->pool, &t);
1128 if (!strcasecmp(w,"Shibboleth")) {
1129 // This is a dummy rule needed because Apache conflates authn and authz.
1130 // Without some require rule, AuthType is ignored and no check_user hooks run.
1131 SHIB_AP_CHECK_IS_OK;
1133 else if (!strcmp(w,"valid-user") && application_id) {
1134 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting valid-user");
1135 SHIB_AP_CHECK_IS_OK;
1137 else if (!strcmp(w,"user") && SH_AP_USER(r)) {
1140 w=ap_getword_conf(r->pool,&t);
1148 // To do regex matching, we have to convert from UTF-8.
1149 auto_ptr<XMLCh> trans(fromUTF8(w));
1150 RegularExpression re(trans.get());
1151 auto_ptr<XMLCh> trans2(fromUTF8(SH_AP_USER(r)));
1152 if (re.matches(trans2.get())) {
1153 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting user: %s",w);
1154 SHIB_AP_CHECK_IS_OK;
1157 catch (XMLException& ex) {
1158 auto_ptr_char tmp(ex.getMessage());
1159 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
1160 "shib_auth_checker caught exception while parsing regular expression (%s): %s",w,tmp.get());
1163 else if (!strcmp(SH_AP_USER(r),w)) {
1164 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting user: %s",w);
1165 SHIB_AP_CHECK_IS_OK;
1169 else if (!strcmp(w,"group")) {
1170 SH_AP_TABLE* grpstatus=NULL;
1171 if (dc->szAuthGrpFile && SH_AP_USER(r)) {
1172 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() using groups file: %s\n",dc->szAuthGrpFile);
1173 grpstatus=groups_for_user(r,SH_AP_USER(r),dc->szAuthGrpFile);
1179 w=ap_getword_conf(r->pool,&t);
1180 if (ap_table_get(grpstatus,w)) {
1181 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting group: %s",w);
1182 SHIB_AP_CHECK_IS_OK;
1187 Iterator<IAAP*> provs=application ? application->getAAPProviders() : EMPTY(IAAP*);
1188 AAP wrapper(provs,w);
1189 if (wrapper.fail()) {
1190 ap_log_rerror(APLOG_MARK,APLOG_WARNING|APLOG_NOERRNO,SH_AP_R(r),
1191 "shib_auth_checker() didn't recognize require rule: %s\n",w);
1196 const char* vals=ap_table_get(r->headers_in,wrapper->getHeader());
1197 while (*t && vals) {
1198 w=ap_getword_conf(r->pool,&t);
1205 auto_ptr<RegularExpression> re;
1207 delete re.release();
1208 auto_ptr<XMLCh> trans(fromUTF8(w));
1209 auto_ptr<RegularExpression> temp(new RegularExpression(trans.get()));
1213 string vals_str(vals);
1215 for (int i = 0; i < vals_str.length(); i++) {
1216 if (vals_str.at(i) == ';') {
1218 ap_log_rerror(APLOG_MARK,APLOG_WARNING|APLOG_NOERRNO,SH_AP_R(r),
1219 "shib_auth_checker() invalid header encoding %s: starts with semicolon", vals);
1220 return SERVER_ERROR;
1223 if (vals_str.at(i-1) == '\\') {
1224 vals_str.erase(i-1, 1);
1229 string val = vals_str.substr(j, i-j);
1232 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
1233 if (re->matches(trans.get())) {
1234 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1235 "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
1236 SHIB_AP_CHECK_IS_OK;
1239 else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
1240 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1241 "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
1242 SHIB_AP_CHECK_IS_OK;
1245 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1246 "shib_auth_checker() expecting %s, got %s: authorization not granted", w, val.c_str());
1251 string val = vals_str.substr(j, vals_str.length()-j);
1253 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
1254 if (re->matches(trans.get())) {
1255 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1256 "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
1257 SHIB_AP_CHECK_IS_OK;
1260 else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
1261 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1262 "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
1263 SHIB_AP_CHECK_IS_OK;
1266 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1267 "shib_auth_checker() expecting %s, got %s: authorization not granted", w, val.c_str());
1270 catch (XMLException& ex) {
1271 auto_ptr_char tmp(ex.getMessage());
1272 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
1273 "shib_auth_checker caught exception while parsing regular expression (%s): %s",w,tmp.get());
1279 // check if all require directives are true
1280 bool auth_all_OK = true;
1281 for (int i= 0; i<reqs_arr->nelts; i++) {
1282 auth_all_OK &= auth_OK[i];
1287 if (!method_restricted)
1290 if (!application_id) {
1291 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
1292 "shib_auth_checker: Shib-Application-ID header not found in request");
1293 return HTTP_FORBIDDEN;
1295 else if (!application) {
1296 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
1297 "shib_auth_checker: unable to map request to application settings, check configuration");
1298 return HTTP_FORBIDDEN;
1301 ShibMLP markupProcessor;
1302 markupProcessor.insert("requestURL", ap_construct_url(r->pool,r->unparsed_uri,r));
1303 return shib_error_page(r, application, "access", markupProcessor);
1307 #ifndef SHIB_APACHE_13
1310 * Empty cleanup hook, Apache 2.x doesn't check NULL very well...
1312 extern "C" apr_status_t shib_exit(void* data)
1314 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,0,NULL,"shib_exit() done\n");
1322 * Cleanup the (per-process) pool info.
1324 #ifdef SHIB_APACHE_13
1325 extern "C" void shib_child_exit(server_rec* s, SH_AP_POOL* p)
1328 extern "C" apr_status_t shib_child_exit(void* data)
1330 server_rec* s = NULL;
1333 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit(%d) dealing with g_Config..", (int)getpid());
1334 g_Config->shutdown();
1336 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit() done\n");
1338 #ifndef SHIB_APACHE_13
1344 * shire_child_init()
1345 * Things to do when the child process is initialized.
1346 * (or after the configs are read in apache-2)
1348 #ifdef SHIB_APACHE_13
1349 extern "C" void shib_child_init(server_rec* s, SH_AP_POOL* p)
1351 extern "C" void shib_child_init(apr_pool_t* p, server_rec* s)
1354 // Initialize runtime components.
1356 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init(%d) starting", (int)getpid());
1359 ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() already initialized!");
1364 g_Config=&ShibTargetConfig::getConfig();
1365 g_Config->setFeatures(
1366 ShibTargetConfig::Listener |
1367 ShibTargetConfig::Metadata |
1368 ShibTargetConfig::AAP |
1369 ShibTargetConfig::RequestMapper |
1370 ShibTargetConfig::SHIREExtensions |
1371 ShibTargetConfig::Logging
1373 if (!g_Config->init(g_szSchemaDir,g_szSHIBConfig)) {
1374 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize SHIB Target");
1379 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize SHIB Target");
1383 // Set the cleanup handler
1384 apr_pool_cleanup_register(p, NULL, &shib_exit, &shib_child_exit);
1386 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() done");
1389 typedef const char* (*config_fn_t)(void);
1391 #ifdef SHIB_APACHE_13
1393 // SHIB Module commands
1395 static command_rec shire_cmds[] = {
1396 {"SHIREConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1397 RSRC_CONF, TAKE1, "Path to shibboleth.xml config file."},
1398 {"ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1399 RSRC_CONF, TAKE1, "Path to shibboleth.xml config file."},
1400 {"ShibSchemaDir", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1401 RSRC_CONF, TAKE1, "Path to Shibboleth XML schema directory."},
1403 {"ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
1404 (void *) XtOffsetOf (shib_server_config, szScheme),
1405 RSRC_CONF, TAKE1, "URL scheme to force into generated URLs for a vhost."},
1407 {"ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1408 (void *) XtOffsetOf (shib_dir_config, bBasicHijack),
1409 OR_AUTHCFG, FLAG, "Respond to AuthType Basic and convert to shib?"},
1410 {"ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1411 (void *) XtOffsetOf (shib_dir_config, bRequireSession),
1412 OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist."},
1413 {"ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1414 (void *) XtOffsetOf (shib_dir_config, bExportAssertion),
1415 OR_AUTHCFG, FLAG, "Export SAML assertion to Shibboleth-defined header?"},
1416 {"AuthGroupFile", (config_fn_t)ap_set_file_slot,
1417 (void *) XtOffsetOf (shib_dir_config, szAuthGrpFile),
1418 OR_AUTHCFG, TAKE1, "text file containing group names and member user IDs"},
1419 {"ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1420 (void *) XtOffsetOf (shib_dir_config, bRequireAll),
1421 OR_AUTHCFG, FLAG, "All require directives must match!"},
1427 handler_rec shib_handlers[] = {
1428 { "shib-shire-post", shib_post_handler },
1432 module MODULE_VAR_EXPORT mod_shib = {
1433 STANDARD_MODULE_STUFF,
1434 NULL, /* initializer */
1435 create_shib_dir_config, /* dir config creater */
1436 merge_shib_dir_config, /* dir merger --- default is to override */
1437 create_shib_server_config, /* server config */
1438 merge_shib_server_config, /* merge server config */
1439 shire_cmds, /* command table */
1440 shib_handlers, /* handlers */
1441 NULL, /* filename translation */
1442 shib_check_user, /* check_user_id */
1443 shib_auth_checker, /* check auth */
1444 NULL, /* check access */
1445 NULL, /* type_checker */
1448 NULL, /* header parser */
1449 shib_child_init, /* child_init */
1450 shib_child_exit, /* child_exit */
1451 NULL /* post read-request */
1454 #elif defined(SHIB_APACHE_20)
1456 extern "C" void shib_register_hooks (apr_pool_t *p)
1458 ap_hook_child_init(shib_child_init, NULL, NULL, APR_HOOK_MIDDLE);
1459 ap_hook_check_user_id(shib_check_user, NULL, NULL, APR_HOOK_MIDDLE);
1460 ap_hook_auth_checker(shib_auth_checker, NULL, NULL, APR_HOOK_FIRST);
1461 ap_hook_handler(shib_post_handler, NULL, NULL, APR_HOOK_LAST);
1464 // SHIB Module commands
1467 static command_rec shib_cmds[] = {
1468 AP_INIT_TAKE1("ShibConfig",
1469 (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1470 RSRC_CONF, "Path to shibboleth.xml config file."),
1471 AP_INIT_TAKE1("ShibSchemaDir",
1472 (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1473 RSRC_CONF, "Path to Shibboleth XML schema directory."),
1475 AP_INIT_TAKE1("ShibURLScheme",
1476 (config_fn_t)shib_set_server_string_slot,
1477 (void *) offsetof (shib_server_config, szScheme),
1478 RSRC_CONF, "URL scheme to force into generated URLs for a vhost."),
1480 AP_INIT_FLAG("ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1481 (void *) offsetof (shib_dir_config, bBasicHijack),
1482 OR_AUTHCFG, "Respond to AuthType Basic and convert to shib?"),
1483 AP_INIT_FLAG("ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1484 (void *) offsetof (shib_dir_config, bRequireSession),
1485 OR_AUTHCFG, "Initiates a new session if one does not exist."),
1486 AP_INIT_FLAG("ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1487 (void *) offsetof (shib_dir_config, bExportAssertion),
1488 OR_AUTHCFG, "Export SAML assertion to Shibboleth-defined header?"),
1489 AP_INIT_TAKE1("AuthGroupFile", (config_fn_t)ap_set_file_slot,
1490 (void *) offsetof (shib_dir_config, szAuthGrpFile),
1491 OR_AUTHCFG, "text file containing group names and member user IDs"),
1492 AP_INIT_FLAG("ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1493 (void *) offsetof (shib_dir_config, bRequireAll),
1494 OR_AUTHCFG, "All require directives must match!"),
1499 module AP_MODULE_DECLARE_DATA mod_shib = {
1500 STANDARD20_MODULE_STUFF,
1501 create_shib_dir_config, /* create dir config */
1502 merge_shib_dir_config, /* merge dir config --- default is to override */
1503 create_shib_server_config, /* create server config */
1504 merge_shib_server_config, /* merge server config */
1505 shib_cmds, /* command table */
1506 shib_register_hooks /* register hooks */
1510 #error "undefined APACHE version"