2 * mod_apache.cpp -- the core Apache Module code
4 * Created by: Derek Atkins <derek@ihtfp.com>
10 #undef _XOPEN_SOURCE // causes gethostname conflict in unistd.h
14 #include <saml/saml.h>
15 #include <shib/shib.h>
16 #include <shib/shib-threads.h>
17 #include <shib-target/shib-target.h>
18 #include <xercesc/util/regx/RegularExpression.hpp>
22 // Apache specific header files
24 #include <http_config.h>
25 #include <http_protocol.h>
26 #include <http_main.h>
28 #include <http_core.h>
31 #ifndef SHIB_APACHE_13
32 #include <http_request.h>
33 #include <apr_strings.h>
34 #include <apr_pools.h>
41 #include <unistd.h> // for getpid()
46 using namespace shibboleth;
47 using namespace shibtarget;
49 extern "C" module MODULE_VAR_EXPORT mod_shib;
50 int shib_handler(request_rec* r, const IApplication* application, SHIRE& shire);
53 char* g_szSHIBConfig = NULL;
54 char* g_szSchemaDir = NULL;
55 ShibTargetConfig* g_Config = NULL;
56 static const char* g_UserDataKey = "_shib_check_user_";
59 // per-server module configuration structure
60 struct shib_server_config
65 // creates the per-server configuration
66 extern "C" void* create_shib_server_config(SH_AP_POOL* p, server_rec* s)
68 shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
73 // overrides server configuration in virtual servers
74 extern "C" void* merge_shib_server_config (SH_AP_POOL* p, void* base, void* sub)
76 shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
77 shib_server_config* parent=(shib_server_config*)base;
78 shib_server_config* child=(shib_server_config*)sub;
81 sc->szScheme=ap_pstrdup(p,child->szScheme);
82 else if (parent->szScheme)
83 sc->szScheme=ap_pstrdup(p,parent->szScheme);
90 // per-dir module configuration structure
91 struct shib_dir_config
94 char* szAuthGrpFile; // Auth GroupFile name
95 int bRequireAll; // all require directives must match, otherwise OR logic
97 // SHIRE Configuration
98 int bBasicHijack; // activate for AuthType Basic?
99 int bRequireSession; // require a session?
100 int bExportAssertion; // export SAML assertion to the environment?
103 // creates per-directory config structure
104 extern "C" void* create_shib_dir_config (SH_AP_POOL* p, char* d)
106 shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
107 dc->bBasicHijack = -1;
108 dc->bRequireSession = -1;
109 dc->bExportAssertion = -1;
110 dc->bRequireAll = -1;
111 dc->szAuthGrpFile = NULL;
115 // overrides server configuration in directories
116 extern "C" void* merge_shib_dir_config (SH_AP_POOL* p, void* base, void* sub)
118 shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
119 shib_dir_config* parent=(shib_dir_config*)base;
120 shib_dir_config* child=(shib_dir_config*)sub;
122 if (child->szAuthGrpFile)
123 dc->szAuthGrpFile=ap_pstrdup(p,child->szAuthGrpFile);
124 else if (parent->szAuthGrpFile)
125 dc->szAuthGrpFile=ap_pstrdup(p,parent->szAuthGrpFile);
127 dc->szAuthGrpFile=NULL;
129 dc->bBasicHijack=((child->bBasicHijack==-1) ? parent->bBasicHijack : child->bBasicHijack);
130 dc->bRequireSession=((child->bRequireSession==-1) ? parent->bRequireSession : child->bRequireSession);
131 dc->bExportAssertion=((child->bExportAssertion==-1) ? parent->bExportAssertion : child->bExportAssertion);
132 dc->bRequireAll=((child->bRequireAll==-1) ? parent->bRequireAll : child->bRequireAll);
136 // generic global slot handlers
137 extern "C" const char* ap_set_global_string_slot(cmd_parms* parms, void*, const char* arg)
139 *((char**)(parms->info))=ap_pstrdup(parms->pool,arg);
143 extern "C" const char* shib_set_server_string_slot(cmd_parms* parms, void*, const char* arg)
145 char* base=(char*)ap_get_module_config(parms->server->module_config,&mod_shib);
146 int offset=(int)parms->info;
147 *((char**)(base + offset))=ap_pstrdup(parms->pool,arg);
151 typedef const char* (*config_fn_t)(void);
153 static int shib_error_page(request_rec* r, const IApplication* app, const char* page, ShibMLP& mlp)
155 const IPropertySet* props=app->getPropertySet("Errors");
157 pair<bool,const char*> p=props->getString(page);
159 ifstream infile(p.second);
160 if (!infile.fail()) {
161 const char* res = mlp.run(infile,props);
163 r->content_type = ap_psprintf(r->pool, "text/html");
164 ap_send_http_header(r);
172 ap_log_rerror(APLOG_MARK,APLOG_ERR,SH_AP_R(r),
173 "shib_error_page() could not process shire error template for application %s",app->getId());
177 static char* shib_get_targeturl(request_rec* r, const char* scheme=NULL)
179 // On 1.3, this is always canonical, but on 2.0, UseCanonicalName comes into play.
180 // However, we also have a setting to forcibly replace the scheme for esoteric cases.
182 unsigned port = ap_get_server_port(r);
183 if ((!strcmp(scheme,"http") && port==80) || (!strcmp(scheme,"https") && port==443)) {
184 return ap_pstrcat(r->pool, scheme, "://", ap_get_server_name(r), r->unparsed_uri, NULL);
186 return ap_psprintf(r->pool, "%s://%s:%u%s", scheme, ap_get_server_name(r), port, r->unparsed_uri);
188 return ap_construct_url(r->pool,r->unparsed_uri,r);
191 extern "C" int shib_check_user(request_rec* r)
193 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: ENTER");
194 shib_dir_config* dc=(shib_dir_config*)ap_get_module_config(r->per_dir_config,&mod_shib);
195 shib_server_config* sc=(shib_server_config*)ap_get_module_config(r->server->module_config,&mod_shib);
197 ostringstream threadid;
198 threadid << "[" << getpid() << "] shib_check_user" << '\0';
199 saml::NDC ndc(threadid.str().c_str());
201 const char* targeturl=shib_get_targeturl(r,sc->szScheme);
203 // We lock the configuration system for the duration.
204 IConfig* conf=g_Config->getINI();
207 // Map request to application and content settings.
208 IRequestMapper* mapper=conf->getRequestMapper();
209 Locker locker2(mapper);
210 IRequestMapper::Settings settings=mapper->getSettingsFromParsedURL(
211 (sc-> szScheme ? sc-> szScheme : ap_http_method(r)), ap_get_server_name(r), ap_get_server_port(r), r->unparsed_uri
213 pair<bool,const char*> application_id=settings.first->getString("applicationId");
214 const IApplication* application=conf->getApplication(application_id.second);
216 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
217 "shib_check_user: unable to map request to application settings, check configuration");
221 // Declare SHIRE object for this request.
222 SHIRE shire(application);
224 // Get location of this application's assertion consumer service and see if this is it.
225 if (strstr(targeturl,shire.getShireURL(targeturl))) {
226 return shib_handler(r,application,shire);
229 // We can short circuit the handler if we run this...
230 apr_pool_userdata_setn((const void*)42,g_UserDataKey,NULL,r->pool);
232 // Regular access to arbitrary resource...check AuthType
233 const char *auth_type=ap_auth_type(r);
237 if (strcasecmp(auth_type,"shibboleth")) {
238 if (!strcasecmp(auth_type,"basic") && dc->bBasicHijack==1) {
239 core_dir_config* conf=
240 (core_dir_config*)ap_get_module_config(r->per_dir_config,
241 ap_find_linked_module("http_core.c"));
242 conf->ap_auth_type="shibboleth";
248 pair<bool,bool> requireSession = settings.first->getBool("requireSession");
249 if (!requireSession.first || !requireSession.second)
250 if (dc->bRequireSession==1)
251 requireSession.second=true;
253 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: session check for %s",targeturl);
255 pair<const char*,const char*> shib_cookie=shire.getCookieNameProps(); // always returns *something*
257 // We're in charge, so check for cookie.
258 const char* session_id=NULL;
259 const char* cookies=ap_table_get(r->headers_in,"Cookie");
262 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: cookies found: %s",cookies);
263 if (session_id=strstr(cookies,shib_cookie.first)) {
264 // Yep, we found a cookie -- pull it out (our session_id)
265 session_id+=strlen(shib_cookie.first) + 1; /* Skip over the '=' */
266 char* cookiebuf = ap_pstrdup(r->pool,session_id);
267 char* cookieend = strchr(cookiebuf,';');
269 *cookieend = '\0'; /* Ignore anyting after a ; */
270 session_id=cookiebuf;
274 if (!session_id || !*session_id) {
275 // If no session required, bail now.
276 if (!requireSession.second)
279 // No acceptable cookie, and we require a session. Generate an AuthnRequest.
280 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: no cookie found -- redirecting to WAYF");
281 ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(targeturl)));
285 // Make sure this session is still valid.
286 RPCError* status = NULL;
287 ShibMLP markupProcessor;
288 markupProcessor.insert("requestURL", targeturl);
291 status = shire.sessionIsValid(session_id, r->connection->remote_ip);
293 catch (ShibTargetException &e) {
294 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): %s", e.what());
295 markupProcessor.insert("errorType", "Session Processing Error");
296 markupProcessor.insert("errorText", e.what());
297 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
298 return shib_error_page(r, application, "shire", markupProcessor);
302 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): caught unexpected error");
303 markupProcessor.insert("errorType", "Session Processing Error");
304 markupProcessor.insert("errorText", "Unexpected Exception");
305 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
306 return shib_error_page(r, application, "shire", markupProcessor);
311 if (status->isError()) {
312 ap_log_rerror(APLOG_MARK,APLOG_INFO|APLOG_NOERRNO,SH_AP_R(r),
313 "shib_check_user() session invalid: %s", status->getText());
315 // If no session required, bail now.
316 if (!requireSession.second)
317 return OK; // XXX: Or should this be DECLINED?
318 // Has to be OK because DECLINED will just cause Apache to fail when it can't locate
319 // anything to process the AuthType. No session plus requireSession false means
320 // do not authenticate the user.
321 else if (status->isRetryable()) {
322 // Oops, session is invalid. Generate AuthnRequest.
323 ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(targeturl)));
328 // return the error page to the user
329 markupProcessor.insert(*status);
331 return shib_error_page(r, application, "shire", markupProcessor);
337 #ifdef SHIB_APACHE_13
339 r->connection->ap_auth_type = "shibboleth";
341 r->ap_auth_type = "shibboleth";
343 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: session successfully verified");
345 // This is code transferred in from the auth check to export the attributes.
346 // We could even combine the isSessionValid/getAssertions API...?
349 vector<SAMLAssertion*> assertions;
350 SAMLAuthenticationStatement* sso_statement=NULL;
353 status = rm.getAssertions(session_id, r->connection->remote_ip, assertions, &sso_statement);
355 catch (ShibTargetException &e) {
356 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): %s", e.what());
357 markupProcessor.insert("errorType", "Attribute Processing Error");
358 markupProcessor.insert("errorText", e.what());
359 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
360 return shib_error_page(r, application, "rm", markupProcessor);
364 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): caught unexpected error");
365 markupProcessor.insert("errorType", "Attribute Processing Error");
366 markupProcessor.insert("errorText", "Unexpected Exception");
367 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
368 return shib_error_page(r, application, "rm", markupProcessor);
372 if (status->isError()) {
373 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
374 "shib_check_user() getAssertions failed: %s", status->getText());
376 markupProcessor.insert(*status);
378 return shib_error_page(r, application, "rm", markupProcessor);
382 // Do we have an access control plugin?
383 if (settings.second) {
384 Locker acllock(settings.second);
385 if (!settings.second->authorized(*sso_statement,assertions)) {
386 for (int k = 0; k < assertions.size(); k++)
387 delete assertions[k];
388 delete sso_statement;
389 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): access control provider denied access");
390 return shib_error_page(r, application, "access", markupProcessor);
394 // Get the AAP providers, which contain the attribute policy info.
395 Iterator<IAAP*> provs=application->getAAPProviders();
397 // Clear out the list of mapped attributes
398 while (provs.hasNext()) {
399 IAAP* aap=provs.next();
402 Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
403 while (rules.hasNext()) {
404 const char* header=rules.next()->getHeader();
406 ap_table_unset(r->headers_in,header);
411 for (int k = 0; k < assertions.size(); k++)
412 delete assertions[k];
413 delete sso_statement;
414 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
415 "shib_check_user(): caught unexpected error while clearing headers");
416 markupProcessor.insert("errorType", "Attribute Processing Error");
417 markupProcessor.insert("errorText", "Unexpected Exception");
418 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
419 return shib_error_page(r, application, "rm", markupProcessor);
425 // Maybe export the first assertion.
426 ap_table_unset(r->headers_in,"Shib-Attributes");
427 pair<bool,bool> exp=settings.first->getBool("exportAssertion");
428 if (!exp.first || !exp.second)
429 if (dc->bExportAssertion==1)
431 if (exp.second && assertions.size()) {
433 RM::serialize(*(assertions[0]), assertion);
434 ap_table_set(r->headers_in,"Shib-Attributes", assertion.c_str());
437 // Export the SAML AuthnMethod and the origin site name, and possibly the NameIdentifier.
438 ap_table_unset(r->headers_in,"Shib-Origin-Site");
439 ap_table_unset(r->headers_in,"Shib-Authentication-Method");
440 ap_table_unset(r->headers_in,"Shib-NameIdentifier-Format");
441 auto_ptr_char os(sso_statement->getSubject()->getNameIdentifier()->getNameQualifier());
442 auto_ptr_char am(sso_statement->getAuthMethod());
443 ap_table_set(r->headers_in,"Shib-Origin-Site", os.get());
444 ap_table_set(r->headers_in,"Shib-Authentication-Method", am.get());
447 AAP wrapper(provs,sso_statement->getSubject()->getNameIdentifier()->getFormat(),Constants::SHIB_ATTRIBUTE_NAMESPACE_URI);
448 if (!wrapper.fail() && wrapper->getHeader()) {
449 auto_ptr_char form(sso_statement->getSubject()->getNameIdentifier()->getFormat());
450 auto_ptr_char nameid(sso_statement->getSubject()->getNameIdentifier()->getName());
451 ap_table_set(r->headers_in,"Shib-NameIdentifier-Format",form.get());
452 if (!strcmp(wrapper->getHeader(),"REMOTE_USER"))
453 SH_AP_USER(r)=ap_pstrdup(r->pool,nameid.get());
455 ap_table_set(r->headers_in,wrapper->getHeader(),nameid.get());
458 ap_table_unset(r->headers_in,"Shib-Application-ID");
459 ap_table_set(r->headers_in,"Shib-Application-ID",application_id.second);
461 // Export the attributes.
462 Iterator<SAMLAssertion*> a_iter(assertions);
463 while (a_iter.hasNext()) {
464 SAMLAssertion* assert=a_iter.next();
465 Iterator<SAMLStatement*> statements=assert->getStatements();
466 while (statements.hasNext()) {
467 SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());
470 Iterator<SAMLAttribute*> attrs=astate->getAttributes();
471 while (attrs.hasNext()) {
472 SAMLAttribute* attr=attrs.next();
474 // Are we supposed to export it?
475 AAP wrapper(provs,attr->getName(),attr->getNamespace());
476 if (wrapper.fail() || !wrapper->getHeader())
479 Iterator<string> vals=attr->getSingleByteValues();
480 if (!strcmp(wrapper->getHeader(),"REMOTE_USER") && vals.hasNext())
481 SH_AP_USER(r)=ap_pstrdup(r->pool,vals.next().c_str());
484 char* header = (char*)ap_table_get(r->headers_in, wrapper->getHeader());
486 header=ap_pstrdup(r->pool, header);
490 header = ap_pstrdup(r->pool, "");
491 for (; vals.hasNext(); it++) {
492 string value = vals.next();
493 for (string::size_type pos = value.find_first_of(";", string::size_type(0));
495 pos = value.find_first_of(";", pos)) {
496 value.insert(pos, "\\");
499 header=ap_pstrcat(r->pool, header, (it ? ";" : ""), value.c_str(), NULL);
501 ap_table_setn(r->headers_in, wrapper->getHeader(), header);
508 for (int k = 0; k < assertions.size(); k++)
509 delete assertions[k];
510 delete sso_statement;
515 extern "C" int shib_post_handler(request_rec* r)
517 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
518 "shib_post_handler(%d): ENTER", (int)getpid());
519 shib_server_config* sc=(shib_server_config*)ap_get_module_config(r->server->module_config,&mod_shib);
521 #ifndef SHIB_APACHE_13
522 // With 2.x, this handler always runs, though last.
523 // We check if shib_check_user ran, because it will detect a SHIRE request
524 // and dispatch it directly.
526 apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
527 if (data==(const void*)42) {
528 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_post_handler skipped since check_user ran");
533 ostringstream threadid;
534 threadid << "[" << getpid() << "] shib_post_handler" << '\0';
535 saml::NDC ndc(threadid.str().c_str());
537 // We lock the configuration system for the duration.
538 IConfig* conf=g_Config->getINI();
541 // Map request to application and content settings.
542 IRequestMapper* mapper=conf->getRequestMapper();
543 Locker locker2(mapper);
544 IRequestMapper::Settings settings=mapper->getSettingsFromParsedURL(
545 (sc->szScheme ? sc->szScheme : ap_http_method(r)), ap_get_server_name(r), ap_get_server_port(r), r->unparsed_uri
547 pair<bool,const char*> application_id=settings.first->getString("applicationId");
548 const IApplication* application=conf->getApplication(application_id.second);
550 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
551 "shib_post_handler: unable to map request to application settings, check configuration");
555 // Declare SHIRE object for this request.
556 SHIRE shire(application);
558 return shib_handler(r, application, shire);
561 int shib_handler(request_rec* r, const IApplication* application, SHIRE& shire)
563 shib_server_config* sc=(shib_server_config*)ap_get_module_config(r->server->module_config,&mod_shib);
565 const char* targeturl=shib_get_targeturl(r,sc->szScheme);
567 // Make sure we only process the SHIRE requests.
568 if (!strstr(targeturl,shire.getShireURL(targeturl)))
571 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler() running");
573 const IPropertySet* sessionProps=application->getPropertySet("Sessions");
575 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
576 "shib_post_handler: unable to map request to application session settings, check configuration");
580 pair<const char*,const char*> shib_cookie=shire.getCookieNameProps(); // always returns something
582 ShibMLP markupProcessor;
583 markupProcessor.insert("requestURL", targeturl);
585 // Process SHIRE request
586 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() Beginning SHIRE processing");
589 pair<bool,bool> shireSSL=sessionProps->getBool("shireSSL");
591 // Make sure this is SSL, if it should be
592 if ((!shireSSL.first || shireSSL.second) && strcmp(ap_http_method(r),"https"))
593 throw ShibTargetException(SHIBRPC_OK, "blocked non-SSL access to session creation service");
595 // If this is a GET, we manufacture an AuthnRequest.
596 if (!strcasecmp(r->method,"GET")) {
597 const char* areq=r->args ? shire.getLazyAuthnRequest(r->args) : NULL;
599 throw ShibTargetException(SHIBRPC_OK, "malformed arguments to request a new session");
600 ap_table_setn(r->headers_out, "Location", ap_pstrdup(r->pool,areq));
603 else if (strcasecmp(r->method,"POST")) {
604 throw ShibTargetException(SHIBRPC_OK, "blocked non-POST to SHIRE POST processor");
607 // Sure sure this POST is an appropriate content type
608 const char *ct = ap_table_get(r->headers_in, "Content-type");
609 if (!ct || strcasecmp(ct, "application/x-www-form-urlencoded"))
610 throw ShibTargetException(SHIBRPC_OK,
611 ap_psprintf(r->pool, "blocked bad content-type to SHIRE POST processor: %s", (ct ? ct : "")));
613 // Read the posted data
614 if (ap_setup_client_block(r, REQUEST_CHUNKED_ERROR))
615 throw ShibTargetException(SHIBRPC_OK, "CGI setup_client_block failed");
616 if (!ap_should_client_block(r))
617 throw ShibTargetException(SHIBRPC_OK, "CGI should_client_block failed");
618 if (r->remaining > 1024*1024)
619 throw ShibTargetException (SHIBRPC_OK, "CGI length too long...");
622 char buff[HUGE_STRING_LEN];
623 ap_hard_timeout("[mod_shib] CGI Parser", r);
624 memset(buff, 0, sizeof(buff));
625 while (ap_get_client_block(r, buff, sizeof(buff)-1) > 0) {
627 memset(buff, 0, sizeof(buff));
631 // Parse the submission.
632 pair<const char*,const char*> elements=shire.getFormSubmission(cgistr.c_str(),cgistr.length());
634 // Make sure the SAML Response parameter exists
635 if (!elements.first || !*elements.first)
636 throw ShibTargetException(SHIBRPC_OK, "SHIRE POST failed to find SAMLResponse form element");
638 // Make sure the target parameter exists
639 if (!elements.second || !*elements.second)
640 throw ShibTargetException(SHIBRPC_OK, "SHIRE POST failed to find TARGET form element");
642 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
643 "shib_handler() Processing POST for target: %s", elements.second);
647 RPCError* status = shire.sessionCreate(elements.first, r->connection->remote_ip, cookie);
649 if (status->isError()) {
650 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
651 "shib_handler() POST process failed (%d): %s", status->getCode(), status->getText());
653 if (status->isRetryable()) {
655 ap_log_rerror(APLOG_MARK,APLOG_INFO|APLOG_NOERRNO,SH_AP_R(r),
656 "shib_handler() retryable error, generating new AuthnRequest");
657 ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(elements.second)));
661 // return this error to the user.
662 markupProcessor.insert(*status);
664 return shib_error_page(r, application, "shire", markupProcessor);
668 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
669 "shib_handler() POST process succeeded. New session: %s", cookie.c_str());
671 // We've got a good session, set the cookie...
672 char* val = ap_psprintf(r->pool,"%s=%s%s",shib_cookie.first,cookie.c_str(),shib_cookie.second);
673 ap_table_setn(r->err_headers_out, "Set-Cookie", val);
674 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() setting cookie: %s", val);
676 // ... and redirect to the target
677 ap_table_setn(r->headers_out, "Location", ap_pstrdup(r->pool,elements.second));
680 catch (ShibTargetException &e) {
681 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() caught exception: %s", e.what());
682 markupProcessor.insert("errorType", "Session Creation Service Error");
683 markupProcessor.insert("errorText", e.what());
684 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
685 return shib_error_page(r, application, "shire", markupProcessor);
689 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler(): unexpected exception");
690 markupProcessor.insert("errorType", "Session Creation Service Error");
691 markupProcessor.insert("errorText", "Unknown Exception");
692 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
693 return shib_error_page(r, application, "shire", markupProcessor);
697 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_handler() server error");
701 static SH_AP_TABLE* groups_for_user(request_rec* r, const char* user, char* grpfile)
704 SH_AP_TABLE* grps=ap_make_table(r->pool,15);
705 char l[MAX_STRING_LEN];
706 const char *group_name, *ll, *w;
708 #ifdef SHIB_APACHE_13
709 if (!(f=ap_pcfg_openfile(r->pool,grpfile))) {
711 if (ap_pcfg_openfile(&f,r->pool,grpfile) != APR_SUCCESS) {
713 ap_log_rerror(APLOG_MARK,APLOG_DEBUG,SH_AP_R(r),"groups_for_user() could not open group file: %s\n",grpfile);
718 #ifdef SHIB_APACHE_13
719 sp=ap_make_sub_pool(r->pool);
721 if (apr_pool_create(&sp,r->pool) != APR_SUCCESS) {
722 ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,
723 "groups_for_user() could not create a subpool");
728 while (!(ap_cfg_getline(l,MAX_STRING_LEN,f))) {
729 if ((*l=='#') || (!*l))
734 group_name=ap_getword(sp,&ll,':');
737 w=ap_getword_conf(sp,&ll);
738 if (!strcmp(w,user)) {
739 ap_table_setn(grps,ap_pstrdup(r->pool,group_name),"in");
750 * shib_auth_checker() -- a simple resource manager to
751 * process the .htaccess settings and copy attributes
752 * into the HTTP headers.
754 extern "C" int shib_auth_checker(request_rec* r)
757 (shib_dir_config*)ap_get_module_config(r->per_dir_config,&mod_shib);
759 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() executing");
761 // Regular access to arbitrary resource...check AuthType
762 const char* auth_type=ap_auth_type(r);
763 if (!auth_type || strcasecmp(auth_type,"shibboleth"))
766 ostringstream threadid;
767 threadid << "[" << getpid() << "] shibrm" << '\0';
768 saml::NDC ndc(threadid.str().c_str());
770 // We lock the configuration system for the duration.
771 IConfig* conf=g_Config->getINI();
774 const char* application_id=ap_table_get(r->headers_in,"Shib-Application-ID");
775 const IApplication* application=NULL;
777 application = conf->getApplication(application_id);
781 int m=r->method_number;
782 bool method_restricted=false;
785 const array_header* reqs_arr=ap_requires(r);
789 require_line* reqs=(require_line*)reqs_arr->elts;
791 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"REQUIRE nelts: %d", reqs_arr->nelts);
792 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"REQUIRE all: %d", dc->bRequireAll);
794 vector<bool> auth_OK(reqs_arr->nelts,false);
796 #define SHIB_AP_CHECK_IS_OK { \
797 if (dc->bRequireAll < 1) \
803 for (int x=0; x<reqs_arr->nelts; x++) {
805 if (!(reqs[x].method_mask & (1 << m)))
807 method_restricted=true;
809 t = reqs[x].requirement;
810 w = ap_getword_white(r->pool, &t);
812 if (!strcasecmp(w,"Shibboleth")) {
813 // This is a dummy rule needed because Apache conflates authn and authz.
814 // Without some require rule, AuthType is ignored and no check_user hooks run.
817 else if (!strcmp(w,"valid-user") && application_id) {
818 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting valid-user");
821 else if (!strcmp(w,"user") && SH_AP_USER(r)) {
824 w=ap_getword_conf(r->pool,&t);
832 // To do regex matching, we have to convert from UTF-8.
833 auto_ptr<XMLCh> trans(fromUTF8(w));
834 RegularExpression re(trans.get());
835 auto_ptr<XMLCh> trans2(fromUTF8(SH_AP_USER(r)));
836 if (re.matches(trans2.get())) {
837 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting user: %s",w);
841 catch (XMLException& ex) {
842 auto_ptr_char tmp(ex.getMessage());
843 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
844 "shib_auth_checker caught exception while parsing regular expression (%s): %s",w,tmp.get());
847 else if (!strcmp(SH_AP_USER(r),w)) {
848 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting user: %s",w);
853 else if (!strcmp(w,"group")) {
854 SH_AP_TABLE* grpstatus=NULL;
855 if (dc->szAuthGrpFile && SH_AP_USER(r)) {
856 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() using groups file: %s\n",dc->szAuthGrpFile);
857 grpstatus=groups_for_user(r,SH_AP_USER(r),dc->szAuthGrpFile);
863 w=ap_getword_conf(r->pool,&t);
864 if (ap_table_get(grpstatus,w)) {
865 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting group: %s",w);
871 Iterator<IAAP*> provs=application ? application->getAAPProviders() : EMPTY(IAAP*);
872 AAP wrapper(provs,w);
873 if (wrapper.fail()) {
874 ap_log_rerror(APLOG_MARK,APLOG_WARNING|APLOG_NOERRNO,SH_AP_R(r),
875 "shib_auth_checker() didn't recognize require rule: %s\n",w);
880 const char* vals=ap_table_get(r->headers_in,wrapper->getHeader());
882 w=ap_getword_conf(r->pool,&t);
889 auto_ptr<RegularExpression> re;
892 auto_ptr<XMLCh> trans(fromUTF8(w));
893 auto_ptr<RegularExpression> temp(new RegularExpression(trans.get()));
897 string vals_str(vals);
899 for (int i = 0; i < vals_str.length(); i++) {
900 if (vals_str.at(i) == ';') {
902 ap_log_rerror(APLOG_MARK,APLOG_WARNING|APLOG_NOERRNO,SH_AP_R(r),
903 "shib_auth_checker() invalid header encoding %s: starts with semicolon", vals);
907 if (vals_str.at(i-1) == '\\') {
908 vals_str.erase(i-1, 1);
913 string val = vals_str.substr(j, i-j);
916 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
917 if (re->matches(trans.get())) {
918 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
919 "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
924 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
925 "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
929 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
930 "shib_auth_checker() expecting %s, got %s: authorization not granted", w, val.c_str());
935 string val = vals_str.substr(j, vals_str.length()-j);
937 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
938 if (re->matches(trans.get())) {
939 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
940 "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
945 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
946 "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
950 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
951 "shib_auth_checker() expecting %s, got %s: authorization not granted", w, val.c_str());
954 catch (XMLException& ex) {
955 auto_ptr_char tmp(ex.getMessage());
956 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
957 "shib_auth_checker caught exception while parsing regular expression (%s): %s",w,tmp.get());
963 // check if all require directives are true
964 bool auth_all_OK = true;
965 for (int i= 0; i<reqs_arr->nelts; i++) {
966 auth_all_OK &= auth_OK[i];
971 if (!method_restricted)
974 if (!application_id) {
975 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
976 "shib_auth_checker: Shib-Application-ID header not found in request");
977 return HTTP_FORBIDDEN;
979 else if (!application) {
980 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
981 "shib_auth_checker: unable to map request to application settings, check configuration");
982 return HTTP_FORBIDDEN;
985 ShibMLP markupProcessor;
986 markupProcessor.insert("requestURL", ap_construct_url(r->pool,r->unparsed_uri,r));
987 return shib_error_page(r, application, "access", markupProcessor);
992 * Cleanup the (per-process) pool info.
994 #ifdef SHIB_APACHE_13
995 extern "C" void shib_exit(server_rec* s, SH_AP_POOL* p)
998 extern "C" apr_status_t shib_exit(void* data)
1000 server_rec* s = NULL;
1003 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_exit(%d) dealing with g_Config..", (int)getpid());
1005 g_Config->shutdown();
1008 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_exit() done\n");
1009 #ifndef SHIB_APACHE_13
1015 #ifdef SHIB_APACHE_13
1016 extern "C" void shib_child_exit(server_rec* s, SH_AP_POOL* p)
1019 extern "C" apr_status_t shib_child_exit(void* data)
1021 server_rec* s = NULL;
1024 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit(%d)",
1027 #ifndef SHIB_APACHE_13
1033 * shire_child_init()
1034 * Things to do when the child process is initialized.
1035 * (or after the configs are read in apache-2)
1037 #ifdef SHIB_APACHE_13
1038 extern "C" void shib_child_init(server_rec* s, SH_AP_POOL* p)
1040 extern "C" int shib_post_config(apr_pool_t* pconf, apr_pool_t* plog,
1041 apr_pool_t* ptemp, server_rec* s)
1044 // Initialize runtime components.
1046 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init(%d) starting", (int)getpid());
1049 ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() already initialized!");
1050 #ifdef SHIB_APACHE_13
1058 g_Config=&ShibTargetConfig::getConfig();
1059 g_Config->setFeatures(
1060 ShibTargetConfig::Listener |
1061 ShibTargetConfig::Metadata |
1062 ShibTargetConfig::AAP |
1063 ShibTargetConfig::RequestMapper |
1064 ShibTargetConfig::SHIREExtensions |
1065 ShibTargetConfig::Logging
1067 if (!g_Config->init(g_szSchemaDir,g_szSHIBConfig)) {
1068 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize SHIB Target");
1073 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize SHIB Target");
1077 // Set the cleanup handler
1078 apr_pool_cleanup_register(pconf, NULL, &shib_exit, &shib_child_exit);
1080 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() done");
1082 #ifndef SHIB_APACHE_13
1087 #ifdef SHIB_APACHE_13
1089 // SHIB Module commands
1091 static command_rec shire_cmds[] = {
1092 {"SHIREConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1093 RSRC_CONF, TAKE1, "Path to shibboleth.xml config file."},
1094 {"ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1095 RSRC_CONF, TAKE1, "Path to shibboleth.xml config file."},
1096 {"ShibSchemaDir", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1097 RSRC_CONF, TAKE1, "Path to Shibboleth XML schema directory."},
1099 {"ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
1100 (void *) XtOffsetOf (shib_server_config, szScheme),
1101 RSRC_CONF, TAKE1, "URL scheme to force into generated URLs for a vhost."},
1103 {"ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1104 (void *) XtOffsetOf (shib_dir_config, bBasicHijack),
1105 OR_AUTHCFG, FLAG, "Respond to AuthType Basic and convert to shib?"},
1106 {"ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1107 (void *) XtOffsetOf (shib_dir_config, bRequireSession),
1108 OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist."},
1109 {"ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1110 (void *) XtOffsetOf (shib_dir_config, bExportAssertion),
1111 OR_AUTHCFG, FLAG, "Export SAML assertion to Shibboleth-defined header?"},
1112 {"AuthGroupFile", (config_fn_t)ap_set_file_slot,
1113 (void *) XtOffsetOf (shib_dir_config, szAuthGrpFile),
1114 OR_AUTHCFG, TAKE1, "text file containing group names and member user IDs"},
1115 {"ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1116 (void *) XtOffsetOf (shib_dir_config, bRequireAll),
1117 OR_AUTHCFG, FLAG, "All require directives must match!"},
1123 handler_rec shib_handlers[] = {
1124 { "shib-shire-post", shib_post_handler },
1128 module MODULE_VAR_EXPORT mod_shib = {
1129 STANDARD_MODULE_STUFF,
1130 NULL, /* initializer */
1131 create_shib_dir_config, /* dir config creater */
1132 merge_shib_dir_config, /* dir merger --- default is to override */
1133 create_shib_server_config, /* server config */
1134 merge_shib_server_config, /* merge server config */
1135 shire_cmds, /* command table */
1136 shib_handlers, /* handlers */
1137 NULL, /* filename translation */
1138 shib_check_user, /* check_user_id */
1139 shib_auth_checker, /* check auth */
1140 NULL, /* check access */
1141 NULL, /* type_checker */
1144 NULL, /* header parser */
1145 shib_child_init, /* child_init */
1146 shib_exit, /* child_exit */
1147 NULL /* post read-request */
1150 #elif defined(SHIB_APACHE_20)
1152 extern "C" void shib_register_hooks (apr_pool_t *p)
1154 ap_hook_post_config(shib_post_config, NULL, NULL, APR_HOOK_MIDDLE);
1155 ap_hook_check_user_id(shib_check_user, NULL, NULL, APR_HOOK_MIDDLE);
1156 ap_hook_auth_checker(shib_auth_checker, NULL, NULL, APR_HOOK_FIRST);
1157 ap_hook_handler(shib_post_handler, NULL, NULL, APR_HOOK_LAST);
1160 // SHIB Module commands
1163 static command_rec shib_cmds[] = {
1164 AP_INIT_TAKE1("ShibConfig",
1165 (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1166 RSRC_CONF, "Path to shibboleth.xml config file."),
1167 AP_INIT_TAKE1("ShibSchemaDir",
1168 (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1169 RSRC_CONF, "Path to Shibboleth XML schema directory."),
1171 AP_INIT_TAKE1("ShibURLScheme",
1172 (config_fn_t)shib_set_server_string_slot,
1173 (void *) offsetof (shib_server_config, szScheme),
1174 RSRC_CONF, "URL scheme to force into generated URLs for a vhost."),
1176 AP_INIT_FLAG("ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1177 (void *) offsetof (shib_dir_config, bBasicHijack),
1178 OR_AUTHCFG, "Respond to AuthType Basic and convert to shib?"),
1179 AP_INIT_FLAG("ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1180 (void *) offsetof (shib_dir_config, bRequireSession),
1181 OR_AUTHCFG, "Initiates a new session if one does not exist."),
1182 AP_INIT_FLAG("ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1183 (void *) offsetof (shib_dir_config, bExportAssertion),
1184 OR_AUTHCFG, "Export SAML assertion to Shibboleth-defined header?"),
1185 AP_INIT_TAKE1("AuthGroupFile", (config_fn_t)ap_set_file_slot,
1186 (void *) offsetof (shib_dir_config, szAuthGrpFile),
1187 OR_AUTHCFG, "text file containing group names and member user IDs"),
1188 AP_INIT_FLAG("ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1189 (void *) offsetof (shib_dir_config, bRequireAll),
1190 OR_AUTHCFG, "All require directives must match!"),
1195 module AP_MODULE_DECLARE_DATA mod_shib = {
1196 STANDARD20_MODULE_STUFF,
1197 create_shib_dir_config, /* create dir config */
1198 merge_shib_dir_config, /* merge dir config --- default is to override */
1199 create_shib_server_config, /* create server config */
1200 merge_shib_server_config, /* merge server config */
1201 shib_cmds, /* command table */
1202 shib_register_hooks /* register hooks */
1206 #error "undefined APACHE version"