2 * mod_apache.cpp -- the core Apache Module code
4 * Created by: Derek Atkins <derek@ihtfp.com>
10 #undef _XOPEN_SOURCE // causes gethostname conflict in unistd.h
14 #include <saml/saml.h>
15 #include <shib/shib.h>
16 #include <shib/shib-threads.h>
17 #include <shib-target/shib-target.h>
18 #include <xercesc/util/regx/RegularExpression.hpp>
22 // Apache specific header files
24 #include <http_config.h>
25 #include <http_protocol.h>
26 #include <http_main.h>
28 #include <http_core.h>
31 #ifndef SHIB_APACHE_13
32 #include <http_request.h>
33 #include <apr_strings.h>
34 #include <apr_pools.h>
41 #include <unistd.h> // for getpid()
46 using namespace shibboleth;
47 using namespace shibtarget;
49 extern "C" module MODULE_VAR_EXPORT mod_shib;
51 int shib_handler(request_rec* r, const IApplication* application, SHIRE& shire);
55 char* g_szSHIBConfig = NULL;
56 char* g_szSchemaDir = NULL;
57 ShibTargetConfig* g_Config = NULL;
58 static const char* g_UserDataKey = "_shib_check_user_";
61 /********************************************************************************/
62 // Basic Apache Configuration code.
65 // per-server module configuration structure
66 struct shib_server_config
71 // creates the per-server configuration
72 extern "C" void* create_shib_server_config(SH_AP_POOL* p, server_rec* s)
74 shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
79 // overrides server configuration in virtual servers
80 extern "C" void* merge_shib_server_config (SH_AP_POOL* p, void* base, void* sub)
82 shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
83 shib_server_config* parent=(shib_server_config*)base;
84 shib_server_config* child=(shib_server_config*)sub;
87 sc->szScheme=ap_pstrdup(p,child->szScheme);
88 else if (parent->szScheme)
89 sc->szScheme=ap_pstrdup(p,parent->szScheme);
96 // per-dir module configuration structure
97 struct shib_dir_config
100 char* szAuthGrpFile; // Auth GroupFile name
101 int bRequireAll; // all require directives must match, otherwise OR logic
103 // SHIRE Configuration
104 int bBasicHijack; // activate for AuthType Basic?
105 int bRequireSession; // require a session?
106 int bExportAssertion; // export SAML assertion to the environment?
109 // creates per-directory config structure
110 extern "C" void* create_shib_dir_config (SH_AP_POOL* p, char* d)
112 shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
113 dc->bBasicHijack = -1;
114 dc->bRequireSession = -1;
115 dc->bExportAssertion = -1;
116 dc->bRequireAll = -1;
117 dc->szAuthGrpFile = NULL;
121 // overrides server configuration in directories
122 extern "C" void* merge_shib_dir_config (SH_AP_POOL* p, void* base, void* sub)
124 shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
125 shib_dir_config* parent=(shib_dir_config*)base;
126 shib_dir_config* child=(shib_dir_config*)sub;
128 if (child->szAuthGrpFile)
129 dc->szAuthGrpFile=ap_pstrdup(p,child->szAuthGrpFile);
130 else if (parent->szAuthGrpFile)
131 dc->szAuthGrpFile=ap_pstrdup(p,parent->szAuthGrpFile);
133 dc->szAuthGrpFile=NULL;
135 dc->bBasicHijack=((child->bBasicHijack==-1) ? parent->bBasicHijack : child->bBasicHijack);
136 dc->bRequireSession=((child->bRequireSession==-1) ? parent->bRequireSession : child->bRequireSession);
137 dc->bExportAssertion=((child->bExportAssertion==-1) ? parent->bExportAssertion : child->bExportAssertion);
138 dc->bRequireAll=((child->bRequireAll==-1) ? parent->bRequireAll : child->bRequireAll);
142 // generic global slot handlers
143 extern "C" const char* ap_set_global_string_slot(cmd_parms* parms, void*, const char* arg)
145 *((char**)(parms->info))=ap_pstrdup(parms->pool,arg);
149 extern "C" const char* shib_set_server_string_slot(cmd_parms* parms, void*, const char* arg)
151 char* base=(char*)ap_get_module_config(parms->server->module_config,&mod_shib);
152 int offset=(int)parms->info;
153 *((char**)(base + offset))=ap_pstrdup(parms->pool,arg);
157 extern "C" const char* shib_ap_set_file_slot(cmd_parms* parms, void* arg1, const char* arg2)
159 ap_set_file_slot(parms, arg1, arg2);
163 /********************************************************************************/
164 // Some other useful helper function(s)
166 static SH_AP_TABLE* groups_for_user(request_rec* r, const char* user, char* grpfile)
169 SH_AP_TABLE* grps=ap_make_table(r->pool,15);
170 char l[MAX_STRING_LEN];
171 const char *group_name, *ll, *w;
173 #ifdef SHIB_APACHE_13
174 if (!(f=ap_pcfg_openfile(r->pool,grpfile))) {
176 if (ap_pcfg_openfile(&f,r->pool,grpfile) != APR_SUCCESS) {
178 ap_log_rerror(APLOG_MARK,APLOG_DEBUG,SH_AP_R(r),"groups_for_user() could not open group file: %s\n",grpfile);
183 #ifdef SHIB_APACHE_13
184 sp=ap_make_sub_pool(r->pool);
186 if (apr_pool_create(&sp,r->pool) != APR_SUCCESS) {
187 ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,
188 "groups_for_user() could not create a subpool");
193 while (!(ap_cfg_getline(l,MAX_STRING_LEN,f))) {
194 if ((*l=='#') || (!*l))
199 group_name=ap_getword(sp,&ll,':');
202 w=ap_getword_conf(sp,&ll);
203 if (!strcmp(w,user)) {
204 ap_table_setn(grps,ap_pstrdup(r->pool,group_name),"in");
214 /********************************************************************************/
215 // Apache ShibTarget subclass(es) here.
217 class HTGroupTableApache : public HTGroupTable
220 HTGroupTableApache(request_rec* r, const char *user, char *grpfile) {
221 groups = groups_for_user(r, user, grpfile);
223 throw ShibTargetException(SHIBRPC_OK, "EEP");
225 ~HTGroupTableApache() {}
226 bool lookup(const char *entry) { return (ap_table_get(groups, entry)!=NULL); }
230 class ShibTargetApache : public ShibTarget
233 ShibTargetApache(request_rec* req) {
234 m_sc = (shib_server_config*)
235 ap_get_module_config(req->server->module_config, &mod_shib);
237 m_dc = (shib_dir_config*)ap_get_module_config(req->per_dir_config, &mod_shib);
239 const char* ct = ap_table_get(req->headers_in, "Content-type");
241 init(g_Config, string(m_sc->szScheme ? m_sc->szScheme : ap_http_method(req)),
242 string(ap_get_server_name(req)), (int)ap_get_server_port(req),
243 string(req->unparsed_uri), string(ct ? ct : ""),
244 string(req->connection->remote_ip), string(req->method));
248 ~ShibTargetApache() { }
250 virtual void log(ShibLogLevel level, const string &msg) {
251 ap_log_rerror(APLOG_MARK,
252 (level == LogLevelDebug ? APLOG_DEBUG :
253 (level == LogLevelInfo ? APLOG_INFO :
254 (level == LogLevelWarn ? APLOG_WARNING :
255 APLOG_ERR)))|APLOG_NOERRNO, SH_AP_R(m_req),
258 virtual string getCookies(void) {
259 const char *c = ap_table_get(m_req->headers_in, "Cookie");
260 return string(c ? c : "");
262 virtual void setCookie(const string &name, const string &value) {
263 char* val = ap_psprintf(m_req->pool, "%s=%s", name.c_str(), value.c_str());
264 ap_table_setn(m_req->err_headers_out, "Set-Cookie", val);
266 virtual string getArgs(void) { return string(m_req->args ? m_req->args : ""); }
267 virtual string getPostData(void) {
268 // Read the posted data
269 if (ap_setup_client_block(m_req, REQUEST_CHUNKED_ERROR))
270 throw ShibTargetException(SHIBRPC_OK, "CGI setup_client_block failed");
271 if (!ap_should_client_block(m_req))
272 throw ShibTargetException(SHIBRPC_OK, "CGI should_client_block failed");
273 if (m_req->remaining > 1024*1024)
274 throw ShibTargetException (SHIBRPC_OK, "CGI length too long...");
277 char buff[HUGE_STRING_LEN];
278 ap_hard_timeout("[mod_shib] getPostData", m_req);
279 memset(buff, 0, sizeof(buff));
280 while (ap_get_client_block(m_req, buff, sizeof(buff)-1) > 0) {
281 ap_reset_timeout(m_req);
283 memset(buff, 0, sizeof(buff));
285 ap_kill_timeout(m_req);
289 virtual void clearHeader(const string &name) {
290 ap_table_unset(m_req->headers_in, name.c_str());
292 virtual void setHeader(const string &name, const string &value) {
293 ap_table_set(m_req->headers_in, name.c_str(), value.c_str());
295 virtual string getHeader(const string &name) {
296 const char *hdr = ap_table_get(m_req->headers_in, name.c_str());
297 return string(hdr ? hdr : "");
299 virtual void setRemoteUser(const string &user) {
300 SH_AP_USER(m_req) = ap_pstrdup(m_req->pool, user.c_str());
302 virtual string getRemoteUser(void) {
303 return string(SH_AP_USER(m_req) ? SH_AP_USER(m_req) : "");
305 // override so we can look at the actual auth type and maybe override it.
306 virtual string getAuthType(void) {
307 const char *auth_type=ap_auth_type(m_req);
310 if (strcasecmp(auth_type, "shibboleth")) {
311 if (!strcasecmp(auth_type, "basic") && m_dc->bBasicHijack == 1) {
312 core_dir_config* conf= (core_dir_config*)
313 ap_get_module_config(m_req->per_dir_config,
314 ap_find_linked_module("http_core.c"));
315 auth_type = conf->ap_auth_type = "shibboleth";
318 return string(auth_type);
320 // Override this function because we want to add the Apache Directory override
321 virtual pair<bool,bool> getRequireSession(IRequestMapper::Settings &settings) {
322 pair<bool,bool> requireSession = settings.first->getBool("requireSession");
323 if (!requireSession.first || !requireSession.second)
324 if (m_dc->bRequireSession == 1)
325 requireSession.second=true;
327 return requireSession;
330 virtual HTAccessInfo* getAccessInfo(void) {
331 int m = m_req->method_number;
332 const array_header* reqs_arr = ap_requires(m_req);
336 require_line* reqs = (require_line*) reqs_arr->elts;
338 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req),
339 "REQUIRE nelts: %d", reqs_arr->nelts);
340 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req),
341 "REQUIRE all: %d", m_dc->bRequireAll);
343 HTAccessInfo* ht = new HTAccessInfo();
344 ht->requireAll = (m_dc->bRequireAll >= 0);
345 ht->elements.reserve(reqs_arr->nelts);
346 for (int x = 0; x < reqs_arr->nelts; x++) {
347 HTAccessInfo::RequireLine* rline = new HTAccessInfo::RequireLine();
348 rline->use_line = (reqs[x].method_mask & (1 << m));
349 rline->tokens.reserve(6); // No reason to reserve specifically 6 tokens
350 const char* t = reqs[x].requirement;
351 const char* w = ap_getword_white(m_req->pool, &t);
352 rline->tokens.push_back(w);
354 w = ap_getword_conf(m_req->pool, &t);
355 rline->tokens.push_back(w);
357 ht->elements.push_back(rline);
361 virtual HTGroupTable* getGroupTable(string &user) {
362 if (m_dc->szAuthGrpFile && !user.empty()) {
363 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req),
364 "getGroupTable() using groups file: %s\n",
365 m_dc->szAuthGrpFile);
367 HTGroupTableApache *gt = new HTGroupTableApache(m_req, user.c_str(),
368 m_dc->szAuthGrpFile);
375 virtual void* sendPage(const string &msg, const string content_type,
376 const pair<string, string> headers[], int code) {
377 m_req->content_type = ap_psprintf(m_req->pool, content_type.c_str());
378 // XXX: push headers and code into the response
379 ap_send_http_header(m_req);
380 ap_rprintf(m_req, msg.c_str());
383 virtual void* sendRedirect(const string url) {
384 ap_table_set(m_req->headers_out, "Location", url.c_str());
385 return (void*)REDIRECT;
387 virtual void* returnDecline(void) { return (void*)DECLINED; }
388 virtual void* returnOK(void) { return (void*)OK; }
391 shib_dir_config* m_dc;
392 shib_server_config* m_sc;
395 /********************************************************************************/
398 extern "C" int shib_check_user(request_rec* r)
400 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
401 "shib_check_user(%d): ENTER\n", (int)getpid());
403 ostringstream threadid;
404 threadid << "[" << getpid() << "] shib_check_user" << '\0';
405 saml::NDC ndc(threadid.str().c_str());
410 ShibTargetApache sta(r);
412 // Check user authentication, the set the post handler bypass
413 pair<bool,void*> res = sta.doCheckAuthN((sta.m_dc->bRequireSession == 1), true);
414 apr_pool_userdata_setn((const void*)42,g_UserDataKey,NULL,r->pool);
415 if (res.first) return (int)res.second;
417 // user auth was okay -- export the assertions now
418 res = sta.doExportAssertions((sta.m_dc->bExportAssertion == 1));
419 if (res.first) return (int)res.second;
421 // export happened successfully.. this user is ok.
426 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r),
427 "shib_check_user threw an uncaught exception!");
433 extern "C" int shib_post_handler(request_rec* r)
435 ostringstream threadid;
436 threadid << "[" << getpid() << "] shib_post_handler" << '\0';
437 saml::NDC ndc(threadid.str().c_str());
439 #ifndef SHIB_APACHE_13
440 // With 2.x, this handler always runs, though last.
441 // We check if shib_check_user ran, because it will detect a SHIRE request
442 // and dispatch it directly.
444 apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
445 if (data==(const void*)42) {
446 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_post_handler skipped since check_user ran");
451 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
452 "shib_post_handler(%d): ENTER", (int)getpid());
457 ShibTargetApache sta(r);
459 pair<bool,void*> res = sta.doHandlePOST();
460 if (res.first) return (int)res.second;
462 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r),
463 "doHandlePOST() did not do anything.");
468 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r),
469 "shib_post_handler threw an uncaught exception!");
476 * shib_auth_checker() -- a simple resource manager to
477 * process the .htaccess settings and copy attributes
478 * into the HTTP headers.
480 extern "C" int shib_auth_checker(request_rec* r)
482 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
483 "shib_check_user(%d): ENTER", (int)getpid());
485 ostringstream threadid;
486 threadid << "[" << getpid() << "] shib_auth_checker" << '\0';
487 saml::NDC ndc(threadid.str().c_str());
492 ShibTargetApache sta(r);
494 pair<bool,void*> res = sta.doCheckAuthZ();
495 if (res.first) return (int)res.second;
502 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r),
503 "shib_auth_checker threw an uncaught exception!");
510 static char* shib_get_targeturl(request_rec* r, const char* scheme=NULL)
512 // On 1.3, this is always canonical, but on 2.0, UseCanonicalName comes into play.
513 // However, we also have a setting to forcibly replace the scheme for esoteric cases.
515 unsigned port = ap_get_server_port(r);
516 if ((!strcmp(scheme,"http") && port==80) || (!strcmp(scheme,"https") && port==443)) {
517 return ap_pstrcat(r->pool, scheme, "://", ap_get_server_name(r), r->unparsed_uri, NULL);
519 return ap_psprintf(r->pool, "%s://%s:%u%s", scheme, ap_get_server_name(r), port, r->unparsed_uri);
521 return ap_construct_url(r->pool,r->unparsed_uri,r);
524 extern "C" int shib_check_user(request_rec* r)
526 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: ENTER");
527 shib_dir_config* dc=(shib_dir_config*)ap_get_module_config(r->per_dir_config,&mod_shib);
528 shib_server_config* sc=(shib_server_config*)ap_get_module_config(r->server->module_config,&mod_shib);
530 ostringstream threadid;
531 threadid << "[" << getpid() << "] shib_check_user" << '\0';
532 saml::NDC ndc(threadid.str().c_str());
534 const char* targeturl=shib_get_targeturl(r,sc->szScheme);
536 // We lock the configuration system for the duration.
537 IConfig* conf=g_Config->getINI();
540 // Map request to application and content settings.
541 IRequestMapper* mapper=conf->getRequestMapper();
542 Locker locker2(mapper);
543 IRequestMapper::Settings settings=mapper->getSettingsFromParsedURL(
544 (sc-> szScheme ? sc-> szScheme : ap_http_method(r)), ap_get_server_name(r), ap_get_server_port(r), r->unparsed_uri
546 pair<bool,const char*> application_id=settings.first->getString("applicationId");
547 const IApplication* application=conf->getApplication(application_id.second);
549 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
550 "shib_check_user: unable to map request to application settings, check configuration");
554 // Declare SHIRE object for this request.
555 SHIRE shire(application);
557 const char* shireURL=shire.getShireURL(targeturl);
559 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
560 "shib_check_user: unable to map request to proper shireURL setting, check configuration");
564 // Get location of this application's assertion consumer service and see if this is it.
565 if (strstr(targeturl,shireURL)) {
566 return shib_handler(r,application,shire);
569 // We can short circuit the handler if we run this...
570 apr_pool_userdata_setn((const void*)42,g_UserDataKey,NULL,r->pool);
572 // Regular access to arbitrary resource...check AuthType
573 const char *auth_type=ap_auth_type(r);
577 if (strcasecmp(auth_type,"shibboleth")) {
578 if (!strcasecmp(auth_type,"basic") && dc->bBasicHijack==1) {
579 core_dir_config* conf=
580 (core_dir_config*)ap_get_module_config(r->per_dir_config,
581 ap_find_linked_module("http_core.c"));
582 conf->ap_auth_type="shibboleth";
588 pair<bool,bool> requireSession = settings.first->getBool("requireSession");
589 if (!requireSession.first || !requireSession.second)
590 if (dc->bRequireSession==1)
591 requireSession.second=true;
593 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: session check for %s",targeturl);
595 pair<const char*,const char*> shib_cookie=shire.getCookieNameProps(); // always returns *something*
597 // We're in charge, so check for cookie.
598 const char* session_id=NULL;
599 const char* cookies=ap_table_get(r->headers_in,"Cookie");
602 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: cookies found: %s",cookies);
603 if (session_id=strstr(cookies,shib_cookie.first)) {
604 // Yep, we found a cookie -- pull it out (our session_id)
605 session_id+=strlen(shib_cookie.first) + 1; /* Skip over the '=' */
606 char* cookiebuf = ap_pstrdup(r->pool,session_id);
607 char* cookieend = strchr(cookiebuf,';');
609 *cookieend = '\0'; /* Ignore anyting after a ; */
610 session_id=cookiebuf;
614 if (!session_id || !*session_id) {
615 // If no session required, bail now.
616 if (!requireSession.second)
619 // No acceptable cookie, and we require a session. Generate an AuthnRequest.
620 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: no cookie found -- redirecting to WAYF");
621 ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(targeturl)));
625 // Make sure this session is still valid.
626 RPCError* status = NULL;
627 ShibMLP markupProcessor;
628 markupProcessor.insert("requestURL", targeturl);
631 status = shire.sessionIsValid(session_id, r->connection->remote_ip);
633 catch (ShibTargetException &e) {
634 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): %s", e.what());
635 markupProcessor.insert("errorType", "Session Processing Error");
636 markupProcessor.insert("errorText", e.what());
637 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
638 return shib_error_page(r, application, "shire", markupProcessor);
642 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): caught unexpected error");
643 markupProcessor.insert("errorType", "Session Processing Error");
644 markupProcessor.insert("errorText", "Unexpected Exception");
645 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
646 return shib_error_page(r, application, "shire", markupProcessor);
651 if (status->isError()) {
652 ap_log_rerror(APLOG_MARK,APLOG_INFO|APLOG_NOERRNO,SH_AP_R(r),
653 "shib_check_user() session invalid: %s", status->getText());
655 // If no session required, bail now.
656 if (!requireSession.second)
657 return OK; // XXX: Or should this be DECLINED?
658 // Has to be OK because DECLINED will just cause Apache to fail when it can't locate
659 // anything to process the AuthType. No session plus requireSession false means
660 // do not authenticate the user.
661 else if (status->isRetryable()) {
662 // Oops, session is invalid. Generate AuthnRequest.
663 ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(targeturl)));
668 // return the error page to the user
669 markupProcessor.insert(*status);
671 return shib_error_page(r, application, "shire", markupProcessor);
677 #ifdef SHIB_APACHE_13
679 r->connection->ap_auth_type = "shibboleth";
681 r->ap_auth_type = "shibboleth";
683 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: session successfully verified");
685 // This is code transferred in from the auth check to export the attributes.
686 // We could even combine the isSessionValid/getAssertions API...?
689 vector<SAMLAssertion*> assertions;
690 SAMLAuthenticationStatement* sso_statement=NULL;
693 status = rm.getAssertions(session_id, r->connection->remote_ip, assertions, &sso_statement);
695 catch (ShibTargetException &e) {
696 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): %s", e.what());
697 markupProcessor.insert("errorType", "Attribute Processing Error");
698 markupProcessor.insert("errorText", e.what());
699 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
700 return shib_error_page(r, application, "rm", markupProcessor);
704 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): caught unexpected error");
705 markupProcessor.insert("errorType", "Attribute Processing Error");
706 markupProcessor.insert("errorText", "Unexpected Exception");
707 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
708 return shib_error_page(r, application, "rm", markupProcessor);
712 if (status->isError()) {
713 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
714 "shib_check_user() getAssertions failed: %s", status->getText());
716 markupProcessor.insert(*status);
718 return shib_error_page(r, application, "rm", markupProcessor);
722 // Do we have an access control plugin?
723 if (settings.second) {
724 Locker acllock(settings.second);
725 if (!settings.second->authorized(*sso_statement,assertions)) {
726 for (int k = 0; k < assertions.size(); k++)
727 delete assertions[k];
728 delete sso_statement;
729 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): access control provider denied access");
730 return shib_error_page(r, application, "access", markupProcessor);
734 // Get the AAP providers, which contain the attribute policy info.
735 Iterator<IAAP*> provs=application->getAAPProviders();
737 // Clear out the list of mapped attributes
738 while (provs.hasNext()) {
739 IAAP* aap=provs.next();
742 Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
743 while (rules.hasNext()) {
744 const char* header=rules.next()->getHeader();
746 ap_table_unset(r->headers_in,header);
751 for (int k = 0; k < assertions.size(); k++)
752 delete assertions[k];
753 delete sso_statement;
754 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
755 "shib_check_user(): caught unexpected error while clearing headers");
756 markupProcessor.insert("errorType", "Attribute Processing Error");
757 markupProcessor.insert("errorText", "Unexpected Exception");
758 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
759 return shib_error_page(r, application, "rm", markupProcessor);
765 // Maybe export the first assertion.
766 ap_table_unset(r->headers_in,"Shib-Attributes");
767 pair<bool,bool> exp=settings.first->getBool("exportAssertion");
768 if (!exp.first || !exp.second)
769 if (dc->bExportAssertion==1)
771 if (exp.second && assertions.size()) {
773 RM::serialize(*(assertions[0]), assertion);
774 ap_table_set(r->headers_in,"Shib-Attributes", assertion.c_str());
777 // Export the SAML AuthnMethod and the origin site name, and possibly the NameIdentifier.
778 ap_table_unset(r->headers_in,"Shib-Origin-Site");
779 ap_table_unset(r->headers_in,"Shib-Authentication-Method");
780 ap_table_unset(r->headers_in,"Shib-NameIdentifier-Format");
781 auto_ptr_char os(sso_statement->getSubject()->getNameIdentifier()->getNameQualifier());
782 auto_ptr_char am(sso_statement->getAuthMethod());
783 ap_table_set(r->headers_in,"Shib-Origin-Site", os.get());
784 ap_table_set(r->headers_in,"Shib-Authentication-Method", am.get());
787 AAP wrapper(provs,sso_statement->getSubject()->getNameIdentifier()->getFormat(),Constants::SHIB_ATTRIBUTE_NAMESPACE_URI);
788 if (!wrapper.fail() && wrapper->getHeader()) {
789 auto_ptr_char form(sso_statement->getSubject()->getNameIdentifier()->getFormat());
790 auto_ptr_char nameid(sso_statement->getSubject()->getNameIdentifier()->getName());
791 ap_table_set(r->headers_in,"Shib-NameIdentifier-Format",form.get());
792 if (!strcmp(wrapper->getHeader(),"REMOTE_USER"))
793 SH_AP_USER(r)=ap_pstrdup(r->pool,nameid.get());
795 ap_table_set(r->headers_in,wrapper->getHeader(),nameid.get());
798 ap_table_unset(r->headers_in,"Shib-Application-ID");
799 ap_table_set(r->headers_in,"Shib-Application-ID",application_id.second);
801 // Export the attributes.
802 Iterator<SAMLAssertion*> a_iter(assertions);
803 while (a_iter.hasNext()) {
804 SAMLAssertion* assert=a_iter.next();
805 Iterator<SAMLStatement*> statements=assert->getStatements();
806 while (statements.hasNext()) {
807 SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());
810 Iterator<SAMLAttribute*> attrs=astate->getAttributes();
811 while (attrs.hasNext()) {
812 SAMLAttribute* attr=attrs.next();
814 // Are we supposed to export it?
815 AAP wrapper(provs,attr->getName(),attr->getNamespace());
816 if (wrapper.fail() || !wrapper->getHeader())
819 Iterator<string> vals=attr->getSingleByteValues();
820 if (!strcmp(wrapper->getHeader(),"REMOTE_USER") && vals.hasNext())
821 SH_AP_USER(r)=ap_pstrdup(r->pool,vals.next().c_str());
824 char* header = (char*)ap_table_get(r->headers_in, wrapper->getHeader());
826 header=ap_pstrdup(r->pool, header);
830 header = ap_pstrdup(r->pool, "");
831 for (; vals.hasNext(); it++) {
832 string value = vals.next();
833 for (string::size_type pos = value.find_first_of(";", string::size_type(0));
835 pos = value.find_first_of(";", pos)) {
836 value.insert(pos, "\\");
839 header=ap_pstrcat(r->pool, header, (it ? ";" : ""), value.c_str(), NULL);
841 ap_table_setn(r->headers_in, wrapper->getHeader(), header);
848 for (int k = 0; k < assertions.size(); k++)
849 delete assertions[k];
850 delete sso_statement;
855 extern "C" int shib_post_handler(request_rec* r)
857 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
858 "shib_post_handler(%d): ENTER", (int)getpid());
859 shib_server_config* sc=(shib_server_config*)ap_get_module_config(r->server->module_config,&mod_shib);
861 #ifndef SHIB_APACHE_13
862 // With 2.x, this handler always runs, though last.
863 // We check if shib_check_user ran, because it will detect a SHIRE request
864 // and dispatch it directly.
866 apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
867 if (data==(const void*)42) {
868 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_post_handler skipped since check_user ran");
873 ostringstream threadid;
874 threadid << "[" << getpid() << "] shib_post_handler" << '\0';
875 saml::NDC ndc(threadid.str().c_str());
877 // We lock the configuration system for the duration.
878 IConfig* conf=g_Config->getINI();
881 // Map request to application and content settings.
882 IRequestMapper* mapper=conf->getRequestMapper();
883 Locker locker2(mapper);
884 IRequestMapper::Settings settings=mapper->getSettingsFromParsedURL(
885 (sc->szScheme ? sc->szScheme : ap_http_method(r)), ap_get_server_name(r), ap_get_server_port(r), r->unparsed_uri
887 pair<bool,const char*> application_id=settings.first->getString("applicationId");
888 const IApplication* application=conf->getApplication(application_id.second);
890 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
891 "shib_post_handler: unable to map request to application settings, check configuration");
895 // Declare SHIRE object for this request.
896 SHIRE shire(application);
898 return shib_handler(r, application, shire);
901 int shib_handler(request_rec* r, const IApplication* application, SHIRE& shire)
903 shib_server_config* sc=(shib_server_config*)ap_get_module_config(r->server->module_config,&mod_shib);
905 const char* targeturl=shib_get_targeturl(r,sc->szScheme);
907 const char* shireURL=shire.getShireURL(targeturl);
909 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
910 "shib_post_handler: unable to map request to proper shireURL setting, check configuration");
914 // Make sure we only process the SHIRE requests.
915 if (!strstr(targeturl,shireURL))
918 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler() running");
920 const IPropertySet* sessionProps=application->getPropertySet("Sessions");
922 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
923 "shib_post_handler: unable to map request to application session settings, check configuration");
927 pair<const char*,const char*> shib_cookie=shire.getCookieNameProps(); // always returns something
929 ShibMLP markupProcessor;
930 markupProcessor.insert("requestURL", targeturl);
932 // Process SHIRE request
933 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() Beginning SHIRE processing");
936 pair<bool,bool> shireSSL=sessionProps->getBool("shireSSL");
938 // Make sure this is SSL, if it should be
939 if ((!shireSSL.first || shireSSL.second) && strcmp(ap_http_method(r),"https"))
940 throw ShibTargetException(SHIBRPC_OK, "blocked non-SSL access to session creation service");
942 // If this is a GET, we manufacture an AuthnRequest.
943 if (!strcasecmp(r->method,"GET")) {
944 const char* areq=r->args ? shire.getLazyAuthnRequest(r->args) : NULL;
946 throw ShibTargetException(SHIBRPC_OK, "malformed arguments to request a new session");
947 ap_table_setn(r->headers_out, "Location", ap_pstrdup(r->pool,areq));
950 else if (strcasecmp(r->method,"POST")) {
951 throw ShibTargetException(SHIBRPC_OK, "blocked non-POST to SHIRE POST processor");
954 // Sure sure this POST is an appropriate content type
955 const char *ct = ap_table_get(r->headers_in, "Content-type");
956 if (!ct || strcasecmp(ct, "application/x-www-form-urlencoded"))
957 throw ShibTargetException(SHIBRPC_OK,
958 ap_psprintf(r->pool, "blocked bad content-type to SHIRE POST processor: %s", (ct ? ct : "")));
960 // Read the posted data
961 if (ap_setup_client_block(r, REQUEST_CHUNKED_ERROR))
962 throw ShibTargetException(SHIBRPC_OK, "CGI setup_client_block failed");
963 if (!ap_should_client_block(r))
964 throw ShibTargetException(SHIBRPC_OK, "CGI should_client_block failed");
965 if (r->remaining > 1024*1024)
966 throw ShibTargetException (SHIBRPC_OK, "CGI length too long...");
969 char buff[HUGE_STRING_LEN];
970 ap_hard_timeout("[mod_shib] CGI Parser", r);
971 memset(buff, 0, sizeof(buff));
972 while (ap_get_client_block(r, buff, sizeof(buff)-1) > 0) {
975 memset(buff, 0, sizeof(buff));
979 // Parse the submission.
980 pair<const char*,const char*> elements=shire.getFormSubmission(cgistr.c_str(),cgistr.length());
982 // Make sure the SAML Response parameter exists
983 if (!elements.first || !*elements.first)
984 throw ShibTargetException(SHIBRPC_OK, "SHIRE POST failed to find SAMLResponse form element");
986 // Make sure the target parameter exists
987 if (!elements.second || !*elements.second)
988 throw ShibTargetException(SHIBRPC_OK, "SHIRE POST failed to find TARGET form element");
990 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
991 "shib_handler() Processing POST for target: %s", elements.second);
995 RPCError* status = shire.sessionCreate(elements.first, r->connection->remote_ip, cookie);
997 if (status->isError()) {
998 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
999 "shib_handler() POST process failed (%d): %s", status->getCode(), status->getText());
1001 if (status->isRetryable()) {
1003 ap_log_rerror(APLOG_MARK,APLOG_INFO|APLOG_NOERRNO,SH_AP_R(r),
1004 "shib_handler() retryable error, generating new AuthnRequest");
1005 ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(elements.second)));
1009 // return this error to the user.
1010 markupProcessor.insert(*status);
1012 return shib_error_page(r, application, "shire", markupProcessor);
1016 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1017 "shib_handler() POST process succeeded. New session: %s", cookie.c_str());
1019 // We've got a good session, set the cookie...
1020 char* val = ap_psprintf(r->pool,"%s=%s%s",shib_cookie.first,cookie.c_str(),shib_cookie.second);
1021 ap_table_setn(r->err_headers_out, "Set-Cookie", val);
1022 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() setting cookie: %s", val);
1024 // ... and redirect to the target
1025 ap_table_setn(r->headers_out, "Location", ap_pstrdup(r->pool,elements.second));
1028 catch (ShibTargetException &e) {
1029 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() caught exception: %s", e.what());
1030 markupProcessor.insert("errorType", "Session Creation Service Error");
1031 markupProcessor.insert("errorText", e.what());
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_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler(): unexpected exception");
1038 markupProcessor.insert("errorType", "Session Creation Service Error");
1039 markupProcessor.insert("errorText", "Unknown Exception");
1040 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
1041 return shib_error_page(r, application, "shire", markupProcessor);
1045 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_handler() server error");
1046 return SERVER_ERROR;
1049 static int shib_error_page(request_rec* r, const IApplication* app, const char* page, ShibMLP& mlp)
1051 const IPropertySet* props=app->getPropertySet("Errors");
1053 pair<bool,const char*> p=props->getString(page);
1055 ifstream infile(p.second);
1056 if (!infile.fail()) {
1057 const char* res = mlp.run(infile,props);
1059 r->content_type = ap_psprintf(r->pool, "text/html");
1060 ap_send_http_header(r);
1068 ap_log_rerror(APLOG_MARK,APLOG_ERR,SH_AP_R(r),
1069 "shib_error_page() could not process shire error template for application %s",app->getId());
1070 return SERVER_ERROR;
1074 * shib_auth_checker() -- a simple resource manager to
1075 * process the .htaccess settings and copy attributes
1076 * into the HTTP headers.
1078 extern "C" int shib_auth_checker(request_rec* r)
1080 shib_dir_config* dc=
1081 (shib_dir_config*)ap_get_module_config(r->per_dir_config,&mod_shib);
1083 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() executing");
1085 // Regular access to arbitrary resource...check AuthType
1086 const char* auth_type=ap_auth_type(r);
1087 if (!auth_type || strcasecmp(auth_type,"shibboleth"))
1090 ostringstream threadid;
1091 threadid << "[" << getpid() << "] shibrm" << '\0';
1092 saml::NDC ndc(threadid.str().c_str());
1094 // We lock the configuration system for the duration.
1095 IConfig* conf=g_Config->getINI();
1096 Locker locker(conf);
1098 const char* application_id=ap_table_get(r->headers_in,"Shib-Application-ID");
1099 const IApplication* application=NULL;
1101 application = conf->getApplication(application_id);
1105 int m=r->method_number;
1106 bool method_restricted=false;
1109 const array_header* reqs_arr=ap_requires(r);
1113 require_line* reqs=(require_line*)reqs_arr->elts;
1115 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"REQUIRE nelts: %d", reqs_arr->nelts);
1116 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"REQUIRE all: %d", dc->bRequireAll);
1118 vector<bool> auth_OK(reqs_arr->nelts,false);
1120 #define SHIB_AP_CHECK_IS_OK { \
1121 if (dc->bRequireAll < 1) \
1123 auth_OK[x] = true; \
1127 for (int x=0; x<reqs_arr->nelts; x++) {
1129 if (!(reqs[x].method_mask & (1 << m)))
1131 method_restricted=true;
1133 t = reqs[x].requirement;
1134 w = ap_getword_white(r->pool, &t);
1136 if (!strcasecmp(w,"Shibboleth")) {
1137 // This is a dummy rule needed because Apache conflates authn and authz.
1138 // Without some require rule, AuthType is ignored and no check_user hooks run.
1139 SHIB_AP_CHECK_IS_OK;
1141 else if (!strcmp(w,"valid-user") && application_id) {
1142 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting valid-user");
1143 SHIB_AP_CHECK_IS_OK;
1145 else if (!strcmp(w,"user") && SH_AP_USER(r)) {
1148 w=ap_getword_conf(r->pool,&t);
1156 // To do regex matching, we have to convert from UTF-8.
1157 auto_ptr<XMLCh> trans(fromUTF8(w));
1158 RegularExpression re(trans.get());
1159 auto_ptr<XMLCh> trans2(fromUTF8(SH_AP_USER(r)));
1160 if (re.matches(trans2.get())) {
1161 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting user: %s",w);
1162 SHIB_AP_CHECK_IS_OK;
1165 catch (XMLException& ex) {
1166 auto_ptr_char tmp(ex.getMessage());
1167 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
1168 "shib_auth_checker caught exception while parsing regular expression (%s): %s",w,tmp.get());
1171 else if (!strcmp(SH_AP_USER(r),w)) {
1172 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting user: %s",w);
1173 SHIB_AP_CHECK_IS_OK;
1177 else if (!strcmp(w,"group")) {
1178 SH_AP_TABLE* grpstatus=NULL;
1179 if (dc->szAuthGrpFile && SH_AP_USER(r)) {
1180 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() using groups file: %s\n",dc->szAuthGrpFile);
1181 grpstatus=groups_for_user(r,SH_AP_USER(r),dc->szAuthGrpFile);
1187 w=ap_getword_conf(r->pool,&t);
1188 if (ap_table_get(grpstatus,w)) {
1189 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting group: %s",w);
1190 SHIB_AP_CHECK_IS_OK;
1195 Iterator<IAAP*> provs=application ? application->getAAPProviders() : EMPTY(IAAP*);
1196 AAP wrapper(provs,w);
1197 if (wrapper.fail()) {
1198 ap_log_rerror(APLOG_MARK,APLOG_WARNING|APLOG_NOERRNO,SH_AP_R(r),
1199 "shib_auth_checker() didn't recognize require rule: %s\n",w);
1204 const char* vals=ap_table_get(r->headers_in,wrapper->getHeader());
1205 while (*t && vals) {
1206 w=ap_getword_conf(r->pool,&t);
1213 auto_ptr<RegularExpression> re;
1215 delete re.release();
1216 auto_ptr<XMLCh> trans(fromUTF8(w));
1217 auto_ptr<RegularExpression> temp(new RegularExpression(trans.get()));
1221 string vals_str(vals);
1223 for (int i = 0; i < vals_str.length(); i++) {
1224 if (vals_str.at(i) == ';') {
1226 ap_log_rerror(APLOG_MARK,APLOG_WARNING|APLOG_NOERRNO,SH_AP_R(r),
1227 "shib_auth_checker() invalid header encoding %s: starts with semicolon", vals);
1228 return SERVER_ERROR;
1231 if (vals_str.at(i-1) == '\\') {
1232 vals_str.erase(i-1, 1);
1237 string val = vals_str.substr(j, i-j);
1240 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
1241 if (re->matches(trans.get())) {
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 else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
1248 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1249 "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
1250 SHIB_AP_CHECK_IS_OK;
1253 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1254 "shib_auth_checker() expecting %s, got %s: authorization not granted", w, val.c_str());
1259 string val = vals_str.substr(j, vals_str.length()-j);
1261 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
1262 if (re->matches(trans.get())) {
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 else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
1269 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1270 "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
1271 SHIB_AP_CHECK_IS_OK;
1274 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1275 "shib_auth_checker() expecting %s, got %s: authorization not granted", w, val.c_str());
1278 catch (XMLException& ex) {
1279 auto_ptr_char tmp(ex.getMessage());
1280 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
1281 "shib_auth_checker caught exception while parsing regular expression (%s): %s",w,tmp.get());
1287 // check if all require directives are true
1288 bool auth_all_OK = true;
1289 for (int i= 0; i<reqs_arr->nelts; i++) {
1290 auth_all_OK &= auth_OK[i];
1295 if (!method_restricted)
1298 if (!application_id) {
1299 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
1300 "shib_auth_checker: Shib-Application-ID header not found in request");
1301 return HTTP_FORBIDDEN;
1303 else if (!application) {
1304 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
1305 "shib_auth_checker: unable to map request to application settings, check configuration");
1306 return HTTP_FORBIDDEN;
1309 ShibMLP markupProcessor;
1310 markupProcessor.insert("requestURL", ap_construct_url(r->pool,r->unparsed_uri,r));
1311 return shib_error_page(r, application, "access", markupProcessor);
1315 #ifndef SHIB_APACHE_13
1318 * Empty cleanup hook, Apache 2.x doesn't check NULL very well...
1320 extern "C" apr_status_t shib_exit(void* data)
1322 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,0,NULL,"shib_exit() done\n");
1330 * Cleanup the (per-process) pool info.
1332 #ifdef SHIB_APACHE_13
1333 extern "C" void shib_child_exit(server_rec* s, SH_AP_POOL* p)
1336 extern "C" apr_status_t shib_child_exit(void* data)
1338 server_rec* s = NULL;
1341 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit(%d) dealing with g_Config..", (int)getpid());
1342 g_Config->shutdown();
1344 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit() done\n");
1346 #ifndef SHIB_APACHE_13
1352 * shire_child_init()
1353 * Things to do when the child process is initialized.
1354 * (or after the configs are read in apache-2)
1356 #ifdef SHIB_APACHE_13
1357 extern "C" void shib_child_init(server_rec* s, SH_AP_POOL* p)
1359 extern "C" void shib_child_init(apr_pool_t* p, server_rec* s)
1362 // Initialize runtime components.
1364 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init(%d) starting", (int)getpid());
1367 ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() already initialized!");
1372 g_Config=&ShibTargetConfig::getConfig();
1373 g_Config->setFeatures(
1374 ShibTargetConfig::Listener |
1375 ShibTargetConfig::Metadata |
1376 ShibTargetConfig::AAP |
1377 ShibTargetConfig::RequestMapper |
1378 ShibTargetConfig::SHIREExtensions |
1379 ShibTargetConfig::Logging
1381 if (!g_Config->init(g_szSchemaDir,g_szSHIBConfig)) {
1382 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize SHIB Target");
1387 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize SHIB Target");
1391 // Set the cleanup handler
1392 apr_pool_cleanup_register(p, NULL, &shib_exit, &shib_child_exit);
1394 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() done");
1397 typedef const char* (*config_fn_t)(void);
1399 #ifdef SHIB_APACHE_13
1401 // SHIB Module commands
1403 static command_rec shire_cmds[] = {
1404 {"SHIREConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1405 RSRC_CONF, TAKE1, "Path to shibboleth.xml config file."},
1406 {"ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1407 RSRC_CONF, TAKE1, "Path to shibboleth.xml config file."},
1408 {"ShibSchemaDir", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1409 RSRC_CONF, TAKE1, "Path to Shibboleth XML schema directory."},
1411 {"ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
1412 (void *) XtOffsetOf (shib_server_config, szScheme),
1413 RSRC_CONF, TAKE1, "URL scheme to force into generated URLs for a vhost."},
1415 {"ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1416 (void *) XtOffsetOf (shib_dir_config, bBasicHijack),
1417 OR_AUTHCFG, FLAG, "Respond to AuthType Basic and convert to shib?"},
1418 {"ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1419 (void *) XtOffsetOf (shib_dir_config, bRequireSession),
1420 OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist."},
1421 {"ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1422 (void *) XtOffsetOf (shib_dir_config, bExportAssertion),
1423 OR_AUTHCFG, FLAG, "Export SAML assertion to Shibboleth-defined header?"},
1424 {"AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
1425 (void *) XtOffsetOf (shib_dir_config, szAuthGrpFile),
1426 OR_AUTHCFG, TAKE1, "text file containing group names and member user IDs"},
1427 {"ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1428 (void *) XtOffsetOf (shib_dir_config, bRequireAll),
1429 OR_AUTHCFG, FLAG, "All require directives must match!"},
1435 handler_rec shib_handlers[] = {
1436 { "shib-shire-post", shib_post_handler },
1440 module MODULE_VAR_EXPORT mod_shib = {
1441 STANDARD_MODULE_STUFF,
1442 NULL, /* initializer */
1443 create_shib_dir_config, /* dir config creater */
1444 merge_shib_dir_config, /* dir merger --- default is to override */
1445 create_shib_server_config, /* server config */
1446 merge_shib_server_config, /* merge server config */
1447 shire_cmds, /* command table */
1448 shib_handlers, /* handlers */
1449 NULL, /* filename translation */
1450 shib_check_user, /* check_user_id */
1451 shib_auth_checker, /* check auth */
1452 NULL, /* check access */
1453 NULL, /* type_checker */
1456 NULL, /* header parser */
1457 shib_child_init, /* child_init */
1458 shib_child_exit, /* child_exit */
1459 NULL /* post read-request */
1462 #elif defined(SHIB_APACHE_20)
1464 extern "C" void shib_register_hooks (apr_pool_t *p)
1466 ap_hook_child_init(shib_child_init, NULL, NULL, APR_HOOK_MIDDLE);
1467 ap_hook_check_user_id(shib_check_user, NULL, NULL, APR_HOOK_MIDDLE);
1468 ap_hook_auth_checker(shib_auth_checker, NULL, NULL, APR_HOOK_FIRST);
1469 ap_hook_handler(shib_post_handler, NULL, NULL, APR_HOOK_LAST);
1472 // SHIB Module commands
1475 static command_rec shib_cmds[] = {
1476 AP_INIT_TAKE1("ShibConfig",
1477 (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1478 RSRC_CONF, "Path to shibboleth.xml config file."),
1479 AP_INIT_TAKE1("ShibSchemaDir",
1480 (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1481 RSRC_CONF, "Path to Shibboleth XML schema directory."),
1483 AP_INIT_TAKE1("ShibURLScheme",
1484 (config_fn_t)shib_set_server_string_slot,
1485 (void *) offsetof (shib_server_config, szScheme),
1486 RSRC_CONF, "URL scheme to force into generated URLs for a vhost."),
1488 AP_INIT_FLAG("ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1489 (void *) offsetof (shib_dir_config, bBasicHijack),
1490 OR_AUTHCFG, "Respond to AuthType Basic and convert to shib?"),
1491 AP_INIT_FLAG("ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1492 (void *) offsetof (shib_dir_config, bRequireSession),
1493 OR_AUTHCFG, "Initiates a new session if one does not exist."),
1494 AP_INIT_FLAG("ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1495 (void *) offsetof (shib_dir_config, bExportAssertion),
1496 OR_AUTHCFG, "Export SAML assertion to Shibboleth-defined header?"),
1497 AP_INIT_TAKE1("AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
1498 (void *) offsetof (shib_dir_config, szAuthGrpFile),
1499 OR_AUTHCFG, "text file containing group names and member user IDs"),
1500 AP_INIT_FLAG("ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1501 (void *) offsetof (shib_dir_config, bRequireAll),
1502 OR_AUTHCFG, "All require directives must match!"),
1507 module AP_MODULE_DECLARE_DATA mod_shib = {
1508 STANDARD20_MODULE_STUFF,
1509 create_shib_dir_config, /* create dir config */
1510 merge_shib_dir_config, /* merge dir config --- default is to override */
1511 create_shib_server_config, /* create server config */
1512 merge_shib_server_config, /* merge server config */
1513 shib_cmds, /* command table */
1514 shib_register_hooks /* register hooks */
1518 #error "undefined APACHE version"