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 OK; // XXX: Or should this be DECLINED?
273 // Has to be OK because DECLINED will just cause Apache to fail when it can't locate
274 // anything to process the AuthType. No session plus requireSession false means
275 // do not authenticate the user.
276 else if (status->isRetryable()) {
277 // Oops, session is invalid. Generate AuthnRequest.
278 ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(targeturl)));
283 // return the error page to the user
284 markupProcessor.insert(*status);
286 return shib_error_page(r, application, "shire", markupProcessor);
292 #ifdef SHIB_APACHE_13
294 r->connection->ap_auth_type = "shibboleth";
296 r->ap_auth_type = "shibboleth";
298 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: session successfully verified");
300 // This is code transferred in from the auth check to export the attributes.
301 // We could even combine the isSessionValid/getAssertions API...?
304 vector<SAMLAssertion*> assertions;
305 SAMLAuthenticationStatement* sso_statement=NULL;
308 status = rm.getAssertions(session_id, r->connection->remote_ip, assertions, &sso_statement);
310 catch (ShibTargetException &e) {
311 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): %s", e.what());
312 markupProcessor.insert("errorType", "Attribute Processing Error");
313 markupProcessor.insert("errorText", e.what());
314 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
315 return shib_error_page(r, application, "rm", markupProcessor);
319 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): caught unexpected error");
320 markupProcessor.insert("errorType", "Attribute Processing Error");
321 markupProcessor.insert("errorText", "Unexpected Exception");
322 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
323 return shib_error_page(r, application, "rm", markupProcessor);
327 if (status->isError()) {
328 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
329 "shib_check_user() getAssertions failed: %s", status->getText());
331 markupProcessor.insert(*status);
333 return shib_error_page(r, application, "rm", markupProcessor);
337 // Do we have an access control plugin?
338 if (settings.second) {
339 Locker acllock(settings.second);
340 if (!settings.second->authorized(assertions)) {
341 for (int k = 0; k < assertions.size(); k++)
342 delete assertions[k];
343 delete sso_statement;
344 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): access control provider denied access");
345 return shib_error_page(r, application, "access", markupProcessor);
349 // Get the AAP providers, which contain the attribute policy info.
350 Iterator<IAAP*> provs=application->getAAPProviders();
352 // Clear out the list of mapped attributes
353 while (provs.hasNext()) {
354 IAAP* aap=provs.next();
357 Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
358 while (rules.hasNext()) {
359 const char* header=rules.next()->getHeader();
361 ap_table_unset(r->headers_in,header);
366 for (int k = 0; k < assertions.size(); k++)
367 delete assertions[k];
368 delete sso_statement;
369 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
370 "shib_check_user(): caught unexpected error while clearing headers");
371 markupProcessor.insert("errorType", "Attribute Processing Error");
372 markupProcessor.insert("errorText", "Unexpected Exception");
373 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
374 return shib_error_page(r, application, "rm", markupProcessor);
380 // Maybe export the first assertion.
381 ap_table_unset(r->headers_in,"Shib-Attributes");
382 pair<bool,bool> exp=pair<bool,bool>(false,false);
383 if (g_bApacheConf && dc->bExportAssertion==1)
384 exp.second=exp.first=true;
385 else if (!g_bApacheConf)
386 exp=settings.first->getBool("exportAssertion");
387 if (exp.first && exp.second && assertions.size()) {
389 RM::serialize(*(assertions[0]), assertion);
390 ap_table_set(r->headers_in,"Shib-Attributes", assertion.c_str());
393 // Export the SAML AuthnMethod and the origin site name.
394 ap_table_unset(r->headers_in,"Shib-Origin-Site");
395 ap_table_unset(r->headers_in,"Shib-Authentication-Method");
397 auto_ptr_char os(sso_statement->getSubject()->getNameQualifier());
398 auto_ptr_char am(sso_statement->getAuthMethod());
399 ap_table_set(r->headers_in,"Shib-Origin-Site", os.get());
400 ap_table_set(r->headers_in,"Shib-Authentication-Method", am.get());
403 ap_table_unset(r->headers_in,"Shib-Application-ID");
404 ap_table_set(r->headers_in,"Shib-Application-ID",application_id.second);
406 // Export the attributes.
407 Iterator<SAMLAssertion*> a_iter(assertions);
408 while (a_iter.hasNext()) {
409 SAMLAssertion* assert=a_iter.next();
410 Iterator<SAMLStatement*> statements=assert->getStatements();
411 while (statements.hasNext()) {
412 SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());
415 Iterator<SAMLAttribute*> attrs=astate->getAttributes();
416 while (attrs.hasNext()) {
417 SAMLAttribute* attr=attrs.next();
419 // Are we supposed to export it?
420 AAP wrapper(provs,attr->getName(),attr->getNamespace());
424 Iterator<string> vals=attr->getSingleByteValues();
425 if (!strcmp(wrapper->getHeader(),"REMOTE_USER") && vals.hasNext())
426 SH_AP_USER(r)=ap_pstrdup(r->pool,vals.next().c_str());
429 char* header = (char*)ap_table_get(r->headers_in, wrapper->getHeader());
431 header=ap_pstrdup(r->pool, header);
435 header = ap_pstrdup(r->pool, "");
436 for (; vals.hasNext(); it++) {
437 string value = vals.next();
438 for (string::size_type pos = value.find_first_of(";", string::size_type(0));
440 pos = value.find_first_of(";", pos)) {
441 value.insert(pos, "\\");
444 header=ap_pstrcat(r->pool, header, (it ? ";" : ""), value.c_str(), NULL);
446 ap_table_setn(r->headers_in, wrapper->getHeader(), header);
453 for (int k = 0; k < assertions.size(); k++)
454 delete assertions[k];
455 delete sso_statement;
460 extern "C" int shib_post_handler(request_rec* r)
462 #ifndef SHIB_APACHE_13
463 // With 2.x, this handler always runs, though last.
464 // We check if shib_check_user ran, because it will detect a SHIRE request
465 // and dispatch it directly.
467 apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
468 if (data==(const void*)42) {
469 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_post_handler skipped since check_user ran");
474 ostringstream threadid;
475 threadid << "[" << getpid() << "] shib_post_handler" << '\0';
476 saml::NDC ndc(threadid.str().c_str());
478 // We lock the configuration system for the duration.
479 IConfig* conf=g_Config->getINI();
482 // Map request to application and content settings.
483 IRequestMapper* mapper=conf->getRequestMapper();
484 Locker locker2(mapper);
485 IRequestMapper::Settings settings=mapper->getSettingsFromParsedURL(
486 ap_http_method(r), ap_get_server_name(r), ap_get_server_port(r), r->unparsed_uri
488 pair<bool,const char*> application_id=settings.first->getString("applicationId");
489 const IApplication* application=conf->getApplication(application_id.second);
490 const IPropertySet* sessionProps=application ? application->getPropertySet("Sessions") : NULL;
491 if (!application || !sessionProps) {
492 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
493 "shib_post_handler: unable to map request to application session settings, check configuration");
497 // Declare SHIRE object for this request.
498 SHIRE shire(application);
500 return shib_handler(r, application, sessionProps, shire);
503 int shib_handler(request_rec* r, const IApplication* application, const IPropertySet* sessionProps, SHIRE& shire)
506 const char* targeturl = ap_construct_url(r->pool,r->unparsed_uri,r);
508 // Make sure we only process the SHIRE requests.
509 if (!strstr(targeturl,shire.getShireURL(targeturl)))
512 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler() running");
514 pair<bool,const char*> shib_cookie=sessionProps->getString("cookieName");
515 pair<bool,const char*> shib_cookie_props=sessionProps->getString("cookieProps");
516 if (!shib_cookie.first) {
517 ap_log_rerror(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(r),
518 "shib_handler: no cookieName set for %s", application->getId());
522 ShibMLP markupProcessor(application);
523 markupProcessor.insert("requestURL", targeturl);
525 // Process SHIRE request
526 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() Beginning SHIRE processing");
529 pair<bool,bool> shireSSL=sessionProps->getBool("shireSSL");
531 // Make sure this is SSL, if it should be
532 if ((!shireSSL.first || shireSSL.second) && strcmp(ap_http_method(r),"https"))
533 throw ShibTargetException(SHIBRPC_OK, "blocked non-SSL access to session creation service");
535 // If this is a GET, we manufacture an AuthnRequest.
536 if (!strcasecmp(r->method,"GET")) {
537 const char* areq=r->args ? shire.getLazyAuthnRequest(r->args) : NULL;
539 throw ShibTargetException(SHIBRPC_OK, "malformed arguments to request a new session");
540 ap_table_setn(r->headers_out, "Location", ap_pstrdup(r->pool,areq));
543 else if (strcasecmp(r->method,"POST")) {
544 throw ShibTargetException(SHIBRPC_OK, "blocked non-POST to SHIRE POST processor");
547 // Sure sure this POST is an appropriate content type
548 const char *ct = ap_table_get(r->headers_in, "Content-type");
549 if (!ct || strcasecmp(ct, "application/x-www-form-urlencoded"))
550 throw ShibTargetException(SHIBRPC_OK,
551 ap_psprintf(r->pool, "blocked bad content-type to SHIRE POST processor: %s", (ct ? ct : "")));
553 // Read the posted data
554 if (ap_setup_client_block(r, REQUEST_CHUNKED_ERROR))
555 throw ShibTargetException(SHIBRPC_OK, "CGI setup_client_block failed");
556 if (!ap_should_client_block(r))
557 throw ShibTargetException(SHIBRPC_OK, "CGI should_client_block failed");
558 if (r->remaining > 1024*1024)
559 throw ShibTargetException (SHIBRPC_OK, "CGI length too long...");
562 char buff[HUGE_STRING_LEN];
563 ap_hard_timeout("[mod_shib] CGI Parser", r);
564 memset(buff, 0, sizeof(buff));
565 while (ap_get_client_block(r, buff, sizeof(buff)-1) > 0) {
567 memset(buff, 0, sizeof(buff));
571 // Parse the submission.
572 pair<const char*,const char*> elements=shire.getFormSubmission(cgistr.c_str(),cgistr.length());
574 // Make sure the SAML Response parameter exists
575 if (!elements.first || !*elements.first)
576 throw ShibTargetException(SHIBRPC_OK, "SHIRE POST failed to find SAMLResponse form element");
578 // Make sure the target parameter exists
579 if (!elements.second || !*elements.second)
580 throw ShibTargetException(SHIBRPC_OK, "SHIRE POST failed to find TARGET form element");
582 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
583 "shib_handler() Processing POST for target: %s", elements.second);
587 RPCError* status = shire.sessionCreate(elements.first, r->connection->remote_ip, cookie);
589 if (status->isError()) {
590 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
591 "shib_handler() POST process failed (%d): %s", status->getCode(), status->getText());
593 if (status->isRetryable()) {
595 ap_log_rerror(APLOG_MARK,APLOG_INFO|APLOG_NOERRNO,SH_AP_R(r),
596 "shib_handler() retryable error, generating new AuthnRequest");
597 ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(elements.second)));
601 // return this error to the user.
602 markupProcessor.insert(*status);
604 return shib_error_page(r, application, "shire", markupProcessor);
608 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
609 "shib_handler() POST process succeeded. New session: %s", cookie.c_str());
611 // We've got a good session, set the cookie...
612 char* val = ap_psprintf(r->pool,"%s=%s%s",shib_cookie.second,cookie.c_str(),
613 shib_cookie_props.first ? shib_cookie_props.second : "; path=/");
614 ap_table_setn(r->err_headers_out, "Set-Cookie", val);
615 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() setting cookie: %s", val);
617 // ... and redirect to the target
618 ap_table_setn(r->headers_out, "Location", ap_pstrdup(r->pool,elements.second));
621 catch (ShibTargetException &e) {
622 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() caught exception: %s", e.what());
623 markupProcessor.insert("errorType", "Session Creation Service Error");
624 markupProcessor.insert("errorText", e.what());
625 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
626 return shib_error_page(r, application, "shire", markupProcessor);
630 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler(): unexpected exception");
631 markupProcessor.insert("errorType", "Session Creation Service Error");
632 markupProcessor.insert("errorText", "Unknown Exception");
633 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
634 return shib_error_page(r, application, "shire", markupProcessor);
638 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_handler() server error");
642 static SH_AP_TABLE* groups_for_user(request_rec* r, const char* user, char* grpfile)
645 SH_AP_TABLE* grps=ap_make_table(r->pool,15);
646 char l[MAX_STRING_LEN];
647 const char *group_name, *ll, *w;
649 #ifdef SHIB_APACHE_13
650 if (!(f=ap_pcfg_openfile(r->pool,grpfile))) {
652 if (ap_pcfg_openfile(&f,r->pool,grpfile) != APR_SUCCESS) {
654 ap_log_rerror(APLOG_MARK,APLOG_DEBUG,SH_AP_R(r),"groups_for_user() could not open group file: %s\n",grpfile);
659 #ifdef SHIB_APACHE_13
660 sp=ap_make_sub_pool(r->pool);
662 if (apr_pool_create(&sp,r->pool) != APR_SUCCESS) {
663 ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,
664 "groups_for_user() could not create a subpool");
669 while (!(ap_cfg_getline(l,MAX_STRING_LEN,f))) {
670 if ((*l=='#') || (!*l))
675 group_name=ap_getword(sp,&ll,':');
678 w=ap_getword_conf(sp,&ll);
679 if (!strcmp(w,user)) {
680 ap_table_setn(grps,ap_pstrdup(r->pool,group_name),"in");
691 * shib_auth_checker() -- a simple resource manager to
692 * process the .htaccess settings and copy attributes
693 * into the HTTP headers.
695 extern "C" int shib_auth_checker(request_rec* r)
698 (shib_dir_config*)ap_get_module_config(r->per_dir_config,&mod_shib);
700 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() executing");
702 // Regular access to arbitrary resource...check AuthType
703 const char* auth_type=ap_auth_type(r);
704 if (!auth_type || strcasecmp(auth_type,"shibboleth"))
707 ostringstream threadid;
708 threadid << "[" << getpid() << "] shibrm" << '\0';
709 saml::NDC ndc(threadid.str().c_str());
711 // We lock the configuration system for the duration.
712 IConfig* conf=g_Config->getINI();
715 const char* application_id=ap_table_get(r->headers_in,"Shib-Application-ID");
716 const IApplication* application=NULL;
718 application = conf->getApplication(application_id);
722 int m=r->method_number;
723 bool method_restricted=false;
726 const array_header* reqs_arr=ap_requires(r);
730 require_line* reqs=(require_line*)reqs_arr->elts;
732 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"REQUIRE nelts: %d", reqs_arr->nelts);
733 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"REQUIRE all: %d", dc->bRequireAll);
735 vector<bool> auth_OK(reqs_arr->nelts,false);
737 #define SHIB_AP_CHECK_IS_OK { \
738 if (dc->bRequireAll < 1) \
744 for (int x=0; x<reqs_arr->nelts; x++) {
746 if (!(reqs[x].method_mask & (1 << m)))
748 method_restricted=true;
750 t = reqs[x].requirement;
751 w = ap_getword_white(r->pool, &t);
753 if (!strcasecmp(w,"Shibboleth")) {
754 // This is a dummy rule needed because Apache conflates authn and authz.
755 // Without some require rule, AuthType is ignored and no check_user hooks run.
758 else if (!strcmp(w,"valid-user") && application_id) {
759 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting valid-user");
762 else if (!strcmp(w,"user") && SH_AP_USER(r)) {
765 w=ap_getword_conf(r->pool,&t);
773 // To do regex matching, we have to convert from UTF-8.
774 auto_ptr<XMLCh> trans(fromUTF8(w));
775 RegularExpression re(trans.get());
776 auto_ptr<XMLCh> trans2(fromUTF8(SH_AP_USER(r)));
777 if (re.matches(trans2.get())) {
778 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting user: %s",w);
782 catch (XMLException& ex) {
783 auto_ptr_char tmp(ex.getMessage());
784 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
785 "shib_auth_checker caught exception while parsing regular expression (%s): %s",w,tmp.get());
788 else if (!strcmp(SH_AP_USER(r),w)) {
789 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting user: %s",w);
794 else if (!strcmp(w,"group")) {
795 SH_AP_TABLE* grpstatus=NULL;
796 if (dc->szAuthGrpFile && SH_AP_USER(r)) {
797 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() using groups file: %s\n",dc->szAuthGrpFile);
798 grpstatus=groups_for_user(r,SH_AP_USER(r),dc->szAuthGrpFile);
804 w=ap_getword_conf(r->pool,&t);
805 if (ap_table_get(grpstatus,w)) {
806 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting group: %s",w);
812 Iterator<IAAP*> provs=application ? application->getAAPProviders() : EMPTY(IAAP*);
813 AAP wrapper(provs,w);
814 if (wrapper.fail()) {
815 ap_log_rerror(APLOG_MARK,APLOG_WARNING|APLOG_NOERRNO,SH_AP_R(r),
816 "shib_auth_checker() didn't recognize require rule: %s\n",w);
821 const char* vals=ap_table_get(r->headers_in,wrapper->getHeader());
823 w=ap_getword_conf(r->pool,&t);
830 auto_ptr<RegularExpression> re;
833 auto_ptr<XMLCh> trans(fromUTF8(w));
834 auto_ptr<RegularExpression> temp(new RegularExpression(trans.get()));
838 string vals_str(vals);
840 for (int i = 0; i < vals_str.length(); i++) {
841 if (vals_str.at(i) == ';') {
843 ap_log_rerror(APLOG_MARK,APLOG_WARNING|APLOG_NOERRNO,SH_AP_R(r),
844 "shib_auth_checker() invalid header encoding %s: starts with semicolon", vals);
848 if (vals_str.at(i-1) == '\\') {
849 vals_str.erase(i-1, 1);
854 string val = vals_str.substr(j, i-j);
857 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
858 if (re->matches(trans.get())) {
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());
865 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
866 "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
870 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
871 "shib_auth_checker() expecting %s, got %s: authorization not granted", w, val.c_str());
876 string val = vals_str.substr(j, vals_str.length()-j);
878 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
879 if (re->matches(trans.get())) {
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());
886 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
887 "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
891 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
892 "shib_auth_checker() expecting %s, got %s: authorization not granted", w, val.c_str());
895 catch (XMLException& ex) {
896 auto_ptr_char tmp(ex.getMessage());
897 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
898 "shib_auth_checker caught exception while parsing regular expression (%s): %s",w,tmp.get());
904 // check if all require directives are true
905 bool auth_all_OK = true;
906 for (int i= 0; i<reqs_arr->nelts; i++) {
907 auth_all_OK &= auth_OK[i];
912 if (!method_restricted)
915 if (!application_id) {
916 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
917 "shib_auth_checker: Shib-Application-ID header not found in request");
918 return HTTP_FORBIDDEN;
920 else if (!application) {
921 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
922 "shib_auth_checker: unable to map request to application settings, check configuration");
923 return HTTP_FORBIDDEN;
926 ShibMLP markupProcessor(application);
927 markupProcessor.insert("requestURL", ap_construct_url(r->pool,r->unparsed_uri,r));
928 return shib_error_page(r, application, "access", markupProcessor);
933 * Cleanup the (per-process) pool info.
935 #ifdef SHIB_APACHE_13
936 extern "C" void shib_exit(server_rec* s, SH_AP_POOL* p)
939 extern "C" apr_status_t shib_exit(void* data)
941 server_rec* s = NULL;
943 g_Config->shutdown();
945 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_exit() done");
946 #ifndef SHIB_APACHE_13
951 static const XMLCh Apache[] =
952 { chLatin_A, chLatin_p, chLatin_a, chLatin_c, chLatin_h, chLatin_e, chNull };
953 static const XMLCh apacheConfig[] =
954 { chLatin_a, chLatin_p, chLatin_a, chLatin_c, chLatin_h, chLatin_e,
955 chLatin_C, chLatin_o, chLatin_n, chLatin_f, chLatin_i, chLatin_g, chNull
957 static const XMLCh Implementation[] =
958 { 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 };
962 * Things to do when the child process is initialized.
963 * (or after the configs are read in apache-2)
965 #ifdef SHIB_APACHE_13
966 extern "C" void shib_child_init(server_rec* s, SH_AP_POOL* p)
968 extern "C" int shib_post_config(apr_pool_t* pconf, apr_pool_t* plog,
969 apr_pool_t* ptemp, server_rec* s)
972 // Initialize runtime components.
974 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() starting");
977 ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init(): already initialized!");
978 #ifdef SHIB_APACHE_13
986 g_Config=&ShibTargetConfig::getConfig();
987 g_Config->setFeatures(
988 ShibTargetConfig::Listener |
989 ShibTargetConfig::Metadata |
990 ShibTargetConfig::AAP |
991 ShibTargetConfig::RequestMapper |
992 ShibTargetConfig::SHIREExtensions
994 if (!g_Config->init(g_szSchemaDir,g_szSHIBConfig)) {
995 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init(): already initialized!");
999 // Access the implementation-specifics for whether to use old Apache config style...
1000 IConfig* conf=g_Config->getINI();
1001 Locker locker(conf);
1002 const IPropertySet* props=conf->getPropertySet("SHIRE");
1004 const DOMElement* impl=saml::XML::getFirstChildElement(
1005 props->getElement(),ShibTargetConfig::SHIBTARGET_NS,Implementation
1007 if (impl && (impl=saml::XML::getFirstChildElement(impl,ShibTargetConfig::SHIBTARGET_NS,Apache))) {
1008 const XMLCh* flag=impl->getAttributeNS(NULL,apacheConfig);
1009 if (flag && (*flag==chDigit_1 || *flag==chLatin_t))
1015 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize SHIB Target");
1019 // Set the cleanup handler
1020 apr_pool_cleanup_register(pconf, NULL, shib_exit, NULL);
1022 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),
1023 "shib_child_init() done, apacheConfig set to %s", g_bApacheConf ? "true" : "false");
1025 #ifndef SHIB_APACHE_13
1030 #ifdef SHIB_APACHE_13
1032 // SHIB Module commands
1034 static command_rec shire_cmds[] = {
1035 {"SHIREConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1036 RSRC_CONF, TAKE1, "Path to shibboleth.xml config file."},
1037 {"ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1038 RSRC_CONF, TAKE1, "Path to shibboleth.xml config file."},
1039 {"ShibSchemaDir", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1040 RSRC_CONF, TAKE1, "Path to Shibboleth XML schema directory."},
1042 {"ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1043 (void *) XtOffsetOf (shib_dir_config, bBasicHijack),
1044 OR_AUTHCFG, FLAG, "Respond to AuthType Basic and convert to shib?"},
1045 {"ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1046 (void *) XtOffsetOf (shib_dir_config, bRequireSession),
1047 OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist."},
1048 {"ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1049 (void *) XtOffsetOf (shib_dir_config, bExportAssertion),
1050 OR_AUTHCFG, FLAG, "Export SAML assertion to Shibboleth-defined header?"},
1051 {"AuthGroupFile", (config_fn_t)ap_set_file_slot,
1052 (void *) XtOffsetOf (shib_dir_config, szAuthGrpFile),
1053 OR_AUTHCFG, TAKE1, "text file containing group names and member user IDs"},
1054 {"ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1055 (void *) XtOffsetOf (shib_dir_config, bRequireAll),
1056 OR_AUTHCFG, FLAG, "All require directives must match!"},
1062 handler_rec shib_handlers[] = {
1063 { "shib-shire-post", shib_post_handler },
1067 module MODULE_VAR_EXPORT mod_shib = {
1068 STANDARD_MODULE_STUFF,
1069 NULL, /* initializer */
1070 create_shib_dir_config, /* dir config creater */
1071 merge_shib_dir_config, /* dir merger --- default is to override */
1072 NULL, /* server config */
1073 NULL, /* merge server config */
1074 shire_cmds, /* command table */
1075 shib_handlers, /* handlers */
1076 NULL, /* filename translation */
1077 shib_check_user, /* check_user_id */
1078 shib_auth_checker, /* check auth */
1079 NULL, /* check access */
1080 NULL, /* type_checker */
1083 NULL, /* header parser */
1084 shib_child_init, /* child_init */
1085 shib_exit, /* child_exit */
1086 NULL /* post read-request */
1089 #elif defined(SHIB_APACHE_20)
1091 extern "C" void shib_register_hooks (apr_pool_t *p)
1093 ap_hook_post_config(shib_post_config, NULL, NULL, APR_HOOK_MIDDLE);
1094 ap_hook_check_user_id(shib_check_user, NULL, NULL, APR_HOOK_MIDDLE);
1095 ap_hook_auth_checker(shib_auth_checker, NULL, NULL, APR_HOOK_FIRST);
1096 ap_hook_handler(shib_post_handler, NULL, NULL, APR_HOOK_LAST);
1099 // SHIB Module commands
1102 static command_rec shib_cmds[] = {
1103 AP_INIT_TAKE1("ShibConfig",
1104 (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1105 RSRC_CONF, "Path to shibboleth.xml config file."),
1106 AP_INIT_TAKE1("ShibSchemaDir",
1107 (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1108 RSRC_CONF, "Path to Shibboleth XML schema directory."),
1110 AP_INIT_FLAG("ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1111 (void *) offsetof (shib_dir_config, bBasicHijack),
1112 OR_AUTHCFG, "Respond to AuthType Basic and convert to shib?"),
1113 AP_INIT_FLAG("ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1114 (void *) offsetof (shib_dir_config, bRequireSession),
1115 OR_AUTHCFG, "Initiates a new session if one does not exist."),
1116 AP_INIT_FLAG("ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1117 (void *) offsetof (shib_dir_config, bExportAssertion),
1118 OR_AUTHCFG, "Export SAML assertion to Shibboleth-defined header?"),
1119 AP_INIT_TAKE1("AuthGroupFile", (config_fn_t)ap_set_file_slot,
1120 (void *) offsetof (shib_dir_config, szAuthGrpFile),
1121 OR_AUTHCFG, "text file containing group names and member user IDs"),
1122 AP_INIT_FLAG("ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1123 (void *) offsetof (shib_dir_config, bRequireAll),
1124 OR_AUTHCFG, "All require directives must match!"),
1129 module AP_MODULE_DECLARE_DATA mod_shib = {
1130 STANDARD20_MODULE_STUFF,
1131 create_shib_dir_config, /* create dir config */
1132 merge_shib_dir_config, /* merge dir config --- default is to override */
1133 NULL, /* create server config */
1134 NULL, /* merge server config */
1135 shib_cmds, /* command table */
1136 shib_register_hooks /* register hooks */
1140 #error "undefined APACHE version"