2 * mod_apache.cpp -- the core Apache Module code
4 * Created by: Derek Atkins <derek@ihtfp.com>
10 #undef _XOPEN_SOURCE // causes gethostname conflict in unistd.h
14 #include <saml/saml.h>
15 #include <shib/shib.h>
16 #include <shib/shib-threads.h>
17 #include <shib-target/shib-target.h>
18 #include <xercesc/util/regx/RegularExpression.hpp>
22 // Apache specific header files
24 #include <http_config.h>
25 #include <http_protocol.h>
26 #include <http_main.h>
28 #include <http_core.h>
31 #ifndef SHIB_APACHE_13
32 #include <http_request.h>
33 #include <apr_strings.h>
34 #include <apr_pools.h>
41 #include <unistd.h> // for getpid()
46 using namespace shibboleth;
47 using namespace shibtarget;
49 extern "C" module MODULE_VAR_EXPORT mod_shib;
51 int shib_handler(request_rec* r, const IApplication* application, SHIRE& shire);
55 char* g_szSHIBConfig = NULL;
56 char* g_szSchemaDir = NULL;
57 ShibTargetConfig* g_Config = NULL;
58 static const char* g_UserDataKey = "_shib_check_user_";
61 /********************************************************************************/
62 // Basic Apache Configuration code.
65 // per-server module configuration structure
66 struct shib_server_config
71 // creates the per-server configuration
72 extern "C" void* create_shib_server_config(SH_AP_POOL* p, server_rec* s)
74 shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
79 // overrides server configuration in virtual servers
80 extern "C" void* merge_shib_server_config (SH_AP_POOL* p, void* base, void* sub)
82 shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
83 shib_server_config* parent=(shib_server_config*)base;
84 shib_server_config* child=(shib_server_config*)sub;
87 sc->szScheme=ap_pstrdup(p,child->szScheme);
88 else if (parent->szScheme)
89 sc->szScheme=ap_pstrdup(p,parent->szScheme);
96 // per-dir module configuration structure
97 struct shib_dir_config
100 char* szAuthGrpFile; // Auth GroupFile name
101 int bRequireAll; // all require directives must match, otherwise OR logic
103 // SHIRE Configuration
104 int bBasicHijack; // activate for AuthType Basic?
105 int bRequireSession; // require a session?
106 int bExportAssertion; // export SAML assertion to the environment?
109 // creates per-directory config structure
110 extern "C" void* create_shib_dir_config (SH_AP_POOL* p, char* d)
112 shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
113 dc->bBasicHijack = -1;
114 dc->bRequireSession = -1;
115 dc->bExportAssertion = -1;
116 dc->bRequireAll = -1;
117 dc->szAuthGrpFile = NULL;
121 // overrides server configuration in directories
122 extern "C" void* merge_shib_dir_config (SH_AP_POOL* p, void* base, void* sub)
124 shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
125 shib_dir_config* parent=(shib_dir_config*)base;
126 shib_dir_config* child=(shib_dir_config*)sub;
128 if (child->szAuthGrpFile)
129 dc->szAuthGrpFile=ap_pstrdup(p,child->szAuthGrpFile);
130 else if (parent->szAuthGrpFile)
131 dc->szAuthGrpFile=ap_pstrdup(p,parent->szAuthGrpFile);
133 dc->szAuthGrpFile=NULL;
135 dc->bBasicHijack=((child->bBasicHijack==-1) ? parent->bBasicHijack : child->bBasicHijack);
136 dc->bRequireSession=((child->bRequireSession==-1) ? parent->bRequireSession : child->bRequireSession);
137 dc->bExportAssertion=((child->bExportAssertion==-1) ? parent->bExportAssertion : child->bExportAssertion);
138 dc->bRequireAll=((child->bRequireAll==-1) ? parent->bRequireAll : child->bRequireAll);
142 // generic global slot handlers
143 extern "C" const char* ap_set_global_string_slot(cmd_parms* parms, void*, const char* arg)
145 *((char**)(parms->info))=ap_pstrdup(parms->pool,arg);
149 extern "C" const char* shib_set_server_string_slot(cmd_parms* parms, void*, const char* arg)
151 char* base=(char*)ap_get_module_config(parms->server->module_config,&mod_shib);
152 int offset=(int)parms->info;
153 *((char**)(base + offset))=ap_pstrdup(parms->pool,arg);
157 extern "C" const char* shib_ap_set_file_slot(cmd_parms* parms,
158 #ifdef SHIB_APACHE_13
159 char* arg1, char* arg2
161 void* arg1, const char* arg2
165 ap_set_file_slot(parms, arg1, arg2);
169 /********************************************************************************/
170 // Some other useful helper function(s)
172 static SH_AP_TABLE* groups_for_user(request_rec* r, const char* user, char* grpfile)
175 SH_AP_TABLE* grps=ap_make_table(r->pool,15);
176 char l[MAX_STRING_LEN];
177 const char *group_name, *ll, *w;
179 #ifdef SHIB_APACHE_13
180 if (!(f=ap_pcfg_openfile(r->pool,grpfile))) {
182 if (ap_pcfg_openfile(&f,r->pool,grpfile) != APR_SUCCESS) {
184 ap_log_rerror(APLOG_MARK,APLOG_DEBUG,SH_AP_R(r),"groups_for_user() could not open group file: %s\n",grpfile);
189 #ifdef SHIB_APACHE_13
190 sp=ap_make_sub_pool(r->pool);
192 if (apr_pool_create(&sp,r->pool) != APR_SUCCESS) {
193 ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,
194 "groups_for_user() could not create a subpool");
199 while (!(ap_cfg_getline(l,MAX_STRING_LEN,f))) {
200 if ((*l=='#') || (!*l))
205 group_name=ap_getword(sp,&ll,':');
208 w=ap_getword_conf(sp,&ll);
209 if (!strcmp(w,user)) {
210 ap_table_setn(grps,ap_pstrdup(r->pool,group_name),"in");
220 /********************************************************************************/
221 // Apache ShibTarget subclass(es) here.
223 class HTGroupTableApache : public HTGroupTable
226 HTGroupTableApache(request_rec* r, const char *user, char *grpfile) {
227 groups = groups_for_user(r, user, grpfile);
229 throw ResourceAccessException("Unable to access group file ($1) for user ($2)",params(2,grpfile,user));
231 ~HTGroupTableApache() {}
232 bool lookup(const char *entry) { return (ap_table_get(groups, entry)!=NULL); }
236 class ShibTargetApache : public ShibTarget
239 ShibTargetApache(request_rec* req) {
240 m_sc = (shib_server_config*)
241 ap_get_module_config(req->server->module_config, &mod_shib);
243 m_dc = (shib_dir_config*)ap_get_module_config(req->per_dir_config, &mod_shib);
247 m_sc->szScheme ? m_sc->szScheme : ap_http_method(req),
248 ap_get_server_name(req),
249 (int)ap_get_server_port(req),
251 ap_table_get(req->headers_in, "Content-type"),
252 req->connection->remote_ip,
258 ~ShibTargetApache() { }
260 virtual void log(ShibLogLevel level, const string &msg) {
261 ap_log_rerror(APLOG_MARK,
262 (level == LogLevelDebug ? APLOG_DEBUG :
263 (level == LogLevelInfo ? APLOG_INFO :
264 (level == LogLevelWarn ? APLOG_WARNING :
265 APLOG_ERR)))|APLOG_NOERRNO, SH_AP_R(m_req),
268 virtual string getCookies(void) const {
269 const char *c = ap_table_get(m_req->headers_in, "Cookie");
270 return string(c ? c : "");
272 virtual void setCookie(const string &name, const string &value) {
273 char* val = ap_psprintf(m_req->pool, "%s=%s", name.c_str(), value.c_str());
274 ap_table_addn(m_req->err_headers_out, "Set-Cookie", val);
276 virtual string getArgs(void) { return string(m_req->args ? m_req->args : ""); }
277 virtual string getPostData(void) {
278 // Read the posted data
279 if (ap_setup_client_block(m_req, REQUEST_CHUNKED_ERROR))
280 throw FatalProfileException("Apache function (setup_client_block) failed while reading profile submission.");
281 if (!ap_should_client_block(m_req))
282 throw FatalProfileException("Apache function (should_client_block) failed while reading profile submission.");
283 if (m_req->remaining > 1024*1024)
284 throw FatalProfileException("Blocked too-large a submission to profile endpoint.");
286 char buff[HUGE_STRING_LEN];
287 ap_hard_timeout("[mod_shib] getPostData", m_req);
288 memset(buff, 0, sizeof(buff));
289 while (ap_get_client_block(m_req, buff, sizeof(buff)-1) > 0) {
290 ap_reset_timeout(m_req);
292 memset(buff, 0, sizeof(buff));
294 ap_kill_timeout(m_req);
298 virtual void clearHeader(const string &name) {
299 ap_table_unset(m_req->headers_in, name.c_str());
301 virtual void setHeader(const string &name, const string &value) {
302 ap_table_set(m_req->headers_in, name.c_str(), value.c_str());
304 virtual string getHeader(const string &name) {
305 const char *hdr = ap_table_get(m_req->headers_in, name.c_str());
306 return string(hdr ? hdr : "");
308 virtual void setRemoteUser(const string &user) {
309 SH_AP_USER(m_req) = ap_pstrdup(m_req->pool, user.c_str());
311 virtual string getRemoteUser(void) {
312 return string(SH_AP_USER(m_req) ? SH_AP_USER(m_req) : "");
314 // override so we can look at the actual auth type and maybe override it.
315 virtual string getAuthType(void) {
316 const char *auth_type=ap_auth_type(m_req);
319 if (strcasecmp(auth_type, "shibboleth")) {
320 if (!strcasecmp(auth_type, "basic") && m_dc->bBasicHijack == 1) {
321 core_dir_config* conf= (core_dir_config*)ap_get_module_config(m_req->per_dir_config,
322 ap_find_linked_module("http_core.c"));
323 auth_type = conf->ap_auth_type = "shibboleth";
326 return string(auth_type);
328 // Override this function because we want to add the Apache Directory override
329 virtual pair<bool,bool> getRequireSession(IRequestMapper::Settings &settings) {
330 pair<bool,bool> requireSession = settings.first->getBool("requireSession");
331 if (!requireSession.first || !requireSession.second)
332 if (m_dc->bRequireSession == 1)
333 requireSession.second=true;
335 return requireSession;
338 virtual HTAccessInfo* getAccessInfo(void) {
339 int m = m_req->method_number;
340 const array_header* reqs_arr = ap_requires(m_req);
344 require_line* reqs = (require_line*) reqs_arr->elts;
346 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req),
347 "REQUIRE nelts: %d", reqs_arr->nelts);
348 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req),
349 "REQUIRE all: %d", m_dc->bRequireAll);
351 HTAccessInfo* ht = new HTAccessInfo();
352 ht->requireAll = (m_dc->bRequireAll == 1);
353 ht->elements.reserve(reqs_arr->nelts);
354 for (int x = 0; x < reqs_arr->nelts; x++) {
355 HTAccessInfo::RequireLine* rline = new HTAccessInfo::RequireLine();
356 rline->use_line = (reqs[x].method_mask & (1 << m));
357 rline->tokens.reserve(6); // No reason to reserve specifically 6 tokens
358 const char* t = reqs[x].requirement;
359 const char* w = ap_getword_white(m_req->pool, &t);
360 rline->tokens.push_back(w);
362 w = ap_getword_conf(m_req->pool, &t);
363 rline->tokens.push_back(w);
365 ht->elements.push_back(rline);
369 virtual HTGroupTable* getGroupTable(string& user) {
370 if (m_dc->szAuthGrpFile && !user.empty()) {
371 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req),
372 "getGroupTable() using groups file: %s\n",
373 m_dc->szAuthGrpFile);
375 HTGroupTableApache *gt = new HTGroupTableApache(m_req, user.c_str(),
376 m_dc->szAuthGrpFile);
383 virtual void* sendPage(
386 const string& content_type="text/html",
387 const Iterator<header_t>& headers=EMPTY(header_t)
389 m_req->content_type = ap_psprintf(m_req->pool, content_type.c_str());
390 while (headers.hasNext()) {
391 const header_t& h=headers.next();
392 ap_table_setn(m_req->headers_out, h.first.c_str(), h.second.c_str());
394 ap_send_http_header(m_req);
395 ap_rprintf(m_req, msg.c_str());
396 return (void*)((code==200) ? DONE : code);
398 virtual void* sendRedirect(const string& url) {
399 ap_table_set(m_req->headers_out, "Location", url.c_str());
400 return (void*)REDIRECT;
402 virtual void* returnDecline(void) { return (void*)DECLINED; }
403 virtual void* returnOK(void) { return (void*)OK; }
406 shib_dir_config* m_dc;
407 shib_server_config* m_sc;
410 /********************************************************************************/
413 extern "C" int shib_check_user(request_rec* r)
415 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_check_user(%d): ENTER\n", (int)getpid());
417 ostringstream threadid;
418 threadid << "[" << getpid() << "] shib_check_user" << '\0';
419 saml::NDC ndc(threadid.str().c_str());
424 ShibTargetApache sta(r);
426 // Check user authentication, the set the handler bypass
427 pair<bool,void*> res = sta.doCheckAuthN((sta.m_dc->bRequireSession == 1), true);
428 apr_pool_userdata_setn((const void*)42,g_UserDataKey,NULL,r->pool);
429 if (res.first) return (int)res.second;
431 // user auth was okay -- export the assertions now
432 res = sta.doExportAssertions((sta.m_dc->bExportAssertion == 1));
433 if (res.first) return (int)res.second;
435 // export happened successfully.. this user is ok.
440 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user threw an uncaught exception!");
446 extern "C" int shib_handler(request_rec* r)
448 ostringstream threadid;
449 threadid << "[" << getpid() << "] shib_handler" << '\0';
450 saml::NDC ndc(threadid.str().c_str());
452 #ifndef SHIB_APACHE_13
453 // With 2.x, this handler always runs, though last.
454 // We check if shib_check_user ran, because it will detect a handler request
455 // and dispatch it directly.
457 apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
458 if (data==(const void*)42) {
459 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler skipped since check_user ran");
464 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler(%d): ENTER", (int)getpid());
469 ShibTargetApache sta(r);
471 pair<bool,void*> res = sta.doHandler();
472 if (res.first) return (int)res.second;
474 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "doHandler() did not do anything.");
479 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler threw an uncaught exception!");
486 * shib_auth_checker() -- a simple resource manager to
487 * process the .htaccess settings
489 extern "C" int shib_auth_checker(request_rec* r)
491 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_auth_checker(%d): ENTER", (int)getpid());
493 ostringstream threadid;
494 threadid << "[" << getpid() << "] shib_auth_checker" << '\0';
495 saml::NDC ndc(threadid.str().c_str());
500 ShibTargetApache sta(r);
502 pair<bool,void*> res = sta.doCheckAuthZ();
503 if (res.first) return (int)res.second;
510 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an uncaught exception!");
517 static char* shib_get_targeturl(request_rec* r, const char* scheme=NULL)
519 // On 1.3, this is always canonical, but on 2.0, UseCanonicalName comes into play.
520 // However, we also have a setting to forcibly replace the scheme for esoteric cases.
522 unsigned port = ap_get_server_port(r);
523 if ((!strcmp(scheme,"http") && port==80) || (!strcmp(scheme,"https") && port==443)) {
524 return ap_pstrcat(r->pool, scheme, "://", ap_get_server_name(r), r->unparsed_uri, NULL);
526 return ap_psprintf(r->pool, "%s://%s:%u%s", scheme, ap_get_server_name(r), port, r->unparsed_uri);
528 return ap_construct_url(r->pool,r->unparsed_uri,r);
531 extern "C" int shib_check_user(request_rec* r)
533 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: ENTER");
534 shib_dir_config* dc=(shib_dir_config*)ap_get_module_config(r->per_dir_config,&mod_shib);
535 shib_server_config* sc=(shib_server_config*)ap_get_module_config(r->server->module_config,&mod_shib);
537 ostringstream threadid;
538 threadid << "[" << getpid() << "] shib_check_user" << '\0';
539 saml::NDC ndc(threadid.str().c_str());
541 const char* targeturl=shib_get_targeturl(r,sc->szScheme);
543 // We lock the configuration system for the duration.
544 IConfig* conf=g_Config->getINI();
547 // Map request to application and content settings.
548 IRequestMapper* mapper=conf->getRequestMapper();
549 Locker locker2(mapper);
550 IRequestMapper::Settings settings=mapper->getSettingsFromParsedURL(
551 (sc-> szScheme ? sc-> szScheme : ap_http_method(r)), ap_get_server_name(r), ap_get_server_port(r), r->unparsed_uri
553 pair<bool,const char*> application_id=settings.first->getString("applicationId");
554 const IApplication* application=conf->getApplication(application_id.second);
556 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
557 "shib_check_user: unable to map request to application settings, check configuration");
561 // Declare SHIRE object for this request.
562 SHIRE shire(application);
564 const char* shireURL=shire.getShireURL(targeturl);
566 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
567 "shib_check_user: unable to map request to proper shireURL setting, check configuration");
571 // Get location of this application's assertion consumer service and see if this is it.
572 if (strstr(targeturl,shireURL)) {
573 return shib_handler(r,application,shire);
576 // We can short circuit the handler if we run this...
577 apr_pool_userdata_setn((const void*)42,g_UserDataKey,NULL,r->pool);
579 // Regular access to arbitrary resource...check AuthType
580 const char *auth_type=ap_auth_type(r);
584 if (strcasecmp(auth_type,"shibboleth")) {
585 if (!strcasecmp(auth_type,"basic") && dc->bBasicHijack==1) {
586 core_dir_config* conf=
587 (core_dir_config*)ap_get_module_config(r->per_dir_config,
588 ap_find_linked_module("http_core.c"));
589 conf->ap_auth_type="shibboleth";
595 pair<bool,bool> requireSession = settings.first->getBool("requireSession");
596 if (!requireSession.first || !requireSession.second)
597 if (dc->bRequireSession==1)
598 requireSession.second=true;
600 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: session check for %s",targeturl);
602 pair<const char*,const char*> shib_cookie=shire.getCookieNameProps(); // always returns *something*
604 // We're in charge, so check for cookie.
605 const char* session_id=NULL;
606 const char* cookies=ap_table_get(r->headers_in,"Cookie");
609 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: cookies found: %s",cookies);
610 if (session_id=strstr(cookies,shib_cookie.first)) {
611 // Yep, we found a cookie -- pull it out (our session_id)
612 session_id+=strlen(shib_cookie.first) + 1; /* Skip over the '=' */
613 char* cookiebuf = ap_pstrdup(r->pool,session_id);
614 char* cookieend = strchr(cookiebuf,';');
616 *cookieend = '\0'; /* Ignore anyting after a ; */
617 session_id=cookiebuf;
621 if (!session_id || !*session_id) {
622 // If no session required, bail now.
623 if (!requireSession.second)
626 // No acceptable cookie, and we require a session. Generate an AuthnRequest.
627 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: no cookie found -- redirecting to WAYF");
628 ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(targeturl)));
632 // Make sure this session is still valid.
633 RPCError* status = NULL;
634 ShibMLP markupProcessor;
635 markupProcessor.insert("requestURL", targeturl);
638 status = shire.sessionIsValid(session_id, r->connection->remote_ip);
640 catch (ShibTargetException &e) {
641 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): %s", e.what());
642 markupProcessor.insert("errorType", "Session Processing Error");
643 markupProcessor.insert("errorText", e.what());
644 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
645 return shib_error_page(r, application, "shire", markupProcessor);
649 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): caught unexpected error");
650 markupProcessor.insert("errorType", "Session Processing Error");
651 markupProcessor.insert("errorText", "Unexpected Exception");
652 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
653 return shib_error_page(r, application, "shire", markupProcessor);
658 if (status->isError()) {
659 ap_log_rerror(APLOG_MARK,APLOG_INFO|APLOG_NOERRNO,SH_AP_R(r),
660 "shib_check_user() session invalid: %s", status->getText());
662 // If no session required, bail now.
663 if (!requireSession.second)
664 return OK; // XXX: Or should this be DECLINED?
665 // Has to be OK because DECLINED will just cause Apache to fail when it can't locate
666 // anything to process the AuthType. No session plus requireSession false means
667 // do not authenticate the user.
668 else if (status->isRetryable()) {
669 // Oops, session is invalid. Generate AuthnRequest.
670 ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(targeturl)));
675 // return the error page to the user
676 markupProcessor.insert(*status);
678 return shib_error_page(r, application, "shire", markupProcessor);
684 #ifdef SHIB_APACHE_13
686 r->connection->ap_auth_type = "shibboleth";
688 r->ap_auth_type = "shibboleth";
690 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: session successfully verified");
692 // This is code transferred in from the auth check to export the attributes.
693 // We could even combine the isSessionValid/getAssertions API...?
696 vector<SAMLAssertion*> assertions;
697 SAMLAuthenticationStatement* sso_statement=NULL;
700 status = rm.getAssertions(session_id, r->connection->remote_ip, assertions, &sso_statement);
702 catch (ShibTargetException &e) {
703 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): %s", e.what());
704 markupProcessor.insert("errorType", "Attribute Processing Error");
705 markupProcessor.insert("errorText", e.what());
706 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
707 return shib_error_page(r, application, "rm", markupProcessor);
711 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): caught unexpected error");
712 markupProcessor.insert("errorType", "Attribute Processing Error");
713 markupProcessor.insert("errorText", "Unexpected Exception");
714 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
715 return shib_error_page(r, application, "rm", markupProcessor);
719 if (status->isError()) {
720 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
721 "shib_check_user() getAssertions failed: %s", status->getText());
723 markupProcessor.insert(*status);
725 return shib_error_page(r, application, "rm", markupProcessor);
729 // Do we have an access control plugin?
730 if (settings.second) {
731 Locker acllock(settings.second);
732 if (!settings.second->authorized(*sso_statement,assertions)) {
733 for (int k = 0; k < assertions.size(); k++)
734 delete assertions[k];
735 delete sso_statement;
736 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): access control provider denied access");
737 return shib_error_page(r, application, "access", markupProcessor);
741 // Get the AAP providers, which contain the attribute policy info.
742 Iterator<IAAP*> provs=application->getAAPProviders();
744 // Clear out the list of mapped attributes
745 while (provs.hasNext()) {
746 IAAP* aap=provs.next();
749 Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
750 while (rules.hasNext()) {
751 const char* header=rules.next()->getHeader();
753 ap_table_unset(r->headers_in,header);
758 for (int k = 0; k < assertions.size(); k++)
759 delete assertions[k];
760 delete sso_statement;
761 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
762 "shib_check_user(): caught unexpected error while clearing headers");
763 markupProcessor.insert("errorType", "Attribute Processing Error");
764 markupProcessor.insert("errorText", "Unexpected Exception");
765 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
766 return shib_error_page(r, application, "rm", markupProcessor);
772 // Maybe export the first assertion.
773 ap_table_unset(r->headers_in,"Shib-Attributes");
774 pair<bool,bool> exp=settings.first->getBool("exportAssertion");
775 if (!exp.first || !exp.second)
776 if (dc->bExportAssertion==1)
778 if (exp.second && assertions.size()) {
780 RM::serialize(*(assertions[0]), assertion);
781 ap_table_set(r->headers_in,"Shib-Attributes", assertion.c_str());
784 // Export the SAML AuthnMethod and the origin site name, and possibly the NameIdentifier.
785 ap_table_unset(r->headers_in,"Shib-Origin-Site");
786 ap_table_unset(r->headers_in,"Shib-Authentication-Method");
787 ap_table_unset(r->headers_in,"Shib-NameIdentifier-Format");
788 auto_ptr_char os(sso_statement->getSubject()->getNameIdentifier()->getNameQualifier());
789 auto_ptr_char am(sso_statement->getAuthMethod());
790 ap_table_set(r->headers_in,"Shib-Origin-Site", os.get());
791 ap_table_set(r->headers_in,"Shib-Authentication-Method", am.get());
794 AAP wrapper(provs,sso_statement->getSubject()->getNameIdentifier()->getFormat(),Constants::SHIB_ATTRIBUTE_NAMESPACE_URI);
795 if (!wrapper.fail() && wrapper->getHeader()) {
796 auto_ptr_char form(sso_statement->getSubject()->getNameIdentifier()->getFormat());
797 auto_ptr_char nameid(sso_statement->getSubject()->getNameIdentifier()->getName());
798 ap_table_set(r->headers_in,"Shib-NameIdentifier-Format",form.get());
799 if (!strcmp(wrapper->getHeader(),"REMOTE_USER"))
800 SH_AP_USER(r)=ap_pstrdup(r->pool,nameid.get());
802 ap_table_set(r->headers_in,wrapper->getHeader(),nameid.get());
805 ap_table_unset(r->headers_in,"Shib-Application-ID");
806 ap_table_set(r->headers_in,"Shib-Application-ID",application_id.second);
808 // Export the attributes.
809 Iterator<SAMLAssertion*> a_iter(assertions);
810 while (a_iter.hasNext()) {
811 SAMLAssertion* assert=a_iter.next();
812 Iterator<SAMLStatement*> statements=assert->getStatements();
813 while (statements.hasNext()) {
814 SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());
817 Iterator<SAMLAttribute*> attrs=astate->getAttributes();
818 while (attrs.hasNext()) {
819 SAMLAttribute* attr=attrs.next();
821 // Are we supposed to export it?
822 AAP wrapper(provs,attr->getName(),attr->getNamespace());
823 if (wrapper.fail() || !wrapper->getHeader())
826 Iterator<string> vals=attr->getSingleByteValues();
827 if (!strcmp(wrapper->getHeader(),"REMOTE_USER") && vals.hasNext())
828 SH_AP_USER(r)=ap_pstrdup(r->pool,vals.next().c_str());
831 char* header = (char*)ap_table_get(r->headers_in, wrapper->getHeader());
833 header=ap_pstrdup(r->pool, header);
837 header = ap_pstrdup(r->pool, "");
838 for (; vals.hasNext(); it++) {
839 string value = vals.next();
840 for (string::size_type pos = value.find_first_of(";", string::size_type(0));
842 pos = value.find_first_of(";", pos)) {
843 value.insert(pos, "\\");
846 header=ap_pstrcat(r->pool, header, (it ? ";" : ""), value.c_str(), NULL);
848 ap_table_setn(r->headers_in, wrapper->getHeader(), header);
855 for (int k = 0; k < assertions.size(); k++)
856 delete assertions[k];
857 delete sso_statement;
862 extern "C" int shib_post_handler(request_rec* r)
864 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
865 "shib_post_handler(%d): ENTER", (int)getpid());
866 shib_server_config* sc=(shib_server_config*)ap_get_module_config(r->server->module_config,&mod_shib);
868 #ifndef SHIB_APACHE_13
869 // With 2.x, this handler always runs, though last.
870 // We check if shib_check_user ran, because it will detect a SHIRE request
871 // and dispatch it directly.
873 apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
874 if (data==(const void*)42) {
875 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_post_handler skipped since check_user ran");
880 ostringstream threadid;
881 threadid << "[" << getpid() << "] shib_post_handler" << '\0';
882 saml::NDC ndc(threadid.str().c_str());
884 // We lock the configuration system for the duration.
885 IConfig* conf=g_Config->getINI();
888 // Map request to application and content settings.
889 IRequestMapper* mapper=conf->getRequestMapper();
890 Locker locker2(mapper);
891 IRequestMapper::Settings settings=mapper->getSettingsFromParsedURL(
892 (sc->szScheme ? sc->szScheme : ap_http_method(r)), ap_get_server_name(r), ap_get_server_port(r), r->unparsed_uri
894 pair<bool,const char*> application_id=settings.first->getString("applicationId");
895 const IApplication* application=conf->getApplication(application_id.second);
897 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
898 "shib_post_handler: unable to map request to application settings, check configuration");
902 // Declare SHIRE object for this request.
903 SHIRE shire(application);
905 return shib_handler(r, application, shire);
908 int shib_handler(request_rec* r, const IApplication* application, SHIRE& shire)
910 shib_server_config* sc=(shib_server_config*)ap_get_module_config(r->server->module_config,&mod_shib);
912 const char* targeturl=shib_get_targeturl(r,sc->szScheme);
914 const char* shireURL=shire.getShireURL(targeturl);
916 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
917 "shib_post_handler: unable to map request to proper shireURL setting, check configuration");
921 // Make sure we only process the SHIRE requests.
922 if (!strstr(targeturl,shireURL))
925 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler() running");
927 const IPropertySet* sessionProps=application->getPropertySet("Sessions");
929 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
930 "shib_post_handler: unable to map request to application session settings, check configuration");
934 pair<const char*,const char*> shib_cookie=shire.getCookieNameProps(); // always returns something
936 ShibMLP markupProcessor;
937 markupProcessor.insert("requestURL", targeturl);
939 // Process SHIRE request
940 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() Beginning SHIRE processing");
943 pair<bool,bool> shireSSL=sessionProps->getBool("shireSSL");
945 // Make sure this is SSL, if it should be
946 if ((!shireSSL.first || shireSSL.second) && strcmp(ap_http_method(r),"https"))
947 throw ShibTargetException(SHIBRPC_OK, "blocked non-SSL access to session creation service");
949 // If this is a GET, we manufacture an AuthnRequest.
950 if (!strcasecmp(r->method,"GET")) {
951 const char* areq=r->args ? shire.getLazyAuthnRequest(r->args) : NULL;
953 throw ShibTargetException(SHIBRPC_OK, "malformed arguments to request a new session");
954 ap_table_setn(r->headers_out, "Location", ap_pstrdup(r->pool,areq));
957 else if (strcasecmp(r->method,"POST")) {
958 throw ShibTargetException(SHIBRPC_OK, "blocked non-POST to SHIRE POST processor");
961 // Sure sure this POST is an appropriate content type
962 const char *ct = ap_table_get(r->headers_in, "Content-type");
963 if (!ct || strcasecmp(ct, "application/x-www-form-urlencoded"))
964 throw ShibTargetException(SHIBRPC_OK,
965 ap_psprintf(r->pool, "blocked bad content-type to SHIRE POST processor: %s", (ct ? ct : "")));
967 // Read the posted data
968 if (ap_setup_client_block(r, REQUEST_CHUNKED_ERROR))
969 throw ShibTargetException(SHIBRPC_OK, "CGI setup_client_block failed");
970 if (!ap_should_client_block(r))
971 throw ShibTargetException(SHIBRPC_OK, "CGI should_client_block failed");
972 if (r->remaining > 1024*1024)
973 throw ShibTargetException (SHIBRPC_OK, "CGI length too long...");
976 char buff[HUGE_STRING_LEN];
977 ap_hard_timeout("[mod_shib] CGI Parser", r);
978 memset(buff, 0, sizeof(buff));
979 while (ap_get_client_block(r, buff, sizeof(buff)-1) > 0) {
982 memset(buff, 0, sizeof(buff));
986 // Parse the submission.
987 pair<const char*,const char*> elements=shire.getFormSubmission(cgistr.c_str(),cgistr.length());
989 // Make sure the SAML Response parameter exists
990 if (!elements.first || !*elements.first)
991 throw ShibTargetException(SHIBRPC_OK, "SHIRE POST failed to find SAMLResponse form element");
993 // Make sure the target parameter exists
994 if (!elements.second || !*elements.second)
995 throw ShibTargetException(SHIBRPC_OK, "SHIRE POST failed to find TARGET form element");
997 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
998 "shib_handler() Processing POST for target: %s", elements.second);
1002 RPCError* status = shire.sessionCreate(elements.first, r->connection->remote_ip, cookie);
1004 if (status->isError()) {
1005 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
1006 "shib_handler() POST process failed (%d): %s", status->getCode(), status->getText());
1008 if (status->isRetryable()) {
1010 ap_log_rerror(APLOG_MARK,APLOG_INFO|APLOG_NOERRNO,SH_AP_R(r),
1011 "shib_handler() retryable error, generating new AuthnRequest");
1012 ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(elements.second)));
1016 // return this error to the user.
1017 markupProcessor.insert(*status);
1019 return shib_error_page(r, application, "shire", markupProcessor);
1023 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1024 "shib_handler() POST process succeeded. New session: %s", cookie.c_str());
1026 // We've got a good session, set the cookie...
1027 char* val = ap_psprintf(r->pool,"%s=%s%s",shib_cookie.first,cookie.c_str(),shib_cookie.second);
1028 ap_table_setn(r->err_headers_out, "Set-Cookie", val);
1029 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() setting cookie: %s", val);
1031 // ... and redirect to the target
1032 ap_table_setn(r->headers_out, "Location", ap_pstrdup(r->pool,elements.second));
1035 catch (ShibTargetException &e) {
1036 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() caught exception: %s", e.what());
1037 markupProcessor.insert("errorType", "Session Creation Service Error");
1038 markupProcessor.insert("errorText", e.what());
1039 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
1040 return shib_error_page(r, application, "shire", markupProcessor);
1044 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler(): unexpected exception");
1045 markupProcessor.insert("errorType", "Session Creation Service Error");
1046 markupProcessor.insert("errorText", "Unknown Exception");
1047 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
1048 return shib_error_page(r, application, "shire", markupProcessor);
1052 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_handler() server error");
1053 return SERVER_ERROR;
1056 static int shib_error_page(request_rec* r, const IApplication* app, const char* page, ShibMLP& mlp)
1058 const IPropertySet* props=app->getPropertySet("Errors");
1060 pair<bool,const char*> p=props->getString(page);
1062 ifstream infile(p.second);
1063 if (!infile.fail()) {
1064 const char* res = mlp.run(infile,props);
1066 r->content_type = ap_psprintf(r->pool, "text/html");
1067 ap_send_http_header(r);
1075 ap_log_rerror(APLOG_MARK,APLOG_ERR,SH_AP_R(r),
1076 "shib_error_page() could not process shire error template for application %s",app->getId());
1077 return SERVER_ERROR;
1081 * shib_auth_checker() -- a simple resource manager to
1082 * process the .htaccess settings and copy attributes
1083 * into the HTTP headers.
1085 extern "C" int shib_auth_checker(request_rec* r)
1087 shib_dir_config* dc=
1088 (shib_dir_config*)ap_get_module_config(r->per_dir_config,&mod_shib);
1090 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() executing");
1092 // Regular access to arbitrary resource...check AuthType
1093 const char* auth_type=ap_auth_type(r);
1094 if (!auth_type || strcasecmp(auth_type,"shibboleth"))
1097 ostringstream threadid;
1098 threadid << "[" << getpid() << "] shibrm" << '\0';
1099 saml::NDC ndc(threadid.str().c_str());
1101 // We lock the configuration system for the duration.
1102 IConfig* conf=g_Config->getINI();
1103 Locker locker(conf);
1105 const char* application_id=ap_table_get(r->headers_in,"Shib-Application-ID");
1106 const IApplication* application=NULL;
1108 application = conf->getApplication(application_id);
1112 int m=r->method_number;
1113 bool method_restricted=false;
1116 const array_header* reqs_arr=ap_requires(r);
1120 require_line* reqs=(require_line*)reqs_arr->elts;
1122 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"REQUIRE nelts: %d", reqs_arr->nelts);
1123 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"REQUIRE all: %d", dc->bRequireAll);
1125 vector<bool> auth_OK(reqs_arr->nelts,false);
1127 #define SHIB_AP_CHECK_IS_OK { \
1128 if (dc->bRequireAll < 1) \
1130 auth_OK[x] = true; \
1134 for (int x=0; x<reqs_arr->nelts; x++) {
1136 if (!(reqs[x].method_mask & (1 << m)))
1138 method_restricted=true;
1140 t = reqs[x].requirement;
1141 w = ap_getword_white(r->pool, &t);
1143 if (!strcasecmp(w,"Shibboleth")) {
1144 // This is a dummy rule needed because Apache conflates authn and authz.
1145 // Without some require rule, AuthType is ignored and no check_user hooks run.
1146 SHIB_AP_CHECK_IS_OK;
1148 else if (!strcmp(w,"valid-user") && application_id) {
1149 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting valid-user");
1150 SHIB_AP_CHECK_IS_OK;
1152 else if (!strcmp(w,"user") && SH_AP_USER(r)) {
1155 w=ap_getword_conf(r->pool,&t);
1163 // To do regex matching, we have to convert from UTF-8.
1164 auto_ptr<XMLCh> trans(fromUTF8(w));
1165 RegularExpression re(trans.get());
1166 auto_ptr<XMLCh> trans2(fromUTF8(SH_AP_USER(r)));
1167 if (re.matches(trans2.get())) {
1168 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting user: %s",w);
1169 SHIB_AP_CHECK_IS_OK;
1172 catch (XMLException& ex) {
1173 auto_ptr_char tmp(ex.getMessage());
1174 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
1175 "shib_auth_checker caught exception while parsing regular expression (%s): %s",w,tmp.get());
1178 else if (!strcmp(SH_AP_USER(r),w)) {
1179 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting user: %s",w);
1180 SHIB_AP_CHECK_IS_OK;
1184 else if (!strcmp(w,"group")) {
1185 SH_AP_TABLE* grpstatus=NULL;
1186 if (dc->szAuthGrpFile && SH_AP_USER(r)) {
1187 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() using groups file: %s\n",dc->szAuthGrpFile);
1188 grpstatus=groups_for_user(r,SH_AP_USER(r),dc->szAuthGrpFile);
1194 w=ap_getword_conf(r->pool,&t);
1195 if (ap_table_get(grpstatus,w)) {
1196 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting group: %s",w);
1197 SHIB_AP_CHECK_IS_OK;
1202 Iterator<IAAP*> provs=application ? application->getAAPProviders() : EMPTY(IAAP*);
1203 AAP wrapper(provs,w);
1204 if (wrapper.fail()) {
1205 ap_log_rerror(APLOG_MARK,APLOG_WARNING|APLOG_NOERRNO,SH_AP_R(r),
1206 "shib_auth_checker() didn't recognize require rule: %s\n",w);
1211 const char* vals=ap_table_get(r->headers_in,wrapper->getHeader());
1212 while (*t && vals) {
1213 w=ap_getword_conf(r->pool,&t);
1220 auto_ptr<RegularExpression> re;
1222 delete re.release();
1223 auto_ptr<XMLCh> trans(fromUTF8(w));
1224 auto_ptr<RegularExpression> temp(new RegularExpression(trans.get()));
1228 string vals_str(vals);
1230 for (int i = 0; i < vals_str.length(); i++) {
1231 if (vals_str.at(i) == ';') {
1233 ap_log_rerror(APLOG_MARK,APLOG_WARNING|APLOG_NOERRNO,SH_AP_R(r),
1234 "shib_auth_checker() invalid header encoding %s: starts with semicolon", vals);
1235 return SERVER_ERROR;
1238 if (vals_str.at(i-1) == '\\') {
1239 vals_str.erase(i-1, 1);
1244 string val = vals_str.substr(j, i-j);
1247 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
1248 if (re->matches(trans.get())) {
1249 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1250 "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
1251 SHIB_AP_CHECK_IS_OK;
1254 else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
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 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1261 "shib_auth_checker() expecting %s, got %s: authorization not granted", w, val.c_str());
1266 string val = vals_str.substr(j, vals_str.length()-j);
1268 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
1269 if (re->matches(trans.get())) {
1270 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1271 "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
1272 SHIB_AP_CHECK_IS_OK;
1275 else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
1276 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1277 "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
1278 SHIB_AP_CHECK_IS_OK;
1281 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1282 "shib_auth_checker() expecting %s, got %s: authorization not granted", w, val.c_str());
1285 catch (XMLException& ex) {
1286 auto_ptr_char tmp(ex.getMessage());
1287 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
1288 "shib_auth_checker caught exception while parsing regular expression (%s): %s",w,tmp.get());
1294 // check if all require directives are true
1295 bool auth_all_OK = true;
1296 for (int i= 0; i<reqs_arr->nelts; i++) {
1297 auth_all_OK &= auth_OK[i];
1302 if (!method_restricted)
1305 if (!application_id) {
1306 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
1307 "shib_auth_checker: Shib-Application-ID header not found in request");
1308 return HTTP_FORBIDDEN;
1310 else if (!application) {
1311 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
1312 "shib_auth_checker: unable to map request to application settings, check configuration");
1313 return HTTP_FORBIDDEN;
1316 ShibMLP markupProcessor;
1317 markupProcessor.insert("requestURL", ap_construct_url(r->pool,r->unparsed_uri,r));
1318 return shib_error_page(r, application, "access", markupProcessor);
1322 #ifndef SHIB_APACHE_13
1325 * Empty cleanup hook, Apache 2.x doesn't check NULL very well...
1327 extern "C" apr_status_t shib_exit(void* data)
1330 g_Config->shutdown();
1333 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,0,NULL,"shib_exit() done\n");
1341 * Cleanup the (per-process) pool info.
1343 #ifdef SHIB_APACHE_13
1344 extern "C" void shib_child_exit(server_rec* s, SH_AP_POOL* p)
1347 extern "C" apr_status_t shib_child_exit(void* data)
1349 server_rec* s = NULL;
1352 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit(%d) dealing with g_Config..", (int)getpid());
1353 g_Config->shutdown();
1355 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit() done\n");
1357 #ifndef SHIB_APACHE_13
1363 * shire_child_init()
1364 * Things to do when the child process is initialized.
1365 * (or after the configs are read in apache-2)
1367 #ifdef SHIB_APACHE_13
1368 extern "C" void shib_child_init(server_rec* s, SH_AP_POOL* p)
1370 extern "C" void shib_child_init(apr_pool_t* p, server_rec* s)
1373 // Initialize runtime components.
1375 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init(%d) starting", (int)getpid());
1378 ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() already initialized!");
1383 g_Config=&ShibTargetConfig::getConfig();
1384 g_Config->setFeatures(
1385 ShibTargetConfig::Listener |
1386 ShibTargetConfig::Metadata |
1387 ShibTargetConfig::AAP |
1388 ShibTargetConfig::RequestMapper |
1389 ShibTargetConfig::LocalExtensions |
1390 ShibTargetConfig::Logging
1392 if (!g_Config->init(g_szSchemaDir,g_szSHIBConfig)) {
1393 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize SHIB Target");
1398 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize SHIB Target");
1402 // Set the cleanup handler
1403 apr_pool_cleanup_register(p, NULL, &shib_exit, &shib_child_exit);
1405 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() done");
1408 typedef const char* (*config_fn_t)(void);
1410 #ifdef SHIB_APACHE_13
1412 // SHIB Module commands
1414 static command_rec shire_cmds[] = {
1415 {"SHIREConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1416 RSRC_CONF, TAKE1, "Path to shibboleth.xml config file."},
1417 {"ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1418 RSRC_CONF, TAKE1, "Path to shibboleth.xml config file."},
1419 {"ShibSchemaDir", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1420 RSRC_CONF, TAKE1, "Path to Shibboleth XML schema directory."},
1422 {"ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
1423 (void *) XtOffsetOf (shib_server_config, szScheme),
1424 RSRC_CONF, TAKE1, "URL scheme to force into generated URLs for a vhost."},
1426 {"ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1427 (void *) XtOffsetOf (shib_dir_config, bBasicHijack),
1428 OR_AUTHCFG, FLAG, "Respond to AuthType Basic and convert to shib?"},
1429 {"ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1430 (void *) XtOffsetOf (shib_dir_config, bRequireSession),
1431 OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist."},
1432 {"ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1433 (void *) XtOffsetOf (shib_dir_config, bExportAssertion),
1434 OR_AUTHCFG, FLAG, "Export SAML assertion to Shibboleth-defined header?"},
1435 {"AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
1436 (void *) XtOffsetOf (shib_dir_config, szAuthGrpFile),
1437 OR_AUTHCFG, TAKE1, "text file containing group names and member user IDs"},
1438 {"ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1439 (void *) XtOffsetOf (shib_dir_config, bRequireAll),
1440 OR_AUTHCFG, FLAG, "All require directives must match!"},
1446 handler_rec shib_handlers[] = {
1447 { "shib-handler", shib_handler },
1451 module MODULE_VAR_EXPORT mod_shib = {
1452 STANDARD_MODULE_STUFF,
1453 NULL, /* initializer */
1454 create_shib_dir_config, /* dir config creater */
1455 merge_shib_dir_config, /* dir merger --- default is to override */
1456 create_shib_server_config, /* server config */
1457 merge_shib_server_config, /* merge server config */
1458 shire_cmds, /* command table */
1459 shib_handlers, /* handlers */
1460 NULL, /* filename translation */
1461 shib_check_user, /* check_user_id */
1462 shib_auth_checker, /* check auth */
1463 NULL, /* check access */
1464 NULL, /* type_checker */
1467 NULL, /* header parser */
1468 shib_child_init, /* child_init */
1469 shib_child_exit, /* child_exit */
1470 NULL /* post read-request */
1473 #elif defined(SHIB_APACHE_20)
1475 extern "C" void shib_register_hooks (apr_pool_t *p)
1477 ap_hook_child_init(shib_child_init, NULL, NULL, APR_HOOK_MIDDLE);
1478 ap_hook_check_user_id(shib_check_user, NULL, NULL, APR_HOOK_MIDDLE);
1479 ap_hook_auth_checker(shib_auth_checker, NULL, NULL, APR_HOOK_FIRST);
1480 ap_hook_handler(shib_handler, NULL, NULL, APR_HOOK_LAST);
1483 // SHIB Module commands
1486 static command_rec shib_cmds[] = {
1487 AP_INIT_TAKE1("ShibConfig",
1488 (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1489 RSRC_CONF, "Path to shibboleth.xml config file."),
1490 AP_INIT_TAKE1("ShibSchemaDir",
1491 (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1492 RSRC_CONF, "Path to Shibboleth XML schema directory."),
1494 AP_INIT_TAKE1("ShibURLScheme",
1495 (config_fn_t)shib_set_server_string_slot,
1496 (void *) offsetof (shib_server_config, szScheme),
1497 RSRC_CONF, "URL scheme to force into generated URLs for a vhost."),
1499 AP_INIT_FLAG("ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1500 (void *) offsetof (shib_dir_config, bBasicHijack),
1501 OR_AUTHCFG, "Respond to AuthType Basic and convert to shib?"),
1502 AP_INIT_FLAG("ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1503 (void *) offsetof (shib_dir_config, bRequireSession),
1504 OR_AUTHCFG, "Initiates a new session if one does not exist."),
1505 AP_INIT_FLAG("ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1506 (void *) offsetof (shib_dir_config, bExportAssertion),
1507 OR_AUTHCFG, "Export SAML assertion to Shibboleth-defined header?"),
1508 AP_INIT_TAKE1("AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
1509 (void *) offsetof (shib_dir_config, szAuthGrpFile),
1510 OR_AUTHCFG, "text file containing group names and member user IDs"),
1511 AP_INIT_FLAG("ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1512 (void *) offsetof (shib_dir_config, bRequireAll),
1513 OR_AUTHCFG, "All require directives must match!"),
1518 module AP_MODULE_DECLARE_DATA mod_shib = {
1519 STANDARD20_MODULE_STUFF,
1520 create_shib_dir_config, /* create dir config */
1521 merge_shib_dir_config, /* merge dir config --- default is to override */
1522 create_shib_server_config, /* create server config */
1523 merge_shib_server_config, /* merge server config */
1524 shib_cmds, /* command table */
1525 shib_register_hooks /* register hooks */
1529 #error "undefined APACHE version"