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 const char* shireURL=shire.getShireURL(targeturl);
226 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
227 "shib_check_user: unable to map request to proper shireURL setting, check configuration");
231 // Get location of this application's assertion consumer service and see if this is it.
232 if (strstr(targeturl,shireURL)) {
233 return shib_handler(r,application,shire);
236 // We can short circuit the handler if we run this...
237 apr_pool_userdata_setn((const void*)42,g_UserDataKey,NULL,r->pool);
239 // Regular access to arbitrary resource...check AuthType
240 const char *auth_type=ap_auth_type(r);
244 if (strcasecmp(auth_type,"shibboleth")) {
245 if (!strcasecmp(auth_type,"basic") && dc->bBasicHijack==1) {
246 core_dir_config* conf=
247 (core_dir_config*)ap_get_module_config(r->per_dir_config,
248 ap_find_linked_module("http_core.c"));
249 conf->ap_auth_type="shibboleth";
255 pair<bool,bool> requireSession = settings.first->getBool("requireSession");
256 if (!requireSession.first || !requireSession.second)
257 if (dc->bRequireSession==1)
258 requireSession.second=true;
260 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: session check for %s",targeturl);
262 pair<const char*,const char*> shib_cookie=shire.getCookieNameProps(); // always returns *something*
264 // We're in charge, so check for cookie.
265 const char* session_id=NULL;
266 const char* cookies=ap_table_get(r->headers_in,"Cookie");
269 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: cookies found: %s",cookies);
270 if (session_id=strstr(cookies,shib_cookie.first)) {
271 // Yep, we found a cookie -- pull it out (our session_id)
272 session_id+=strlen(shib_cookie.first) + 1; /* Skip over the '=' */
273 char* cookiebuf = ap_pstrdup(r->pool,session_id);
274 char* cookieend = strchr(cookiebuf,';');
276 *cookieend = '\0'; /* Ignore anyting after a ; */
277 session_id=cookiebuf;
281 if (!session_id || !*session_id) {
282 // If no session required, bail now.
283 if (!requireSession.second)
286 // No acceptable cookie, and we require a session. Generate an AuthnRequest.
287 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: no cookie found -- redirecting to WAYF");
288 ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(targeturl)));
292 // Make sure this session is still valid.
293 RPCError* status = NULL;
294 ShibMLP markupProcessor;
295 markupProcessor.insert("requestURL", targeturl);
298 status = shire.sessionIsValid(session_id, r->connection->remote_ip);
300 catch (ShibTargetException &e) {
301 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): %s", e.what());
302 markupProcessor.insert("errorType", "Session Processing Error");
303 markupProcessor.insert("errorText", e.what());
304 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
305 return shib_error_page(r, application, "shire", markupProcessor);
309 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): caught unexpected error");
310 markupProcessor.insert("errorType", "Session Processing Error");
311 markupProcessor.insert("errorText", "Unexpected Exception");
312 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
313 return shib_error_page(r, application, "shire", markupProcessor);
318 if (status->isError()) {
319 ap_log_rerror(APLOG_MARK,APLOG_INFO|APLOG_NOERRNO,SH_AP_R(r),
320 "shib_check_user() session invalid: %s", status->getText());
322 // If no session required, bail now.
323 if (!requireSession.second)
324 return OK; // XXX: Or should this be DECLINED?
325 // Has to be OK because DECLINED will just cause Apache to fail when it can't locate
326 // anything to process the AuthType. No session plus requireSession false means
327 // do not authenticate the user.
328 else if (status->isRetryable()) {
329 // Oops, session is invalid. Generate AuthnRequest.
330 ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(targeturl)));
335 // return the error page to the user
336 markupProcessor.insert(*status);
338 return shib_error_page(r, application, "shire", markupProcessor);
344 #ifdef SHIB_APACHE_13
346 r->connection->ap_auth_type = "shibboleth";
348 r->ap_auth_type = "shibboleth";
350 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: session successfully verified");
352 // This is code transferred in from the auth check to export the attributes.
353 // We could even combine the isSessionValid/getAssertions API...?
356 vector<SAMLAssertion*> assertions;
357 SAMLAuthenticationStatement* sso_statement=NULL;
360 status = rm.getAssertions(session_id, r->connection->remote_ip, assertions, &sso_statement);
362 catch (ShibTargetException &e) {
363 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): %s", e.what());
364 markupProcessor.insert("errorType", "Attribute Processing Error");
365 markupProcessor.insert("errorText", e.what());
366 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
367 return shib_error_page(r, application, "rm", markupProcessor);
371 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): caught unexpected error");
372 markupProcessor.insert("errorType", "Attribute Processing Error");
373 markupProcessor.insert("errorText", "Unexpected Exception");
374 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
375 return shib_error_page(r, application, "rm", markupProcessor);
379 if (status->isError()) {
380 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
381 "shib_check_user() getAssertions failed: %s", status->getText());
383 markupProcessor.insert(*status);
385 return shib_error_page(r, application, "rm", markupProcessor);
389 // Do we have an access control plugin?
390 if (settings.second) {
391 Locker acllock(settings.second);
392 if (!settings.second->authorized(*sso_statement,assertions)) {
393 for (int k = 0; k < assertions.size(); k++)
394 delete assertions[k];
395 delete sso_statement;
396 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): access control provider denied access");
397 return shib_error_page(r, application, "access", markupProcessor);
401 // Get the AAP providers, which contain the attribute policy info.
402 Iterator<IAAP*> provs=application->getAAPProviders();
404 // Clear out the list of mapped attributes
405 while (provs.hasNext()) {
406 IAAP* aap=provs.next();
409 Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
410 while (rules.hasNext()) {
411 const char* header=rules.next()->getHeader();
413 ap_table_unset(r->headers_in,header);
418 for (int k = 0; k < assertions.size(); k++)
419 delete assertions[k];
420 delete sso_statement;
421 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
422 "shib_check_user(): caught unexpected error while clearing headers");
423 markupProcessor.insert("errorType", "Attribute Processing Error");
424 markupProcessor.insert("errorText", "Unexpected Exception");
425 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
426 return shib_error_page(r, application, "rm", markupProcessor);
432 // Maybe export the first assertion.
433 ap_table_unset(r->headers_in,"Shib-Attributes");
434 pair<bool,bool> exp=settings.first->getBool("exportAssertion");
435 if (!exp.first || !exp.second)
436 if (dc->bExportAssertion==1)
438 if (exp.second && assertions.size()) {
440 RM::serialize(*(assertions[0]), assertion);
441 ap_table_set(r->headers_in,"Shib-Attributes", assertion.c_str());
444 // Export the SAML AuthnMethod and the origin site name, and possibly the NameIdentifier.
445 ap_table_unset(r->headers_in,"Shib-Origin-Site");
446 ap_table_unset(r->headers_in,"Shib-Authentication-Method");
447 ap_table_unset(r->headers_in,"Shib-NameIdentifier-Format");
448 auto_ptr_char os(sso_statement->getSubject()->getNameIdentifier()->getNameQualifier());
449 auto_ptr_char am(sso_statement->getAuthMethod());
450 ap_table_set(r->headers_in,"Shib-Origin-Site", os.get());
451 ap_table_set(r->headers_in,"Shib-Authentication-Method", am.get());
454 AAP wrapper(provs,sso_statement->getSubject()->getNameIdentifier()->getFormat(),Constants::SHIB_ATTRIBUTE_NAMESPACE_URI);
455 if (!wrapper.fail() && wrapper->getHeader()) {
456 auto_ptr_char form(sso_statement->getSubject()->getNameIdentifier()->getFormat());
457 auto_ptr_char nameid(sso_statement->getSubject()->getNameIdentifier()->getName());
458 ap_table_set(r->headers_in,"Shib-NameIdentifier-Format",form.get());
459 if (!strcmp(wrapper->getHeader(),"REMOTE_USER"))
460 SH_AP_USER(r)=ap_pstrdup(r->pool,nameid.get());
462 ap_table_set(r->headers_in,wrapper->getHeader(),nameid.get());
465 ap_table_unset(r->headers_in,"Shib-Application-ID");
466 ap_table_set(r->headers_in,"Shib-Application-ID",application_id.second);
468 // Export the attributes.
469 Iterator<SAMLAssertion*> a_iter(assertions);
470 while (a_iter.hasNext()) {
471 SAMLAssertion* assert=a_iter.next();
472 Iterator<SAMLStatement*> statements=assert->getStatements();
473 while (statements.hasNext()) {
474 SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());
477 Iterator<SAMLAttribute*> attrs=astate->getAttributes();
478 while (attrs.hasNext()) {
479 SAMLAttribute* attr=attrs.next();
481 // Are we supposed to export it?
482 AAP wrapper(provs,attr->getName(),attr->getNamespace());
483 if (wrapper.fail() || !wrapper->getHeader())
486 Iterator<string> vals=attr->getSingleByteValues();
487 if (!strcmp(wrapper->getHeader(),"REMOTE_USER") && vals.hasNext())
488 SH_AP_USER(r)=ap_pstrdup(r->pool,vals.next().c_str());
491 char* header = (char*)ap_table_get(r->headers_in, wrapper->getHeader());
493 header=ap_pstrdup(r->pool, header);
497 header = ap_pstrdup(r->pool, "");
498 for (; vals.hasNext(); it++) {
499 string value = vals.next();
500 for (string::size_type pos = value.find_first_of(";", string::size_type(0));
502 pos = value.find_first_of(";", pos)) {
503 value.insert(pos, "\\");
506 header=ap_pstrcat(r->pool, header, (it ? ";" : ""), value.c_str(), NULL);
508 ap_table_setn(r->headers_in, wrapper->getHeader(), header);
515 for (int k = 0; k < assertions.size(); k++)
516 delete assertions[k];
517 delete sso_statement;
522 extern "C" int shib_post_handler(request_rec* r)
524 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
525 "shib_post_handler(%d): ENTER", (int)getpid());
526 shib_server_config* sc=(shib_server_config*)ap_get_module_config(r->server->module_config,&mod_shib);
528 #ifndef SHIB_APACHE_13
529 // With 2.x, this handler always runs, though last.
530 // We check if shib_check_user ran, because it will detect a SHIRE request
531 // and dispatch it directly.
533 apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
534 if (data==(const void*)42) {
535 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_post_handler skipped since check_user ran");
540 ostringstream threadid;
541 threadid << "[" << getpid() << "] shib_post_handler" << '\0';
542 saml::NDC ndc(threadid.str().c_str());
544 // We lock the configuration system for the duration.
545 IConfig* conf=g_Config->getINI();
548 // Map request to application and content settings.
549 IRequestMapper* mapper=conf->getRequestMapper();
550 Locker locker2(mapper);
551 IRequestMapper::Settings settings=mapper->getSettingsFromParsedURL(
552 (sc->szScheme ? sc->szScheme : ap_http_method(r)), ap_get_server_name(r), ap_get_server_port(r), r->unparsed_uri
554 pair<bool,const char*> application_id=settings.first->getString("applicationId");
555 const IApplication* application=conf->getApplication(application_id.second);
557 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
558 "shib_post_handler: unable to map request to application settings, check configuration");
562 // Declare SHIRE object for this request.
563 SHIRE shire(application);
565 return shib_handler(r, application, shire);
568 int shib_handler(request_rec* r, const IApplication* application, SHIRE& shire)
570 shib_server_config* sc=(shib_server_config*)ap_get_module_config(r->server->module_config,&mod_shib);
572 const char* targeturl=shib_get_targeturl(r,sc->szScheme);
574 const char* shireURL=shire.getShireURL(targeturl);
576 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
577 "shib_post_handler: unable to map request to proper shireURL setting, check configuration");
581 // Make sure we only process the SHIRE requests.
582 if (!strstr(targeturl,shireURL))
585 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler() running");
587 const IPropertySet* sessionProps=application->getPropertySet("Sessions");
589 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
590 "shib_post_handler: unable to map request to application session settings, check configuration");
594 pair<const char*,const char*> shib_cookie=shire.getCookieNameProps(); // always returns something
596 ShibMLP markupProcessor;
597 markupProcessor.insert("requestURL", targeturl);
599 // Process SHIRE request
600 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() Beginning SHIRE processing");
603 pair<bool,bool> shireSSL=sessionProps->getBool("shireSSL");
605 // Make sure this is SSL, if it should be
606 if ((!shireSSL.first || shireSSL.second) && strcmp(ap_http_method(r),"https"))
607 throw ShibTargetException(SHIBRPC_OK, "blocked non-SSL access to session creation service");
609 // If this is a GET, we manufacture an AuthnRequest.
610 if (!strcasecmp(r->method,"GET")) {
611 const char* areq=r->args ? shire.getLazyAuthnRequest(r->args) : NULL;
613 throw ShibTargetException(SHIBRPC_OK, "malformed arguments to request a new session");
614 ap_table_setn(r->headers_out, "Location", ap_pstrdup(r->pool,areq));
617 else if (strcasecmp(r->method,"POST")) {
618 throw ShibTargetException(SHIBRPC_OK, "blocked non-POST to SHIRE POST processor");
621 // Sure sure this POST is an appropriate content type
622 const char *ct = ap_table_get(r->headers_in, "Content-type");
623 if (!ct || strcasecmp(ct, "application/x-www-form-urlencoded"))
624 throw ShibTargetException(SHIBRPC_OK,
625 ap_psprintf(r->pool, "blocked bad content-type to SHIRE POST processor: %s", (ct ? ct : "")));
627 // Read the posted data
628 if (ap_setup_client_block(r, REQUEST_CHUNKED_ERROR))
629 throw ShibTargetException(SHIBRPC_OK, "CGI setup_client_block failed");
630 if (!ap_should_client_block(r))
631 throw ShibTargetException(SHIBRPC_OK, "CGI should_client_block failed");
632 if (r->remaining > 1024*1024)
633 throw ShibTargetException (SHIBRPC_OK, "CGI length too long...");
636 char buff[HUGE_STRING_LEN];
637 ap_hard_timeout("[mod_shib] CGI Parser", r);
638 memset(buff, 0, sizeof(buff));
639 while (ap_get_client_block(r, buff, sizeof(buff)-1) > 0) {
642 memset(buff, 0, sizeof(buff));
646 // Parse the submission.
647 pair<const char*,const char*> elements=shire.getFormSubmission(cgistr.c_str(),cgistr.length());
649 // Make sure the SAML Response parameter exists
650 if (!elements.first || !*elements.first)
651 throw ShibTargetException(SHIBRPC_OK, "SHIRE POST failed to find SAMLResponse form element");
653 // Make sure the target parameter exists
654 if (!elements.second || !*elements.second)
655 throw ShibTargetException(SHIBRPC_OK, "SHIRE POST failed to find TARGET form element");
657 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
658 "shib_handler() Processing POST for target: %s", elements.second);
662 RPCError* status = shire.sessionCreate(elements.first, r->connection->remote_ip, cookie);
664 if (status->isError()) {
665 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
666 "shib_handler() POST process failed (%d): %s", status->getCode(), status->getText());
668 if (status->isRetryable()) {
670 ap_log_rerror(APLOG_MARK,APLOG_INFO|APLOG_NOERRNO,SH_AP_R(r),
671 "shib_handler() retryable error, generating new AuthnRequest");
672 ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(elements.second)));
676 // return this error to the user.
677 markupProcessor.insert(*status);
679 return shib_error_page(r, application, "shire", markupProcessor);
683 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
684 "shib_handler() POST process succeeded. New session: %s", cookie.c_str());
686 // We've got a good session, set the cookie...
687 char* val = ap_psprintf(r->pool,"%s=%s%s",shib_cookie.first,cookie.c_str(),shib_cookie.second);
688 ap_table_setn(r->err_headers_out, "Set-Cookie", val);
689 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() setting cookie: %s", val);
691 // ... and redirect to the target
692 ap_table_setn(r->headers_out, "Location", ap_pstrdup(r->pool,elements.second));
695 catch (ShibTargetException &e) {
696 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() caught exception: %s", e.what());
697 markupProcessor.insert("errorType", "Session Creation Service Error");
698 markupProcessor.insert("errorText", e.what());
699 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
700 return shib_error_page(r, application, "shire", markupProcessor);
704 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler(): unexpected exception");
705 markupProcessor.insert("errorType", "Session Creation Service Error");
706 markupProcessor.insert("errorText", "Unknown Exception");
707 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
708 return shib_error_page(r, application, "shire", markupProcessor);
712 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_handler() server error");
716 static SH_AP_TABLE* groups_for_user(request_rec* r, const char* user, char* grpfile)
719 SH_AP_TABLE* grps=ap_make_table(r->pool,15);
720 char l[MAX_STRING_LEN];
721 const char *group_name, *ll, *w;
723 #ifdef SHIB_APACHE_13
724 if (!(f=ap_pcfg_openfile(r->pool,grpfile))) {
726 if (ap_pcfg_openfile(&f,r->pool,grpfile) != APR_SUCCESS) {
728 ap_log_rerror(APLOG_MARK,APLOG_DEBUG,SH_AP_R(r),"groups_for_user() could not open group file: %s\n",grpfile);
733 #ifdef SHIB_APACHE_13
734 sp=ap_make_sub_pool(r->pool);
736 if (apr_pool_create(&sp,r->pool) != APR_SUCCESS) {
737 ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,
738 "groups_for_user() could not create a subpool");
743 while (!(ap_cfg_getline(l,MAX_STRING_LEN,f))) {
744 if ((*l=='#') || (!*l))
749 group_name=ap_getword(sp,&ll,':');
752 w=ap_getword_conf(sp,&ll);
753 if (!strcmp(w,user)) {
754 ap_table_setn(grps,ap_pstrdup(r->pool,group_name),"in");
765 * shib_auth_checker() -- a simple resource manager to
766 * process the .htaccess settings and copy attributes
767 * into the HTTP headers.
769 extern "C" int shib_auth_checker(request_rec* r)
772 (shib_dir_config*)ap_get_module_config(r->per_dir_config,&mod_shib);
774 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() executing");
776 // Regular access to arbitrary resource...check AuthType
777 const char* auth_type=ap_auth_type(r);
778 if (!auth_type || strcasecmp(auth_type,"shibboleth"))
781 ostringstream threadid;
782 threadid << "[" << getpid() << "] shibrm" << '\0';
783 saml::NDC ndc(threadid.str().c_str());
785 // We lock the configuration system for the duration.
786 IConfig* conf=g_Config->getINI();
789 const char* application_id=ap_table_get(r->headers_in,"Shib-Application-ID");
790 const IApplication* application=NULL;
792 application = conf->getApplication(application_id);
796 int m=r->method_number;
797 bool method_restricted=false;
800 const array_header* reqs_arr=ap_requires(r);
804 require_line* reqs=(require_line*)reqs_arr->elts;
806 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"REQUIRE nelts: %d", reqs_arr->nelts);
807 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"REQUIRE all: %d", dc->bRequireAll);
809 vector<bool> auth_OK(reqs_arr->nelts,false);
811 #define SHIB_AP_CHECK_IS_OK { \
812 if (dc->bRequireAll < 1) \
818 for (int x=0; x<reqs_arr->nelts; x++) {
820 if (!(reqs[x].method_mask & (1 << m)))
822 method_restricted=true;
824 t = reqs[x].requirement;
825 w = ap_getword_white(r->pool, &t);
827 if (!strcasecmp(w,"Shibboleth")) {
828 // This is a dummy rule needed because Apache conflates authn and authz.
829 // Without some require rule, AuthType is ignored and no check_user hooks run.
832 else if (!strcmp(w,"valid-user") && application_id) {
833 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting valid-user");
836 else if (!strcmp(w,"user") && SH_AP_USER(r)) {
839 w=ap_getword_conf(r->pool,&t);
847 // To do regex matching, we have to convert from UTF-8.
848 auto_ptr<XMLCh> trans(fromUTF8(w));
849 RegularExpression re(trans.get());
850 auto_ptr<XMLCh> trans2(fromUTF8(SH_AP_USER(r)));
851 if (re.matches(trans2.get())) {
852 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting user: %s",w);
856 catch (XMLException& ex) {
857 auto_ptr_char tmp(ex.getMessage());
858 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
859 "shib_auth_checker caught exception while parsing regular expression (%s): %s",w,tmp.get());
862 else if (!strcmp(SH_AP_USER(r),w)) {
863 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting user: %s",w);
868 else if (!strcmp(w,"group")) {
869 SH_AP_TABLE* grpstatus=NULL;
870 if (dc->szAuthGrpFile && SH_AP_USER(r)) {
871 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() using groups file: %s\n",dc->szAuthGrpFile);
872 grpstatus=groups_for_user(r,SH_AP_USER(r),dc->szAuthGrpFile);
878 w=ap_getword_conf(r->pool,&t);
879 if (ap_table_get(grpstatus,w)) {
880 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting group: %s",w);
886 Iterator<IAAP*> provs=application ? application->getAAPProviders() : EMPTY(IAAP*);
887 AAP wrapper(provs,w);
888 if (wrapper.fail()) {
889 ap_log_rerror(APLOG_MARK,APLOG_WARNING|APLOG_NOERRNO,SH_AP_R(r),
890 "shib_auth_checker() didn't recognize require rule: %s\n",w);
895 const char* vals=ap_table_get(r->headers_in,wrapper->getHeader());
897 w=ap_getword_conf(r->pool,&t);
904 auto_ptr<RegularExpression> re;
907 auto_ptr<XMLCh> trans(fromUTF8(w));
908 auto_ptr<RegularExpression> temp(new RegularExpression(trans.get()));
912 string vals_str(vals);
914 for (int i = 0; i < vals_str.length(); i++) {
915 if (vals_str.at(i) == ';') {
917 ap_log_rerror(APLOG_MARK,APLOG_WARNING|APLOG_NOERRNO,SH_AP_R(r),
918 "shib_auth_checker() invalid header encoding %s: starts with semicolon", vals);
922 if (vals_str.at(i-1) == '\\') {
923 vals_str.erase(i-1, 1);
928 string val = vals_str.substr(j, i-j);
931 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
932 if (re->matches(trans.get())) {
933 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
934 "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
938 else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
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());
944 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
945 "shib_auth_checker() expecting %s, got %s: authorization not granted", w, val.c_str());
950 string val = vals_str.substr(j, vals_str.length()-j);
952 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
953 if (re->matches(trans.get())) {
954 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
955 "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
959 else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
960 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
961 "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
965 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
966 "shib_auth_checker() expecting %s, got %s: authorization not granted", w, val.c_str());
969 catch (XMLException& ex) {
970 auto_ptr_char tmp(ex.getMessage());
971 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
972 "shib_auth_checker caught exception while parsing regular expression (%s): %s",w,tmp.get());
978 // check if all require directives are true
979 bool auth_all_OK = true;
980 for (int i= 0; i<reqs_arr->nelts; i++) {
981 auth_all_OK &= auth_OK[i];
986 if (!method_restricted)
989 if (!application_id) {
990 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
991 "shib_auth_checker: Shib-Application-ID header not found in request");
992 return HTTP_FORBIDDEN;
994 else if (!application) {
995 ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
996 "shib_auth_checker: unable to map request to application settings, check configuration");
997 return HTTP_FORBIDDEN;
1000 ShibMLP markupProcessor;
1001 markupProcessor.insert("requestURL", ap_construct_url(r->pool,r->unparsed_uri,r));
1002 return shib_error_page(r, application, "access", markupProcessor);
1005 #ifndef SHIB_APACHE_13
1008 * Empty cleanup hook, Apache 2.x doesn't check NULL very well...
1010 extern "C" apr_status_t shib_exit(void* data)
1012 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,0,NULL,"shib_exit() done\n");
1020 * Cleanup the (per-process) pool info.
1022 #ifdef SHIB_APACHE_13
1023 extern "C" void shib_child_exit(server_rec* s, SH_AP_POOL* p)
1026 extern "C" apr_status_t shib_child_exit(void* data)
1028 server_rec* s = NULL;
1031 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit(%d) dealing with g_Config..", (int)getpid());
1032 g_Config->shutdown();
1034 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit() done\n");
1036 #ifndef SHIB_APACHE_13
1042 * shire_child_init()
1043 * Things to do when the child process is initialized.
1044 * (or after the configs are read in apache-2)
1046 #ifdef SHIB_APACHE_13
1047 extern "C" void shib_child_init(server_rec* s, SH_AP_POOL* p)
1049 extern "C" void shib_child_init(apr_pool_t* p, server_rec* s)
1052 // Initialize runtime components.
1054 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init(%d) starting", (int)getpid());
1057 ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() already initialized!");
1062 g_Config=&ShibTargetConfig::getConfig();
1063 g_Config->setFeatures(
1064 ShibTargetConfig::Listener |
1065 ShibTargetConfig::Metadata |
1066 ShibTargetConfig::AAP |
1067 ShibTargetConfig::RequestMapper |
1068 ShibTargetConfig::SHIREExtensions |
1069 ShibTargetConfig::Logging
1071 if (!g_Config->init(g_szSchemaDir,g_szSHIBConfig)) {
1072 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize SHIB Target");
1077 ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize SHIB Target");
1081 // Set the cleanup handler
1082 apr_pool_cleanup_register(p, NULL, &shib_exit, &shib_child_exit);
1084 ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() done");
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_child_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_child_init(shib_child_init, 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"