2 * mod_apache.cpp -- the core Apache Module code
4 * Created by: Derek Atkins <derek@ihtfp.com>
10 #include <saml/saml.h>
11 #include <shib/shib.h>
12 #include <shib/shib-threads.h>
13 #include <shib-target/shib-target.h>
14 #include <xercesc/util/regx/RegularExpression.hpp>
18 // Apache specific header files
20 #include <http_config.h>
21 #include <http_protocol.h>
22 #include <http_main.h>
24 #include <http_core.h>
27 #ifndef SHIB_APACHE_13
28 #include <http_request.h>
29 #include <apr_strings.h>
30 #include <apr_pools.h>
37 #include <unistd.h> // for getpid()
42 using namespace shibboleth;
43 using namespace shibtarget;
45 extern "C" module MODULE_VAR_EXPORT mod_shib;
46 int shib_handler(request_rec* r, const IApplication* application, const IPropertySet* sessionProps, SHIRE& shire);
49 char* g_szSHIBConfig = NULL;
50 char* g_szSchemaDir = NULL;
51 ShibTargetConfig* g_Config = NULL;
52 static const char* g_UserDataKey = "_shib_check_user_";
55 // per-dir module configuration structure
56 struct shib_dir_config
59 char* szAuthGrpFile; // Auth GroupFile name
60 int bRequireAll; // all require directives must match, otherwise OR logic
62 // SHIRE Configuration
63 int bBasicHijack; // activate for AuthType Basic?
64 int bRequireSession; // require a session?
65 int bExportAssertion; // export SAML assertion to the environment?
68 // creates per-directory config structure
69 extern "C" void* create_shib_dir_config (SH_AP_POOL* p, char* d)
71 shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
72 dc->bBasicHijack = -1;
73 dc->bRequireSession = -1;
74 dc->bExportAssertion = -1;
76 dc->szAuthGrpFile = NULL;
80 // overrides server configuration in directories
81 extern "C" void* merge_shib_dir_config (SH_AP_POOL* p, void* base, void* sub)
83 shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
84 shib_dir_config* parent=(shib_dir_config*)base;
85 shib_dir_config* child=(shib_dir_config*)sub;
87 if (child->szAuthGrpFile)
88 dc->szAuthGrpFile=ap_pstrdup(p,child->szAuthGrpFile);
89 else if (parent->szAuthGrpFile)
90 dc->szAuthGrpFile=ap_pstrdup(p,parent->szAuthGrpFile);
92 dc->szAuthGrpFile=NULL;
94 dc->bBasicHijack=((child->bBasicHijack==-1) ? parent->bBasicHijack : child->bBasicHijack);
95 dc->bRequireSession=((child->bRequireSession==-1) ? parent->bRequireSession : child->bRequireSession);
96 dc->bExportAssertion=((child->bExportAssertion==-1) ? parent->bExportAssertion : child->bExportAssertion);
97 dc->bRequireAll=((child->bRequireAll==-1) ? parent->bRequireAll : child->bRequireAll);
101 // generic global slot handlers
102 extern "C" const char* ap_set_global_string_slot(cmd_parms* parms, void*, const char* arg)
104 *((char**)(parms->info))=ap_pstrdup(parms->pool,arg);
108 typedef const char* (*config_fn_t)(void);
110 static int shib_error_page(request_rec* r, const IApplication* app, const char* page, ShibMLP& mlp)
112 const IPropertySet* props=app->getPropertySet("Errors");
114 pair<bool,const char*> p=props->getString(page);
116 ifstream infile(p.second);
117 if (!infile.fail()) {
118 const char* res = mlp.run(infile);
120 r->content_type = ap_psprintf(r->pool, "text/html");
121 ap_send_http_header(r);
129 ap_log_rerror(APLOG_MARK,APLOG_ERR,SH_AP_R(r),
130 "shib_error_page() could not process shire error template for application %s",app->getId());
134 extern "C" int shib_check_user(request_rec* r)
136 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: ENTER");
137 shib_dir_config* dc=(shib_dir_config*)ap_get_module_config(r->per_dir_config,&mod_shib);
139 ostringstream threadid;
140 threadid << "[" << getpid() << "] shib_check_user" << '\0';
141 saml::NDC ndc(threadid.str().c_str());
143 // This will always be normalized, because Apache uses ap_get_server_name in this API call.
144 const char* targeturl=ap_construct_url(r->pool,r->unparsed_uri,r);
146 // We lock the configuration system for the duration.
147 IConfig* conf=g_Config->getINI();
150 // Map request to application and content settings.
151 IRequestMapper* mapper=conf->getRequestMapper();
152 Locker locker2(mapper);
153 IRequestMapper::Settings settings=mapper->getSettingsFromParsedURL(
154 ap_http_method(r), ap_get_server_name(r), ap_get_server_port(r), r->unparsed_uri
156 pair<bool,const char*> application_id=settings.first->getString("applicationId");
157 const IApplication* application=conf->getApplication(application_id.second);
158 const IPropertySet* sessionProps=application ? application->getPropertySet("Sessions") : NULL;
159 if (!application || !sessionProps) {
160 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
161 "shib_check_user: unable to map request to application session settings, check configuration");
165 // Declare SHIRE object for this request.
166 SHIRE shire(application);
168 // Get location of this application's assertion consumer service and see if this is it.
169 if (strstr(targeturl,shire.getShireURL(targeturl))) {
170 return shib_handler(r,application,sessionProps,shire);
173 // We can short circuit the handler if we run this...
174 apr_pool_userdata_setn((const void*)42,g_UserDataKey,NULL,r->pool);
176 // Regular access to arbitrary resource...check AuthType
177 const char *auth_type=ap_auth_type(r);
181 if (strcasecmp(auth_type,"shibboleth")) {
182 if (!strcasecmp(auth_type,"basic") && dc->bBasicHijack==1) {
183 core_dir_config* conf=
184 (core_dir_config*)ap_get_module_config(r->per_dir_config,
185 ap_find_linked_module("http_core.c"));
186 conf->ap_auth_type="shibboleth";
192 pair<bool,bool> requireSession = settings.first->getBool("requireSession");
193 if (!requireSession.first || !requireSession.second)
194 if (dc->bRequireSession==1)
195 requireSession.second=true;
197 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: session check for %s",targeturl);
199 pair<bool,const char*> shib_cookie=sessionProps->getString("cookieName");
200 if (!shib_cookie.first) {
201 ap_log_rerror(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(r),
202 "shib_check_user: no cookieName set for %s",
203 application_id.second);
207 // We're in charge, so check for cookie.
208 const char* session_id=NULL;
209 const char* cookies=ap_table_get(r->headers_in,"Cookie");
212 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: cookies found: %s",cookies);
213 if (session_id=strstr(cookies,shib_cookie.second)) {
214 // Yep, we found a cookie -- pull it out (our session_id)
215 session_id+=strlen(shib_cookie.second) + 1; /* Skip over the '=' */
216 char* cookiebuf = ap_pstrdup(r->pool,session_id);
217 char* cookieend = strchr(cookiebuf,';');
219 *cookieend = '\0'; /* Ignore anyting after a ; */
220 session_id=cookiebuf;
224 if (!session_id || !*session_id) {
225 // If no session required, bail now.
226 if (!requireSession.second)
229 // No acceptable cookie, and we require a session. Generate an AuthnRequest.
230 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: no cookie found -- redirecting to WAYF");
231 ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(targeturl)));
235 // Make sure this session is still valid.
236 RPCError* status = NULL;
237 ShibMLP markupProcessor(application);
238 markupProcessor.insert("requestURL", targeturl);
241 status = shire.sessionIsValid(session_id, r->connection->remote_ip);
243 catch (ShibTargetException &e) {
244 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): %s", e.what());
245 markupProcessor.insert("errorType", "Session Processing Error");
246 markupProcessor.insert("errorText", e.what());
247 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
248 return shib_error_page(r, application, "shire", markupProcessor);
252 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): caught unexpected error");
253 markupProcessor.insert("errorType", "Session Processing Error");
254 markupProcessor.insert("errorText", "Unexpected Exception");
255 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
256 return shib_error_page(r, application, "shire", markupProcessor);
261 if (status->isError()) {
262 ap_log_rerror(APLOG_MARK,APLOG_INFO|APLOG_NOERRNO,SH_AP_R(r),
263 "shib_check_user() session invalid: %s", status->getText());
265 // If no session required, bail now.
266 if (!requireSession.second)
267 return OK; // XXX: Or should this be DECLINED?
268 // Has to be OK because DECLINED will just cause Apache to fail when it can't locate
269 // anything to process the AuthType. No session plus requireSession false means
270 // do not authenticate the user.
271 else if (status->isRetryable()) {
272 // Oops, session is invalid. Generate AuthnRequest.
273 ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(targeturl)));
278 // return the error page to the user
279 markupProcessor.insert(*status);
281 return shib_error_page(r, application, "shire", markupProcessor);
287 #ifdef SHIB_APACHE_13
289 r->connection->ap_auth_type = "shibboleth";
291 r->ap_auth_type = "shibboleth";
293 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: session successfully verified");
295 // This is code transferred in from the auth check to export the attributes.
296 // We could even combine the isSessionValid/getAssertions API...?
299 vector<SAMLAssertion*> assertions;
300 SAMLAuthenticationStatement* sso_statement=NULL;
303 status = rm.getAssertions(session_id, r->connection->remote_ip, assertions, &sso_statement);
305 catch (ShibTargetException &e) {
306 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): %s", e.what());
307 markupProcessor.insert("errorType", "Attribute Processing Error");
308 markupProcessor.insert("errorText", e.what());
309 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
310 return shib_error_page(r, application, "rm", markupProcessor);
314 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): caught unexpected error");
315 markupProcessor.insert("errorType", "Attribute Processing Error");
316 markupProcessor.insert("errorText", "Unexpected Exception");
317 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
318 return shib_error_page(r, application, "rm", markupProcessor);
322 if (status->isError()) {
323 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
324 "shib_check_user() getAssertions failed: %s", status->getText());
326 markupProcessor.insert(*status);
328 return shib_error_page(r, application, "rm", markupProcessor);
332 // Do we have an access control plugin?
333 if (settings.second) {
334 Locker acllock(settings.second);
335 if (!settings.second->authorized(assertions)) {
336 for (int k = 0; k < assertions.size(); k++)
337 delete assertions[k];
338 delete sso_statement;
339 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): access control provider denied access");
340 return shib_error_page(r, application, "access", markupProcessor);
344 // Get the AAP providers, which contain the attribute policy info.
345 Iterator<IAAP*> provs=application->getAAPProviders();
347 // Clear out the list of mapped attributes
348 while (provs.hasNext()) {
349 IAAP* aap=provs.next();
352 Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
353 while (rules.hasNext()) {
354 const char* header=rules.next()->getHeader();
356 ap_table_unset(r->headers_in,header);
361 for (int k = 0; k < assertions.size(); k++)
362 delete assertions[k];
363 delete sso_statement;
364 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
365 "shib_check_user(): caught unexpected error while clearing headers");
366 markupProcessor.insert("errorType", "Attribute Processing Error");
367 markupProcessor.insert("errorText", "Unexpected Exception");
368 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
369 return shib_error_page(r, application, "rm", markupProcessor);
375 // Maybe export the first assertion.
376 ap_table_unset(r->headers_in,"Shib-Attributes");
377 pair<bool,bool> exp=settings.first->getBool("exportAssertion");
378 if (!exp.first || !exp.second)
379 if (dc->bExportAssertion==1)
381 if (exp.second && assertions.size()) {
383 RM::serialize(*(assertions[0]), assertion);
384 ap_table_set(r->headers_in,"Shib-Attributes", assertion.c_str());
387 // Export the SAML AuthnMethod and the origin site name.
388 ap_table_unset(r->headers_in,"Shib-Origin-Site");
389 ap_table_unset(r->headers_in,"Shib-Authentication-Method");
391 auto_ptr_char os(sso_statement->getSubject()->getNameIdentifier()->getNameQualifier());
392 auto_ptr_char am(sso_statement->getAuthMethod());
393 ap_table_set(r->headers_in,"Shib-Origin-Site", os.get());
394 ap_table_set(r->headers_in,"Shib-Authentication-Method", am.get());
397 ap_table_unset(r->headers_in,"Shib-Application-ID");
398 ap_table_set(r->headers_in,"Shib-Application-ID",application_id.second);
400 // Export the attributes.
401 Iterator<SAMLAssertion*> a_iter(assertions);
402 while (a_iter.hasNext()) {
403 SAMLAssertion* assert=a_iter.next();
404 Iterator<SAMLStatement*> statements=assert->getStatements();
405 while (statements.hasNext()) {
406 SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());
409 Iterator<SAMLAttribute*> attrs=astate->getAttributes();
410 while (attrs.hasNext()) {
411 SAMLAttribute* attr=attrs.next();
413 // Are we supposed to export it?
414 AAP wrapper(provs,attr->getName(),attr->getNamespace());
418 Iterator<string> vals=attr->getSingleByteValues();
419 if (!strcmp(wrapper->getHeader(),"REMOTE_USER") && vals.hasNext())
420 SH_AP_USER(r)=ap_pstrdup(r->pool,vals.next().c_str());
423 char* header = (char*)ap_table_get(r->headers_in, wrapper->getHeader());
425 header=ap_pstrdup(r->pool, header);
429 header = ap_pstrdup(r->pool, "");
430 for (; vals.hasNext(); it++) {
431 string value = vals.next();
432 for (string::size_type pos = value.find_first_of(";", string::size_type(0));
434 pos = value.find_first_of(";", pos)) {
435 value.insert(pos, "\\");
438 header=ap_pstrcat(r->pool, header, (it ? ";" : ""), value.c_str(), NULL);
440 ap_table_setn(r->headers_in, wrapper->getHeader(), header);
447 for (int k = 0; k < assertions.size(); k++)
448 delete assertions[k];
449 delete sso_statement;
454 extern "C" int shib_post_handler(request_rec* r)
456 #ifndef SHIB_APACHE_13
457 // With 2.x, this handler always runs, though last.
458 // We check if shib_check_user ran, because it will detect a SHIRE request
459 // and dispatch it directly.
461 apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
462 if (data==(const void*)42) {
463 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_post_handler skipped since check_user ran");
468 ostringstream threadid;
469 threadid << "[" << getpid() << "] shib_post_handler" << '\0';
470 saml::NDC ndc(threadid.str().c_str());
472 // We lock the configuration system for the duration.
473 IConfig* conf=g_Config->getINI();
476 // Map request to application and content settings.
477 IRequestMapper* mapper=conf->getRequestMapper();
478 Locker locker2(mapper);
479 IRequestMapper::Settings settings=mapper->getSettingsFromParsedURL(
480 ap_http_method(r), ap_get_server_name(r), ap_get_server_port(r), r->unparsed_uri
482 pair<bool,const char*> application_id=settings.first->getString("applicationId");
483 const IApplication* application=conf->getApplication(application_id.second);
484 const IPropertySet* sessionProps=application ? application->getPropertySet("Sessions") : NULL;
485 if (!application || !sessionProps) {
486 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
487 "shib_post_handler: unable to map request to application session settings, check configuration");
491 // Declare SHIRE object for this request.
492 SHIRE shire(application);
494 return shib_handler(r, application, sessionProps, shire);
497 int shib_handler(request_rec* r, const IApplication* application, const IPropertySet* sessionProps, SHIRE& shire)
500 const char* targeturl = ap_construct_url(r->pool,r->unparsed_uri,r);
502 // Make sure we only process the SHIRE requests.
503 if (!strstr(targeturl,shire.getShireURL(targeturl)))
506 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler() running");
508 pair<bool,const char*> shib_cookie=sessionProps->getString("cookieName");
509 pair<bool,const char*> shib_cookie_props=sessionProps->getString("cookieProps");
510 if (!shib_cookie.first) {
511 ap_log_rerror(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(r),
512 "shib_handler: no cookieName set for %s", application->getId());
516 ShibMLP markupProcessor(application);
517 markupProcessor.insert("requestURL", targeturl);
519 // Process SHIRE request
520 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() Beginning SHIRE processing");
523 pair<bool,bool> shireSSL=sessionProps->getBool("shireSSL");
525 // Make sure this is SSL, if it should be
526 if ((!shireSSL.first || shireSSL.second) && strcmp(ap_http_method(r),"https"))
527 throw ShibTargetException(SHIBRPC_OK, "blocked non-SSL access to session creation service");
529 // If this is a GET, we manufacture an AuthnRequest.
530 if (!strcasecmp(r->method,"GET")) {
531 const char* areq=r->args ? shire.getLazyAuthnRequest(r->args) : NULL;
533 throw ShibTargetException(SHIBRPC_OK, "malformed arguments to request a new session");
534 ap_table_setn(r->headers_out, "Location", ap_pstrdup(r->pool,areq));
537 else if (strcasecmp(r->method,"POST")) {
538 throw ShibTargetException(SHIBRPC_OK, "blocked non-POST to SHIRE POST processor");
541 // Sure sure this POST is an appropriate content type
542 const char *ct = ap_table_get(r->headers_in, "Content-type");
543 if (!ct || strcasecmp(ct, "application/x-www-form-urlencoded"))
544 throw ShibTargetException(SHIBRPC_OK,
545 ap_psprintf(r->pool, "blocked bad content-type to SHIRE POST processor: %s", (ct ? ct : "")));
547 // Read the posted data
548 if (ap_setup_client_block(r, REQUEST_CHUNKED_ERROR))
549 throw ShibTargetException(SHIBRPC_OK, "CGI setup_client_block failed");
550 if (!ap_should_client_block(r))
551 throw ShibTargetException(SHIBRPC_OK, "CGI should_client_block failed");
552 if (r->remaining > 1024*1024)
553 throw ShibTargetException (SHIBRPC_OK, "CGI length too long...");
556 char buff[HUGE_STRING_LEN];
557 ap_hard_timeout("[mod_shib] CGI Parser", r);
558 memset(buff, 0, sizeof(buff));
559 while (ap_get_client_block(r, buff, sizeof(buff)-1) > 0) {
561 memset(buff, 0, sizeof(buff));
565 // Parse the submission.
566 pair<const char*,const char*> elements=shire.getFormSubmission(cgistr.c_str(),cgistr.length());
568 // Make sure the SAML Response parameter exists
569 if (!elements.first || !*elements.first)
570 throw ShibTargetException(SHIBRPC_OK, "SHIRE POST failed to find SAMLResponse form element");
572 // Make sure the target parameter exists
573 if (!elements.second || !*elements.second)
574 throw ShibTargetException(SHIBRPC_OK, "SHIRE POST failed to find TARGET form element");
576 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
577 "shib_handler() Processing POST for target: %s", elements.second);
581 RPCError* status = shire.sessionCreate(elements.first, r->connection->remote_ip, cookie);
583 if (status->isError()) {
584 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
585 "shib_handler() POST process failed (%d): %s", status->getCode(), status->getText());
587 if (status->isRetryable()) {
589 ap_log_rerror(APLOG_MARK,APLOG_INFO|APLOG_NOERRNO,SH_AP_R(r),
590 "shib_handler() retryable error, generating new AuthnRequest");
591 ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(elements.second)));
595 // return this error to the user.
596 markupProcessor.insert(*status);
598 return shib_error_page(r, application, "shire", markupProcessor);
602 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
603 "shib_handler() POST process succeeded. New session: %s", cookie.c_str());
605 // We've got a good session, set the cookie...
606 char* val = ap_psprintf(r->pool,"%s=%s%s",shib_cookie.second,cookie.c_str(),
607 shib_cookie_props.first ? shib_cookie_props.second : "; path=/");
608 ap_table_setn(r->err_headers_out, "Set-Cookie", val);
609 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() setting cookie: %s", val);
611 // ... and redirect to the target
612 ap_table_setn(r->headers_out, "Location", ap_pstrdup(r->pool,elements.second));
615 catch (ShibTargetException &e) {
616 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() caught exception: %s", e.what());
617 markupProcessor.insert("errorType", "Session Creation Service Error");
618 markupProcessor.insert("errorText", e.what());
619 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
620 return shib_error_page(r, application, "shire", markupProcessor);
624 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler(): unexpected exception");
625 markupProcessor.insert("errorType", "Session Creation Service Error");
626 markupProcessor.insert("errorText", "Unknown Exception");
627 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
628 return shib_error_page(r, application, "shire", markupProcessor);
632 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_handler() server error");
636 static SH_AP_TABLE* groups_for_user(request_rec* r, const char* user, char* grpfile)
639 SH_AP_TABLE* grps=ap_make_table(r->pool,15);
640 char l[MAX_STRING_LEN];
641 const char *group_name, *ll, *w;
643 #ifdef SHIB_APACHE_13
644 if (!(f=ap_pcfg_openfile(r->pool,grpfile))) {
646 if (ap_pcfg_openfile(&f,r->pool,grpfile) != APR_SUCCESS) {
648 ap_log_rerror(APLOG_MARK,APLOG_DEBUG,SH_AP_R(r),"groups_for_user() could not open group file: %s\n",grpfile);
653 #ifdef SHIB_APACHE_13
654 sp=ap_make_sub_pool(r->pool);
656 if (apr_pool_create(&sp,r->pool) != APR_SUCCESS) {
657 ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,
658 "groups_for_user() could not create a subpool");
663 while (!(ap_cfg_getline(l,MAX_STRING_LEN,f))) {
664 if ((*l=='#') || (!*l))
669 group_name=ap_getword(sp,&ll,':');
672 w=ap_getword_conf(sp,&ll);
673 if (!strcmp(w,user)) {
674 ap_table_setn(grps,ap_pstrdup(r->pool,group_name),"in");
685 * shib_auth_checker() -- a simple resource manager to
686 * process the .htaccess settings and copy attributes
687 * into the HTTP headers.
689 extern "C" int shib_auth_checker(request_rec* r)
692 (shib_dir_config*)ap_get_module_config(r->per_dir_config,&mod_shib);
694 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() executing");
696 // Regular access to arbitrary resource...check AuthType
697 const char* auth_type=ap_auth_type(r);
698 if (!auth_type || strcasecmp(auth_type,"shibboleth"))
701 ostringstream threadid;
702 threadid << "[" << getpid() << "] shibrm" << '\0';
703 saml::NDC ndc(threadid.str().c_str());
705 // We lock the configuration system for the duration.
706 IConfig* conf=g_Config->getINI();
709 const char* application_id=ap_table_get(r->headers_in,"Shib-Application-ID");
710 const IApplication* application=NULL;
712 application = conf->getApplication(application_id);
716 int m=r->method_number;
717 bool method_restricted=false;
720 const array_header* reqs_arr=ap_requires(r);
724 require_line* reqs=(require_line*)reqs_arr->elts;
726 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"REQUIRE nelts: %d", reqs_arr->nelts);
727 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"REQUIRE all: %d", dc->bRequireAll);
729 vector<bool> auth_OK(reqs_arr->nelts,false);
731 #define SHIB_AP_CHECK_IS_OK { \
732 if (dc->bRequireAll < 1) \
738 for (int x=0; x<reqs_arr->nelts; x++) {
740 if (!(reqs[x].method_mask & (1 << m)))
742 method_restricted=true;
744 t = reqs[x].requirement;
745 w = ap_getword_white(r->pool, &t);
747 if (!strcasecmp(w,"Shibboleth")) {
748 // This is a dummy rule needed because Apache conflates authn and authz.
749 // Without some require rule, AuthType is ignored and no check_user hooks run.
752 else if (!strcmp(w,"valid-user") && application_id) {
753 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting valid-user");
756 else if (!strcmp(w,"user") && SH_AP_USER(r)) {
759 w=ap_getword_conf(r->pool,&t);
767 // To do regex matching, we have to convert from UTF-8.
768 auto_ptr<XMLCh> trans(fromUTF8(w));
769 RegularExpression re(trans.get());
770 auto_ptr<XMLCh> trans2(fromUTF8(SH_AP_USER(r)));
771 if (re.matches(trans2.get())) {
772 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting user: %s",w);
776 catch (XMLException& ex) {
777 auto_ptr_char tmp(ex.getMessage());
778 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
779 "shib_auth_checker caught exception while parsing regular expression (%s): %s",w,tmp.get());
782 else if (!strcmp(SH_AP_USER(r),w)) {
783 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting user: %s",w);
788 else if (!strcmp(w,"group")) {
789 SH_AP_TABLE* grpstatus=NULL;
790 if (dc->szAuthGrpFile && SH_AP_USER(r)) {
791 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() using groups file: %s\n",dc->szAuthGrpFile);
792 grpstatus=groups_for_user(r,SH_AP_USER(r),dc->szAuthGrpFile);
798 w=ap_getword_conf(r->pool,&t);
799 if (ap_table_get(grpstatus,w)) {
800 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting group: %s",w);
806 Iterator<IAAP*> provs=application ? application->getAAPProviders() : EMPTY(IAAP*);
807 AAP wrapper(provs,w);
808 if (wrapper.fail()) {
809 ap_log_rerror(APLOG_MARK,APLOG_WARNING|APLOG_NOERRNO,SH_AP_R(r),
810 "shib_auth_checker() didn't recognize require rule: %s\n",w);
815 const char* vals=ap_table_get(r->headers_in,wrapper->getHeader());
817 w=ap_getword_conf(r->pool,&t);
824 auto_ptr<RegularExpression> re;
827 auto_ptr<XMLCh> trans(fromUTF8(w));
828 auto_ptr<RegularExpression> temp(new RegularExpression(trans.get()));
832 string vals_str(vals);
834 for (int i = 0; i < vals_str.length(); i++) {
835 if (vals_str.at(i) == ';') {
837 ap_log_rerror(APLOG_MARK,APLOG_WARNING|APLOG_NOERRNO,SH_AP_R(r),
838 "shib_auth_checker() invalid header encoding %s: starts with semicolon", vals);
842 if (vals_str.at(i-1) == '\\') {
843 vals_str.erase(i-1, 1);
848 string val = vals_str.substr(j, i-j);
851 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
852 if (re->matches(trans.get())) {
853 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
854 "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
859 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
860 "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
864 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
865 "shib_auth_checker() expecting %s, got %s: authorization not granted", w, val.c_str());
870 string val = vals_str.substr(j, vals_str.length()-j);
872 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
873 if (re->matches(trans.get())) {
874 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
875 "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
880 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
881 "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
885 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
886 "shib_auth_checker() expecting %s, got %s: authorization not granted", w, val.c_str());
889 catch (XMLException& ex) {
890 auto_ptr_char tmp(ex.getMessage());
891 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
892 "shib_auth_checker caught exception while parsing regular expression (%s): %s",w,tmp.get());
898 // check if all require directives are true
899 bool auth_all_OK = true;
900 for (int i= 0; i<reqs_arr->nelts; i++) {
901 auth_all_OK &= auth_OK[i];
906 if (!method_restricted)
909 if (!application_id) {
910 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
911 "shib_auth_checker: Shib-Application-ID header not found in request");
912 return HTTP_FORBIDDEN;
914 else if (!application) {
915 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
916 "shib_auth_checker: unable to map request to application settings, check configuration");
917 return HTTP_FORBIDDEN;
920 ShibMLP markupProcessor(application);
921 markupProcessor.insert("requestURL", ap_construct_url(r->pool,r->unparsed_uri,r));
922 return shib_error_page(r, application, "access", markupProcessor);
927 * Cleanup the (per-process) pool info.
929 #ifdef SHIB_APACHE_13
930 extern "C" void shib_exit(server_rec* s, SH_AP_POOL* p)
933 extern "C" apr_status_t shib_exit(void* data)
935 server_rec* s = NULL;
937 g_Config->shutdown();
939 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_exit() done");
940 #ifndef SHIB_APACHE_13
947 * Things to do when the child process is initialized.
948 * (or after the configs are read in apache-2)
950 #ifdef SHIB_APACHE_13
951 extern "C" void shib_child_init(server_rec* s, SH_AP_POOL* p)
953 extern "C" int shib_post_config(apr_pool_t* pconf, apr_pool_t* plog,
954 apr_pool_t* ptemp, server_rec* s)
957 // Initialize runtime components.
959 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() starting");
962 ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() already initialized!");
963 #ifdef SHIB_APACHE_13
971 g_Config=&ShibTargetConfig::getConfig();
972 g_Config->setFeatures(
973 ShibTargetConfig::Listener |
974 ShibTargetConfig::Metadata |
975 ShibTargetConfig::AAP |
976 ShibTargetConfig::RequestMapper |
977 ShibTargetConfig::SHIREExtensions
979 if (!g_Config->init(g_szSchemaDir,g_szSHIBConfig)) {
980 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize SHIB Target");
985 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize SHIB Target");
989 // Set the cleanup handler
990 apr_pool_cleanup_register(pconf, NULL, shib_exit, NULL);
992 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() done");
994 #ifndef SHIB_APACHE_13
999 #ifdef SHIB_APACHE_13
1001 // SHIB Module commands
1003 static command_rec shire_cmds[] = {
1004 {"SHIREConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1005 RSRC_CONF, TAKE1, "Path to shibboleth.xml config file."},
1006 {"ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1007 RSRC_CONF, TAKE1, "Path to shibboleth.xml config file."},
1008 {"ShibSchemaDir", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1009 RSRC_CONF, TAKE1, "Path to Shibboleth XML schema directory."},
1011 {"ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1012 (void *) XtOffsetOf (shib_dir_config, bBasicHijack),
1013 OR_AUTHCFG, FLAG, "Respond to AuthType Basic and convert to shib?"},
1014 {"ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1015 (void *) XtOffsetOf (shib_dir_config, bRequireSession),
1016 OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist."},
1017 {"ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1018 (void *) XtOffsetOf (shib_dir_config, bExportAssertion),
1019 OR_AUTHCFG, FLAG, "Export SAML assertion to Shibboleth-defined header?"},
1020 {"AuthGroupFile", (config_fn_t)ap_set_file_slot,
1021 (void *) XtOffsetOf (shib_dir_config, szAuthGrpFile),
1022 OR_AUTHCFG, TAKE1, "text file containing group names and member user IDs"},
1023 {"ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1024 (void *) XtOffsetOf (shib_dir_config, bRequireAll),
1025 OR_AUTHCFG, FLAG, "All require directives must match!"},
1031 handler_rec shib_handlers[] = {
1032 { "shib-shire-post", shib_post_handler },
1036 module MODULE_VAR_EXPORT mod_shib = {
1037 STANDARD_MODULE_STUFF,
1038 NULL, /* initializer */
1039 create_shib_dir_config, /* dir config creater */
1040 merge_shib_dir_config, /* dir merger --- default is to override */
1041 NULL, /* server config */
1042 NULL, /* merge server config */
1043 shire_cmds, /* command table */
1044 shib_handlers, /* handlers */
1045 NULL, /* filename translation */
1046 shib_check_user, /* check_user_id */
1047 shib_auth_checker, /* check auth */
1048 NULL, /* check access */
1049 NULL, /* type_checker */
1052 NULL, /* header parser */
1053 shib_child_init, /* child_init */
1054 shib_exit, /* child_exit */
1055 NULL /* post read-request */
1058 #elif defined(SHIB_APACHE_20)
1060 extern "C" void shib_register_hooks (apr_pool_t *p)
1062 ap_hook_post_config(shib_post_config, NULL, NULL, APR_HOOK_MIDDLE);
1063 ap_hook_check_user_id(shib_check_user, NULL, NULL, APR_HOOK_MIDDLE);
1064 ap_hook_auth_checker(shib_auth_checker, NULL, NULL, APR_HOOK_FIRST);
1065 ap_hook_handler(shib_post_handler, NULL, NULL, APR_HOOK_LAST);
1068 // SHIB Module commands
1071 static command_rec shib_cmds[] = {
1072 AP_INIT_TAKE1("ShibConfig",
1073 (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1074 RSRC_CONF, "Path to shibboleth.xml config file."),
1075 AP_INIT_TAKE1("ShibSchemaDir",
1076 (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1077 RSRC_CONF, "Path to Shibboleth XML schema directory."),
1079 AP_INIT_FLAG("ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1080 (void *) offsetof (shib_dir_config, bBasicHijack),
1081 OR_AUTHCFG, "Respond to AuthType Basic and convert to shib?"),
1082 AP_INIT_FLAG("ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1083 (void *) offsetof (shib_dir_config, bRequireSession),
1084 OR_AUTHCFG, "Initiates a new session if one does not exist."),
1085 AP_INIT_FLAG("ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1086 (void *) offsetof (shib_dir_config, bExportAssertion),
1087 OR_AUTHCFG, "Export SAML assertion to Shibboleth-defined header?"),
1088 AP_INIT_TAKE1("AuthGroupFile", (config_fn_t)ap_set_file_slot,
1089 (void *) offsetof (shib_dir_config, szAuthGrpFile),
1090 OR_AUTHCFG, "text file containing group names and member user IDs"),
1091 AP_INIT_FLAG("ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1092 (void *) offsetof (shib_dir_config, bRequireAll),
1093 OR_AUTHCFG, "All require directives must match!"),
1098 module AP_MODULE_DECLARE_DATA mod_shib = {
1099 STANDARD20_MODULE_STUFF,
1100 create_shib_dir_config, /* create dir config */
1101 merge_shib_dir_config, /* merge dir config --- default is to override */
1102 NULL, /* create server config */
1103 NULL, /* merge server config */
1104 shib_cmds, /* command table */
1105 shib_register_hooks /* register hooks */
1109 #error "undefined APACHE version"