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 bool g_bApacheConf = false;
53 static const char* g_UserDataKey = "_shib_check_user_";
56 // per-dir module configuration structure
57 struct shib_dir_config
60 char* szAuthGrpFile; // Auth GroupFile name
61 int bRequireAll; // all require directives must match, otherwise OR logic
63 // SHIRE Configuration
64 int bBasicHijack; // activate for AuthType Basic?
65 int bRequireSession; // require a session?
66 int bExportAssertion; // export SAML assertion to the environment?
69 // creates per-directory config structure
70 extern "C" void* create_shib_dir_config (SH_AP_POOL* p, char* d)
72 shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
73 dc->bBasicHijack = -1;
74 dc->bRequireSession = -1;
75 dc->bExportAssertion = -1;
77 dc->szAuthGrpFile = NULL;
81 // overrides server configuration in directories
82 extern "C" void* merge_shib_dir_config (SH_AP_POOL* p, void* base, void* sub)
84 shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
85 shib_dir_config* parent=(shib_dir_config*)base;
86 shib_dir_config* child=(shib_dir_config*)sub;
88 if (child->szAuthGrpFile)
89 dc->szAuthGrpFile=ap_pstrdup(p,child->szAuthGrpFile);
90 else if (parent->szAuthGrpFile)
91 dc->szAuthGrpFile=ap_pstrdup(p,parent->szAuthGrpFile);
93 dc->szAuthGrpFile=NULL;
95 dc->bBasicHijack=((child->bBasicHijack==-1) ? parent->bBasicHijack : child->bBasicHijack);
96 dc->bRequireSession=((child->bRequireSession==-1) ? parent->bRequireSession : child->bRequireSession);
97 dc->bExportAssertion=((child->bExportAssertion==-1) ? parent->bExportAssertion : child->bExportAssertion);
98 dc->bRequireAll=((child->bRequireAll==-1) ? parent->bRequireAll : child->bRequireAll);
102 // generic global slot handlers
103 extern "C" const char* ap_set_global_string_slot(cmd_parms* parms, void*, const char* arg)
105 *((char**)(parms->info))=ap_pstrdup(parms->pool,arg);
109 typedef const char* (*config_fn_t)(void);
111 static int shib_error_page(request_rec* r, const IApplication* app, const char* page, ShibMLP& mlp)
113 const IPropertySet* props=app->getPropertySet("Errors");
115 pair<bool,const char*> p=props->getString(page);
117 ifstream infile(p.second);
118 if (!infile.fail()) {
119 const char* res = mlp.run(infile);
121 r->content_type = ap_psprintf(r->pool, "text/html");
122 ap_send_http_header(r);
130 ap_log_rerror(APLOG_MARK,APLOG_ERR,SH_AP_R(r),
131 "shib_error_page() could not process shire error template for application %s",app->getId());
135 extern "C" int shib_check_user(request_rec* r)
137 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: ENTER");
138 shib_dir_config* dc=(shib_dir_config*)ap_get_module_config(r->per_dir_config,&mod_shib);
140 ostringstream threadid;
141 threadid << "[" << getpid() << "] shib_check_user" << '\0';
142 saml::NDC ndc(threadid.str().c_str());
144 // This will always be normalized, because Apache uses ap_get_server_name in this API call.
145 const char* targeturl=ap_construct_url(r->pool,r->unparsed_uri,r);
147 // We lock the configuration system for the duration.
148 IConfig* conf=g_Config->getINI();
151 // Map request to application and content settings.
152 IRequestMapper* mapper=conf->getRequestMapper();
153 Locker locker2(mapper);
154 IRequestMapper::Settings settings=mapper->getSettingsFromParsedURL(
155 ap_http_method(r), ap_get_server_name(r), ap_get_server_port(r), r->unparsed_uri
157 pair<bool,const char*> application_id=settings.first->getString("applicationId");
158 const IApplication* application=conf->getApplication(application_id.second);
159 const IPropertySet* sessionProps=application ? application->getPropertySet("Sessions") : NULL;
160 if (!application || !sessionProps) {
161 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
162 "shib_check_user: unable to map request to application session settings, check configuration");
166 // Declare SHIRE object for this request.
167 SHIRE shire(application);
169 // Get location of this application's assertion consumer service and see if this is it.
170 if (strstr(targeturl,shire.getShireURL(targeturl))) {
171 return shib_handler(r,application,sessionProps,shire);
174 // We can short circuit the handler if we run this...
175 apr_pool_userdata_setn((const void*)42,g_UserDataKey,NULL,r->pool);
177 // Regular access to arbitrary resource...check AuthType
178 const char *auth_type=ap_auth_type(r);
182 if (strcasecmp(auth_type,"shibboleth")) {
183 if (!strcasecmp(auth_type,"basic") && dc->bBasicHijack==1) {
184 core_dir_config* conf=
185 (core_dir_config*)ap_get_module_config(r->per_dir_config,
186 ap_find_linked_module("http_core.c"));
187 conf->ap_auth_type="shibboleth";
193 pair<bool,bool> requireSession = pair<bool,bool>(false,false);
195 // By default, we will require a session.
196 if (dc->bRequireSession!=0)
197 requireSession.second=true;
200 requireSession = settings.first->getBool("requireSession");
202 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: session check for %s",targeturl);
204 pair<bool,const char*> shib_cookie=sessionProps->getString("cookieName");
205 if (!shib_cookie.first) {
206 ap_log_rerror(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(r),
207 "shib_check_user: no cookieName set for %s",
208 application_id.second);
212 // We're in charge, so check for cookie.
213 const char* session_id=NULL;
214 const char* cookies=ap_table_get(r->headers_in,"Cookie");
217 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: cookies found: %s",cookies);
218 if (session_id=strstr(cookies,shib_cookie.second)) {
219 // Yep, we found a cookie -- pull it out (our session_id)
220 session_id+=strlen(shib_cookie.second) + 1; /* Skip over the '=' */
221 char* cookiebuf = ap_pstrdup(r->pool,session_id);
222 char* cookieend = strchr(cookiebuf,';');
224 *cookieend = '\0'; /* Ignore anyting after a ; */
225 session_id=cookiebuf;
229 if (!session_id || !*session_id) {
230 // If no session required, bail now.
231 if (!requireSession.second)
234 // No acceptable cookie, and we require a session. Generate an AuthnRequest.
235 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: no cookie found -- redirecting to WAYF");
236 ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(targeturl)));
240 // Make sure this session is still valid.
241 RPCError* status = NULL;
242 ShibMLP markupProcessor(application);
243 markupProcessor.insert("requestURL", targeturl);
246 status = shire.sessionIsValid(session_id, r->connection->remote_ip);
248 catch (ShibTargetException &e) {
249 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): %s", e.what());
250 markupProcessor.insert("errorType", "Session Processing Error");
251 markupProcessor.insert("errorText", e.what());
252 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
253 return shib_error_page(r, application, "shire", markupProcessor);
257 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): caught unexpected error");
258 markupProcessor.insert("errorType", "Session Processing Error");
259 markupProcessor.insert("errorText", "Unexpected Exception");
260 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
261 return shib_error_page(r, application, "shire", markupProcessor);
266 if (status->isError()) {
267 ap_log_rerror(APLOG_MARK,APLOG_INFO|APLOG_NOERRNO,SH_AP_R(r),
268 "shib_check_user() session invalid: %s", status->getText());
270 // If no session required, bail now.
271 if (!requireSession.second)
272 return DECLINED; // XXX: Or should this be OK?
273 else if (status->isRetryable()) {
274 // Oops, session is invalid. Generate AuthnRequest.
275 ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(targeturl)));
280 // return the error page to the user
281 markupProcessor.insert(*status);
283 return shib_error_page(r, application, "shire", markupProcessor);
289 #ifdef SHIB_APACHE_13
291 r->connection->ap_auth_type = "shibboleth";
293 r->ap_auth_type = "shibboleth";
295 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: session successfully verified");
297 // This is code transferred in from the auth check to export the attributes.
298 // We could even combine the isSessionValid/getAssertions API...?
301 vector<SAMLAssertion*> assertions;
302 SAMLAuthenticationStatement* sso_statement=NULL;
305 status = rm.getAssertions(session_id, r->connection->remote_ip, assertions, &sso_statement);
307 catch (ShibTargetException &e) {
308 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): %s", e.what());
309 markupProcessor.insert("errorType", "Attribute Processing Error");
310 markupProcessor.insert("errorText", e.what());
311 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
312 return shib_error_page(r, application, "rm", markupProcessor);
316 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): caught unexpected error");
317 markupProcessor.insert("errorType", "Attribute Processing Error");
318 markupProcessor.insert("errorText", "Unexpected Exception");
319 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
320 return shib_error_page(r, application, "rm", markupProcessor);
324 if (status->isError()) {
325 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
326 "shib_check_user() getAssertions failed: %s", status->getText());
328 markupProcessor.insert(*status);
330 return shib_error_page(r, application, "rm", markupProcessor);
334 // Do we have an access control plugin?
335 if (settings.second) {
336 Locker acllock(settings.second);
337 if (!settings.second->authorized(assertions)) {
338 for (int k = 0; k < assertions.size(); k++)
339 delete assertions[k];
340 delete sso_statement;
341 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): access control provider denied access");
342 return shib_error_page(r, application, "access", markupProcessor);
346 // Get the AAP providers, which contain the attribute policy info.
347 Iterator<IAAP*> provs=application->getAAPProviders();
349 // Clear out the list of mapped attributes
350 while (provs.hasNext()) {
351 IAAP* aap=provs.next();
354 Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
355 while (rules.hasNext()) {
356 const char* header=rules.next()->getHeader();
358 ap_table_unset(r->headers_in,header);
363 for (int k = 0; k < assertions.size(); k++)
364 delete assertions[k];
365 delete sso_statement;
366 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
367 "shib_check_user(): caught unexpected error while clearing headers");
368 markupProcessor.insert("errorType", "Attribute Processing Error");
369 markupProcessor.insert("errorText", "Unexpected Exception");
370 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
371 return shib_error_page(r, application, "rm", markupProcessor);
377 // Maybe export the first assertion.
378 ap_table_unset(r->headers_in,"Shib-Attributes");
379 pair<bool,bool> exp=pair<bool,bool>(false,false);
380 if (g_bApacheConf && dc->bExportAssertion==1)
381 exp.second=exp.first=true;
382 else if (!g_bApacheConf)
383 exp=settings.first->getBool("exportAssertion");
384 if (exp.first && exp.second && assertions.size()) {
386 RM::serialize(*(assertions[0]), assertion);
387 ap_table_set(r->headers_in,"Shib-Attributes", assertion.c_str());
390 // Export the SAML AuthnMethod and the origin site name.
391 ap_table_unset(r->headers_in,"Shib-Origin-Site");
392 ap_table_unset(r->headers_in,"Shib-Authentication-Method");
394 auto_ptr_char os(sso_statement->getSubject()->getNameQualifier());
395 auto_ptr_char am(sso_statement->getAuthMethod());
396 ap_table_set(r->headers_in,"Shib-Origin-Site", os.get());
397 ap_table_set(r->headers_in,"Shib-Authentication-Method", am.get());
400 ap_table_unset(r->headers_in,"Shib-Application-ID");
401 ap_table_set(r->headers_in,"Shib-Application-ID",application_id.second);
403 // Export the attributes.
404 Iterator<SAMLAssertion*> a_iter(assertions);
405 while (a_iter.hasNext()) {
406 SAMLAssertion* assert=a_iter.next();
407 Iterator<SAMLStatement*> statements=assert->getStatements();
408 while (statements.hasNext()) {
409 SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());
412 Iterator<SAMLAttribute*> attrs=astate->getAttributes();
413 while (attrs.hasNext()) {
414 SAMLAttribute* attr=attrs.next();
416 // Are we supposed to export it?
417 AAP wrapper(provs,attr->getName(),attr->getNamespace());
421 Iterator<string> vals=attr->getSingleByteValues();
422 if (!strcmp(wrapper->getHeader(),"REMOTE_USER") && vals.hasNext())
423 SH_AP_USER(r)=ap_pstrdup(r->pool,vals.next().c_str());
426 char* header = (char*)ap_table_get(r->headers_in, wrapper->getHeader());
428 header=ap_pstrdup(r->pool, header);
432 header = ap_pstrdup(r->pool, "");
433 for (; vals.hasNext(); it++) {
434 string value = vals.next();
435 for (string::size_type pos = value.find_first_of(";", string::size_type(0));
437 pos = value.find_first_of(";", pos)) {
438 value.insert(pos, "\\");
441 header=ap_pstrcat(r->pool, header, (it ? ";" : ""), value.c_str(), NULL);
443 ap_table_setn(r->headers_in, wrapper->getHeader(), header);
450 for (int k = 0; k < assertions.size(); k++)
451 delete assertions[k];
452 delete sso_statement;
457 extern "C" int shib_post_handler(request_rec* r)
459 #ifndef SHIB_APACHE_13
460 // With 2.x, this handler always runs, though last.
461 // We check if shib_check_user ran, because it will detect a SHIRE request
462 // and dispatch it directly.
464 apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
465 if (data==(const void*)42) {
466 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_post_handler skipped since check_user ran");
471 ostringstream threadid;
472 threadid << "[" << getpid() << "] shib_post_handler" << '\0';
473 saml::NDC ndc(threadid.str().c_str());
475 // We lock the configuration system for the duration.
476 IConfig* conf=g_Config->getINI();
479 // Map request to application and content settings.
480 IRequestMapper* mapper=conf->getRequestMapper();
481 Locker locker2(mapper);
482 IRequestMapper::Settings settings=mapper->getSettingsFromParsedURL(
483 ap_http_method(r), ap_get_server_name(r), ap_get_server_port(r), r->unparsed_uri
485 pair<bool,const char*> application_id=settings.first->getString("applicationId");
486 const IApplication* application=conf->getApplication(application_id.second);
487 const IPropertySet* sessionProps=application ? application->getPropertySet("Sessions") : NULL;
488 if (!application || !sessionProps) {
489 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
490 "shib_post_handler: unable to map request to application session settings, check configuration");
494 // Declare SHIRE object for this request.
495 SHIRE shire(application);
497 return shib_handler(r, application, sessionProps, shire);
500 int shib_handler(request_rec* r, const IApplication* application, const IPropertySet* sessionProps, SHIRE& shire)
503 const char* targeturl = ap_construct_url(r->pool,r->unparsed_uri,r);
505 // Make sure we only process the SHIRE requests.
506 if (!strstr(targeturl,shire.getShireURL(targeturl)))
509 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler() running");
511 pair<bool,const char*> shib_cookie=sessionProps->getString("cookieName");
512 pair<bool,const char*> shib_cookie_props=sessionProps->getString("cookieProps");
513 if (!shib_cookie.first) {
514 ap_log_rerror(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(r),
515 "shib_handler: no cookieName set for %s", application->getId());
519 ShibMLP markupProcessor(application);
520 markupProcessor.insert("requestURL", targeturl);
522 // Process SHIRE request
523 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() Beginning SHIRE processing");
526 pair<bool,bool> shireSSL=sessionProps->getBool("shireSSL");
528 // Make sure this is SSL, if it should be
529 if ((!shireSSL.first || shireSSL.second) && strcmp(ap_http_method(r),"https"))
530 throw ShibTargetException(SHIBRPC_OK, "blocked non-SSL access to session creation service");
532 // If this is a GET, we manufacture an AuthnRequest.
533 if (!strcasecmp(r->method,"GET")) {
534 const char* areq=r->args ? shire.getLazyAuthnRequest(r->args) : NULL;
536 throw ShibTargetException(SHIBRPC_OK, "malformed arguments to request a new session");
537 ap_table_setn(r->headers_out, "Location", ap_pstrdup(r->pool,areq));
540 else if (strcasecmp(r->method,"POST")) {
541 throw ShibTargetException(SHIBRPC_OK, "blocked non-POST to SHIRE POST processor");
544 // Sure sure this POST is an appropriate content type
545 const char *ct = ap_table_get(r->headers_in, "Content-type");
546 if (!ct || strcasecmp(ct, "application/x-www-form-urlencoded"))
547 throw ShibTargetException(SHIBRPC_OK,
548 ap_psprintf(r->pool, "blocked bad content-type to SHIRE POST processor: %s", (ct ? ct : "")));
550 // Read the posted data
551 if (ap_setup_client_block(r, REQUEST_CHUNKED_ERROR))
552 throw ShibTargetException(SHIBRPC_OK, "CGI setup_client_block failed");
553 if (!ap_should_client_block(r))
554 throw ShibTargetException(SHIBRPC_OK, "CGI should_client_block failed");
555 if (r->remaining > 1024*1024)
556 throw ShibTargetException (SHIBRPC_OK, "CGI length too long...");
559 char buff[HUGE_STRING_LEN];
560 ap_hard_timeout("[mod_shib] CGI Parser", r);
561 memset(buff, 0, sizeof(buff));
562 while (ap_get_client_block(r, buff, sizeof(buff)-1) > 0) {
564 memset(buff, 0, sizeof(buff));
568 // Parse the submission.
569 pair<const char*,const char*> elements=shire.getFormSubmission(cgistr.c_str(),cgistr.length());
571 // Make sure the SAML Response parameter exists
572 if (!elements.first || !*elements.first)
573 throw ShibTargetException(SHIBRPC_OK, "SHIRE POST failed to find SAMLResponse form element");
575 // Make sure the target parameter exists
576 if (!elements.second || !*elements.second)
577 throw ShibTargetException(SHIBRPC_OK, "SHIRE POST failed to find TARGET form element");
579 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
580 "shib_handler() Processing POST for target: %s", elements.second);
584 RPCError* status = shire.sessionCreate(elements.first, r->connection->remote_ip, cookie);
586 if (status->isError()) {
587 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
588 "shib_handler() POST process failed (%d): %s", status->getCode(), status->getText());
590 if (status->isRetryable()) {
592 ap_log_rerror(APLOG_MARK,APLOG_INFO|APLOG_NOERRNO,SH_AP_R(r),
593 "shib_handler() retryable error, generating new AuthnRequest");
594 ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(elements.second)));
598 // return this error to the user.
599 markupProcessor.insert(*status);
601 return shib_error_page(r, application, "shire", markupProcessor);
605 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
606 "shib_handler() POST process succeeded. New session: %s", cookie.c_str());
608 // We've got a good session, set the cookie...
609 char* val = ap_psprintf(r->pool,"%s=%s%s",shib_cookie.second,cookie.c_str(),
610 shib_cookie_props.first ? shib_cookie_props.second : "; path=/");
611 ap_table_setn(r->err_headers_out, "Set-Cookie", val);
612 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() setting cookie: %s", val);
614 // ... and redirect to the target
615 ap_table_setn(r->headers_out, "Location", ap_pstrdup(r->pool,elements.second));
618 catch (ShibTargetException &e) {
619 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() caught exception: %s", e.what());
620 markupProcessor.insert("errorType", "Session Creation Service Error");
621 markupProcessor.insert("errorText", e.what());
622 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
623 return shib_error_page(r, application, "shire", markupProcessor);
627 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler(): unexpected exception");
628 markupProcessor.insert("errorType", "Session Creation Service Error");
629 markupProcessor.insert("errorText", "Unknown Exception");
630 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
631 return shib_error_page(r, application, "shire", markupProcessor);
635 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_handler() server error");
639 static SH_AP_TABLE* groups_for_user(request_rec* r, const char* user, char* grpfile)
642 SH_AP_TABLE* grps=ap_make_table(r->pool,15);
643 char l[MAX_STRING_LEN];
644 const char *group_name, *ll, *w;
646 #ifdef SHIB_APACHE_13
647 if (!(f=ap_pcfg_openfile(r->pool,grpfile))) {
649 if (ap_pcfg_openfile(&f,r->pool,grpfile) != APR_SUCCESS) {
651 ap_log_rerror(APLOG_MARK,APLOG_DEBUG,SH_AP_R(r),"groups_for_user() could not open group file: %s\n",grpfile);
656 #ifdef SHIB_APACHE_13
657 sp=ap_make_sub_pool(r->pool);
659 if (apr_pool_create(&sp,r->pool) != APR_SUCCESS) {
660 ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,
661 "groups_for_user() could not create a subpool");
666 while (!(ap_cfg_getline(l,MAX_STRING_LEN,f))) {
667 if ((*l=='#') || (!*l))
672 group_name=ap_getword(sp,&ll,':');
675 w=ap_getword_conf(sp,&ll);
676 if (!strcmp(w,user)) {
677 ap_table_setn(grps,ap_pstrdup(r->pool,group_name),"in");
688 * shib_auth_checker() -- a simple resource manager to
689 * process the .htaccess settings and copy attributes
690 * into the HTTP headers.
692 extern "C" int shib_auth_checker(request_rec* r)
695 (shib_dir_config*)ap_get_module_config(r->per_dir_config,&mod_shib);
697 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() executing");
699 // Regular access to arbitrary resource...check AuthType
700 const char* auth_type=ap_auth_type(r);
701 if (!auth_type || strcasecmp(auth_type,"shibboleth"))
704 ostringstream threadid;
705 threadid << "[" << getpid() << "] shibrm" << '\0';
706 saml::NDC ndc(threadid.str().c_str());
708 // We lock the configuration system for the duration.
709 IConfig* conf=g_Config->getINI();
712 const char* application_id=ap_table_get(r->headers_in,"Shib-Application-ID");
713 const IApplication* application=NULL;
715 application = conf->getApplication(application_id);
719 int m=r->method_number;
720 bool method_restricted=false;
723 const array_header* reqs_arr=ap_requires(r);
727 require_line* reqs=(require_line*)reqs_arr->elts;
729 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"REQUIRE nelts: %d", reqs_arr->nelts);
730 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"REQUIRE all: %d", dc->bRequireAll);
732 vector<bool> auth_OK(reqs_arr->nelts,false);
734 #define SHIB_AP_CHECK_IS_OK { \
735 if (dc->bRequireAll < 1) \
741 for (int x=0; x<reqs_arr->nelts; x++) {
743 if (!(reqs[x].method_mask & (1 << m)))
745 method_restricted=true;
747 t = reqs[x].requirement;
748 w = ap_getword_white(r->pool, &t);
750 if (!strcmp(w,"valid-user")) {
751 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting valid-user");
754 else if (!strcmp(w,"user") && SH_AP_USER(r)) {
757 w=ap_getword_conf(r->pool,&t);
765 // To do regex matching, we have to convert from UTF-8.
766 auto_ptr<XMLCh> trans(fromUTF8(w));
767 RegularExpression re(trans.get());
768 auto_ptr<XMLCh> trans2(fromUTF8(SH_AP_USER(r)));
769 if (re.matches(trans2.get())) {
770 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting user: %s",w);
774 catch (XMLException& ex) {
775 auto_ptr_char tmp(ex.getMessage());
776 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
777 "shib_auth_checker caught exception while parsing regular expression (%s): %s",w,tmp.get());
780 else if (!strcmp(SH_AP_USER(r),w)) {
781 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting user: %s",w);
786 else if (!strcmp(w,"group")) {
787 SH_AP_TABLE* grpstatus=NULL;
788 if (dc->szAuthGrpFile && SH_AP_USER(r)) {
789 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() using groups file: %s\n",dc->szAuthGrpFile);
790 grpstatus=groups_for_user(r,SH_AP_USER(r),dc->szAuthGrpFile);
796 w=ap_getword_conf(r->pool,&t);
797 if (ap_table_get(grpstatus,w)) {
798 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting group: %s",w);
804 Iterator<IAAP*> provs=application ? application->getAAPProviders() : EMPTY(IAAP*);
805 AAP wrapper(provs,w);
806 if (wrapper.fail()) {
807 ap_log_rerror(APLOG_MARK,APLOG_WARNING|APLOG_NOERRNO,SH_AP_R(r),
808 "shib_auth_checker() didn't recognize require rule: %s\n",w);
813 const char* vals=ap_table_get(r->headers_in,wrapper->getHeader());
815 w=ap_getword_conf(r->pool,&t);
822 auto_ptr<RegularExpression> re;
825 auto_ptr<XMLCh> trans(fromUTF8(w));
826 auto_ptr<RegularExpression> temp(new RegularExpression(trans.get()));
830 string vals_str(vals);
832 for (int i = 0; i < vals_str.length(); i++) {
833 if (vals_str.at(i) == ';') {
835 ap_log_rerror(APLOG_MARK,APLOG_WARNING|APLOG_NOERRNO,SH_AP_R(r),
836 "shib_auth_checker() invalid header encoding %s: starts with semicolon", vals);
840 if (vals_str.at(i-1) == '\\') {
841 vals_str.erase(i-1, 1);
846 string val = vals_str.substr(j, i-j);
849 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
850 if (re->matches(trans.get())) {
851 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
852 "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
857 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
858 "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
862 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
863 "shib_auth_checker() expecting %s, got %s: authorization not granted", w, val.c_str());
868 string val = vals_str.substr(j, vals_str.length()-j);
870 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
871 if (re->matches(trans.get())) {
872 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
873 "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
878 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
879 "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
883 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
884 "shib_auth_checker() expecting %s, got %s: authorization not granted", w, val.c_str());
887 catch (XMLException& ex) {
888 auto_ptr_char tmp(ex.getMessage());
889 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
890 "shib_auth_checker caught exception while parsing regular expression (%s): %s",w,tmp.get());
896 // check if all require directives are true
897 bool auth_all_OK = true;
898 for (int i= 0; i<reqs_arr->nelts; i++) {
899 auth_all_OK &= auth_OK[i];
904 if (!method_restricted)
907 if (!application_id) {
908 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
909 "shib_auth_checker: Shib-Application-ID header not found in request");
910 return HTTP_FORBIDDEN;
912 else if (!application) {
913 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
914 "shib_auth_checker: unable to map request to application settings, check configuration");
915 return HTTP_FORBIDDEN;
918 ShibMLP markupProcessor(application);
919 markupProcessor.insert("requestURL", ap_construct_url(r->pool,r->unparsed_uri,r));
920 return shib_error_page(r, application, "access", markupProcessor);
925 * Cleanup the (per-process) pool info.
927 #ifdef SHIB_APACHE_13
928 extern "C" void shib_exit(server_rec* s, SH_AP_POOL* p)
931 extern "C" apr_status_t shib_exit(void* data)
933 server_rec* s = NULL;
935 g_Config->shutdown();
937 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_exit() done");
938 #ifndef SHIB_APACHE_13
943 static const XMLCh Apache[] =
944 { chLatin_A, chLatin_p, chLatin_a, chLatin_c, chLatin_h, chLatin_e, chNull };
945 static const XMLCh apacheConfig[] =
946 { chLatin_a, chLatin_p, chLatin_a, chLatin_c, chLatin_h, chLatin_e,
947 chLatin_C, chLatin_o, chLatin_n, chLatin_f, chLatin_i, chLatin_g, chNull
949 static const XMLCh Implementation[] =
950 { chLatin_I, chLatin_m, chLatin_p, chLatin_l, chLatin_e, chLatin_m, chLatin_e, chLatin_n, chLatin_t, chLatin_a, chLatin_t, chLatin_i, chLatin_o, chLatin_n, chNull };
954 * Things to do when the child process is initialized.
955 * (or after the configs are read in apache-2)
957 #ifdef SHIB_APACHE_13
958 extern "C" void shib_child_init(server_rec* s, SH_AP_POOL* p)
960 extern "C" int shib_post_config(apr_pool_t* pconf, apr_pool_t* plog,
961 apr_pool_t* ptemp, server_rec* s)
964 // Initialize runtime components.
966 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() starting");
969 ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init(): already initialized!");
970 #ifdef SHIB_APACHE_13
978 g_Config=&ShibTargetConfig::getConfig();
979 g_Config->setFeatures(
980 ShibTargetConfig::Listener |
981 ShibTargetConfig::Metadata |
982 ShibTargetConfig::AAP |
983 ShibTargetConfig::RequestMapper |
984 ShibTargetConfig::SHIREExtensions
986 if (!g_Config->init(g_szSchemaDir,g_szSHIBConfig)) {
987 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init(): already initialized!");
991 // Access the implementation-specifics for whether to use old Apache config style...
992 IConfig* conf=g_Config->getINI();
994 const IPropertySet* props=conf->getPropertySet("SHIRE");
996 const DOMElement* impl=saml::XML::getFirstChildElement(
997 props->getElement(),ShibTargetConfig::SHIBTARGET_NS,Implementation
999 if (impl && (impl=saml::XML::getFirstChildElement(impl,ShibTargetConfig::SHIBTARGET_NS,Apache))) {
1000 const XMLCh* flag=impl->getAttributeNS(NULL,apacheConfig);
1001 if (flag && (*flag==chDigit_1 || *flag==chLatin_t))
1007 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize SHIB Target");
1011 // Set the cleanup handler
1012 apr_pool_cleanup_register(pconf, NULL, shib_exit, NULL);
1014 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),
1015 "shib_child_init() done, apacheConfig set to %s", g_bApacheConf ? "true" : "false");
1017 #ifndef SHIB_APACHE_13
1022 #ifdef SHIB_APACHE_13
1024 // SHIB Module commands
1026 static command_rec shire_cmds[] = {
1027 {"SHIREConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1028 RSRC_CONF, TAKE1, "Path to shibboleth.xml config file."},
1029 {"ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1030 RSRC_CONF, TAKE1, "Path to shibboleth.xml config file."},
1031 {"ShibSchemaDir", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1032 RSRC_CONF, TAKE1, "Path to Shibboleth XML schema directory."},
1034 {"ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1035 (void *) XtOffsetOf (shib_dir_config, bBasicHijack),
1036 OR_AUTHCFG, FLAG, "Respond to AuthType Basic and convert to shib?"},
1037 {"ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1038 (void *) XtOffsetOf (shib_dir_config, bRequireSession),
1039 OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist."},
1040 {"ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1041 (void *) XtOffsetOf (shib_dir_config, bExportAssertion),
1042 OR_AUTHCFG, FLAG, "Export SAML assertion to Shibboleth-defined header?"},
1043 {"AuthGroupFile", (config_fn_t)ap_set_file_slot,
1044 (void *) XtOffsetOf (shib_dir_config, szAuthGrpFile),
1045 OR_AUTHCFG, TAKE1, "text file containing group names and member user IDs"},
1046 {"ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1047 (void *) XtOffsetOf (shib_dir_config, bRequireAll),
1048 OR_AUTHCFG, FLAG, "All require directives must match!"},
1054 handler_rec shib_handlers[] = {
1055 { "shib-shire-post", shib_post_handler },
1059 module MODULE_VAR_EXPORT mod_shib = {
1060 STANDARD_MODULE_STUFF,
1061 NULL, /* initializer */
1062 create_shib_dir_config, /* dir config creater */
1063 merge_shib_dir_config, /* dir merger --- default is to override */
1064 NULL, /* server config */
1065 NULL, /* merge server config */
1066 shire_cmds, /* command table */
1067 shib_handlers, /* handlers */
1068 NULL, /* filename translation */
1069 shib_check_user, /* check_user_id */
1070 shib_auth_checker, /* check auth */
1071 NULL, /* check access */
1072 NULL, /* type_checker */
1075 NULL, /* header parser */
1076 shib_child_init, /* child_init */
1077 shib_exit, /* child_exit */
1078 NULL /* post read-request */
1081 #elif defined(SHIB_APACHE_20)
1083 extern "C" void shib_register_hooks (apr_pool_t *p)
1085 ap_hook_post_config(shib_post_config, NULL, NULL, APR_HOOK_MIDDLE);
1086 ap_hook_check_user_id(shib_check_user, NULL, NULL, APR_HOOK_MIDDLE);
1087 ap_hook_auth_checker(shib_auth_checker, NULL, NULL, APR_HOOK_FIRST);
1088 ap_hook_handler(shib_post_handler, NULL, NULL, APR_HOOK_LAST);
1091 // SHIB Module commands
1094 static command_rec shib_cmds[] = {
1095 AP_INIT_TAKE1("ShibConfig",
1096 (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1097 RSRC_CONF, "Path to shibboleth.xml config file."),
1098 AP_INIT_TAKE1("ShibSchemaDir",
1099 (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1100 RSRC_CONF, "Path to Shibboleth XML schema directory."),
1102 AP_INIT_FLAG("ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1103 (void *) offsetof (shib_dir_config, bBasicHijack),
1104 OR_AUTHCFG, "Respond to AuthType Basic and convert to shib?"),
1105 AP_INIT_FLAG("ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1106 (void *) offsetof (shib_dir_config, bRequireSession),
1107 OR_AUTHCFG, "Initiates a new session if one does not exist."),
1108 AP_INIT_FLAG("ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1109 (void *) offsetof (shib_dir_config, bExportAssertion),
1110 OR_AUTHCFG, "Export SAML assertion to Shibboleth-defined header?"),
1111 AP_INIT_TAKE1("AuthGroupFile", (config_fn_t)ap_set_file_slot,
1112 (void *) offsetof (shib_dir_config, szAuthGrpFile),
1113 OR_AUTHCFG, "text file containing group names and member user IDs"),
1114 AP_INIT_FLAG("ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1115 (void *) offsetof (shib_dir_config, bRequireAll),
1116 OR_AUTHCFG, "All require directives must match!"),
1121 module AP_MODULE_DECLARE_DATA mod_shib = {
1122 STANDARD20_MODULE_STUFF,
1123 create_shib_dir_config, /* create dir config */
1124 merge_shib_dir_config, /* merge dir config --- default is to override */
1125 NULL, /* create server config */
1126 NULL, /* merge server config */
1127 shib_cmds, /* command table */
1128 shib_register_hooks /* register hooks */
1132 #error "undefined APACHE version"