Added require Shibboleth rule, fixed valid-user, and handling of no session.
[shibboleth/cpp-sp.git] / apache / mod_apache.cpp
1 /*
2  * mod_apache.cpp -- the core Apache Module code
3  *
4  * Created by:  Derek Atkins <derek@ihtfp.com>
5  *
6  * $Id$
7  */
8
9 // SAML Runtime
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>
15
16 #undef _XPG4_2
17
18 // Apache specific header files
19 #include <httpd.h>
20 #include <http_config.h>
21 #include <http_protocol.h>
22 #include <http_main.h>
23 #define CORE_PRIVATE
24 #include <http_core.h>
25 #include <http_log.h>
26
27 #ifndef SHIB_APACHE_13
28 #include <http_request.h>
29 #include <apr_strings.h>
30 #include <apr_pools.h>
31 #endif
32
33 #include <fstream>
34 #include <sstream>
35
36 #ifdef HAVE_UNISTD_H
37 #include <unistd.h>             // for getpid()
38 #endif
39
40 using namespace std;
41 using namespace saml;
42 using namespace shibboleth;
43 using namespace shibtarget;
44
45 extern "C" module MODULE_VAR_EXPORT mod_shib;
46 int shib_handler(request_rec* r, const IApplication* application, const IPropertySet* sessionProps, SHIRE& shire);
47
48 namespace {
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_";
54 }
55
56 // per-dir module configuration structure
57 struct shib_dir_config
58 {
59     // RM Configuration
60     char* szAuthGrpFile;    // Auth GroupFile name
61     int bRequireAll;        // all require directives must match, otherwise OR logic
62
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?
67 };
68
69 // creates per-directory config structure
70 extern "C" void* create_shib_dir_config (SH_AP_POOL* p, char* d)
71 {
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;
76     dc->bRequireAll = -1;
77     dc->szAuthGrpFile = NULL;
78     return dc;
79 }
80
81 // overrides server configuration in directories
82 extern "C" void* merge_shib_dir_config (SH_AP_POOL* p, void* base, void* sub)
83 {
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;
87
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);
92     else
93         dc->szAuthGrpFile=NULL;
94
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);
99     return dc;
100 }
101
102 // generic global slot handlers
103 extern "C" const char* ap_set_global_string_slot(cmd_parms* parms, void*, const char* arg)
104 {
105     *((char**)(parms->info))=ap_pstrdup(parms->pool,arg);
106     return NULL;
107 }
108
109 typedef const char* (*config_fn_t)(void);
110
111 static int shib_error_page(request_rec* r, const IApplication* app, const char* page, ShibMLP& mlp)
112 {
113     const IPropertySet* props=app->getPropertySet("Errors");
114     if (props) {
115         pair<bool,const char*> p=props->getString(page);
116         if (p.first) {
117             ifstream infile(p.second);
118             if (!infile.fail()) {
119                 const char* res = mlp.run(infile);
120                 if (res) {
121                     r->content_type = ap_psprintf(r->pool, "text/html");
122                     ap_send_http_header(r);
123                     ap_rprintf(r, res);
124                     return DONE;
125                 }
126             }
127         }
128     }
129
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());
132     return SERVER_ERROR;
133 }
134
135 extern "C" int shib_check_user(request_rec* r)
136 {
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);
139
140     ostringstream threadid;
141     threadid << "[" << getpid() << "] shib_check_user" << '\0';
142     saml::NDC ndc(threadid.str().c_str());
143
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);
146
147     // We lock the configuration system for the duration.
148     IConfig* conf=g_Config->getINI();
149     Locker locker(conf);
150     
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
156         );
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");
163         return SERVER_ERROR;
164     }
165     
166     // Declare SHIRE object for this request.
167     SHIRE shire(application);
168     
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);
172     }
173
174     // We can short circuit the handler if we run this...
175     apr_pool_userdata_setn((const void*)42,g_UserDataKey,NULL,r->pool);
176
177     // Regular access to arbitrary resource...check AuthType
178     const char *auth_type=ap_auth_type(r);
179     if (!auth_type)
180         return DECLINED;
181
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";
188         }
189         else
190             return DECLINED;
191     }
192
193     pair<bool,bool> requireSession = pair<bool,bool>(false,false);
194     if (g_bApacheConf) {
195         // By default, we will require a session.
196         if (dc->bRequireSession!=0)
197             requireSession.second=true;
198     }
199     else
200         requireSession = settings.first->getBool("requireSession");
201
202     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: session check for %s",targeturl);
203
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);
209         return SERVER_ERROR;
210     }
211
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");
215
216     if (cookies) {
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,';');
223             if (cookieend)
224                 *cookieend = '\0';    /* Ignore anyting after a ; */
225             session_id=cookiebuf;
226         }
227     }
228
229     if (!session_id || !*session_id) {
230         // If no session required, bail now.
231         if (!requireSession.second)
232             return OK;
233
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)));
237         return REDIRECT;
238     }
239
240     // Make sure this session is still valid.
241     RPCError* status = NULL;
242     ShibMLP markupProcessor(application);
243     markupProcessor.insert("requestURL", targeturl);
244
245     try {
246         status = shire.sessionIsValid(session_id, r->connection->remote_ip);
247     }
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);
254     }
255 #ifndef _DEBUG
256     catch (...) {
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);
262     }
263 #endif
264
265     // Check the status
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());
269
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)));
279             delete status;
280             return REDIRECT;
281         }
282         else {
283             // return the error page to the user
284             markupProcessor.insert(*status);
285             delete status;
286             return shib_error_page(r, application, "shire", markupProcessor);
287         }
288     }
289
290     delete status;
291     // set the authtype
292 #ifdef SHIB_APACHE_13
293     if (r->connection)
294         r->connection->ap_auth_type = "shibboleth";
295 #else
296     r->ap_auth_type = "shibboleth";
297 #endif
298     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: session successfully verified");
299
300     // This is code transferred in from the auth check to export the attributes.
301     // We could even combine the isSessionValid/getAssertions API...?
302
303     RM rm(application);
304     vector<SAMLAssertion*> assertions;
305     SAMLAuthenticationStatement* sso_statement=NULL;
306
307     try {
308         status = rm.getAssertions(session_id, r->connection->remote_ip, assertions, &sso_statement);
309     }
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);
316     }
317 #ifndef _DEBUG
318     catch (...) {
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);
324     }
325 #endif
326
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());
330
331         markupProcessor.insert(*status);
332         delete status;
333         return shib_error_page(r, application, "rm", markupProcessor);
334     }
335     delete status;
336
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);
346         }
347     }
348
349     // Get the AAP providers, which contain the attribute policy info.
350     Iterator<IAAP*> provs=application->getAAPProviders();
351
352     // Clear out the list of mapped attributes
353     while (provs.hasNext()) {
354         IAAP* aap=provs.next();
355         aap->lock();
356         try {
357             Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
358             while (rules.hasNext()) {
359                 const char* header=rules.next()->getHeader();
360                 if (header)
361                     ap_table_unset(r->headers_in,header);
362             }
363         }
364         catch(...) {
365             aap->unlock();
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);
375         }
376         aap->unlock();
377     }
378     provs.reset();
379     
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()) {
388         string assertion;
389         RM::serialize(*(assertions[0]), assertion);
390         ap_table_set(r->headers_in,"Shib-Attributes", assertion.c_str());
391     }
392
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");
396     if (sso_statement) {
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());
401     }
402     
403     ap_table_unset(r->headers_in,"Shib-Application-ID");
404     ap_table_set(r->headers_in,"Shib-Application-ID",application_id.second);
405
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());
413             if (!astate)
414                 continue;
415             Iterator<SAMLAttribute*> attrs=astate->getAttributes();
416             while (attrs.hasNext()) {
417                 SAMLAttribute* attr=attrs.next();
418         
419                 // Are we supposed to export it?
420                 AAP wrapper(provs,attr->getName(),attr->getNamespace());
421                 if (wrapper.fail())
422                     continue;
423                 
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());
427                 else {
428                     int it=0;
429                     char* header = (char*)ap_table_get(r->headers_in, wrapper->getHeader());
430                     if (header) {
431                         header=ap_pstrdup(r->pool, header);
432                         it++;
433                     }
434                     else
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));
439                                 pos != string::npos;
440                                 pos = value.find_first_of(";", pos)) {
441                             value.insert(pos, "\\");
442                             pos += 2;
443                         }
444                         header=ap_pstrcat(r->pool, header, (it ? ";" : ""), value.c_str(), NULL);
445                     }
446                     ap_table_setn(r->headers_in, wrapper->getHeader(), header);
447                }
448             }
449         }
450     }
451
452     // clean up memory
453     for (int k = 0; k < assertions.size(); k++)
454         delete assertions[k];
455     delete sso_statement;
456
457     return OK;
458 }
459
460 extern "C" int shib_post_handler(request_rec* r)
461 {
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.
466     void* data;
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");
470         return DECLINED;
471     }
472 #endif
473     
474     ostringstream threadid;
475     threadid << "[" << getpid() << "] shib_post_handler" << '\0';
476     saml::NDC ndc(threadid.str().c_str());
477
478     // We lock the configuration system for the duration.
479     IConfig* conf=g_Config->getINI();
480     Locker locker(conf);
481     
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
487         );
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");
494         return SERVER_ERROR;
495     }
496     
497     // Declare SHIRE object for this request.
498     SHIRE shire(application);
499     
500     return shib_handler(r, application, sessionProps, shire);
501 }
502
503 int shib_handler(request_rec* r, const IApplication* application, const IPropertySet* sessionProps, SHIRE& shire)
504 {
505     // Prime the pump...
506     const char* targeturl = ap_construct_url(r->pool,r->unparsed_uri,r);
507
508     // Make sure we only process the SHIRE requests.
509     if (!strstr(targeturl,shire.getShireURL(targeturl)))
510         return DECLINED;
511
512     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler() running");
513
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());
519         return SERVER_ERROR;
520     }
521
522     ShibMLP markupProcessor(application);
523     markupProcessor.insert("requestURL", targeturl);
524
525     // Process SHIRE request
526     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() Beginning SHIRE processing");
527       
528     try {
529         pair<bool,bool> shireSSL=sessionProps->getBool("shireSSL");
530       
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");
534
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;
538             if (!areq)
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));
541             return REDIRECT;
542         }
543         else if (strcasecmp(r->method,"POST")) {
544             throw ShibTargetException(SHIBRPC_OK, "blocked non-POST to SHIRE POST processor");
545         }
546
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 : "")));
552
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...");
560
561         string cgistr;
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) {
566             cgistr += buff;
567             memset(buff, 0, sizeof(buff));
568         }
569         ap_kill_timeout(r);
570
571         // Parse the submission.
572         pair<const char*,const char*> elements=shire.getFormSubmission(cgistr.c_str(),cgistr.length());
573     
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");
577     
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");
581     
582         ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
583             "shib_handler() Processing POST for target: %s", elements.second);
584
585         // process the post
586         string cookie;
587         RPCError* status = shire.sessionCreate(elements.first, r->connection->remote_ip, cookie);
588
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());
592
593             if (status->isRetryable()) {
594                 delete status;
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)));
598                 return REDIRECT;
599             }
600
601             // return this error to the user.
602             markupProcessor.insert(*status);
603             delete status;
604             return shib_error_page(r, application, "shire", markupProcessor);
605         }
606         delete status;
607
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());
610
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);
616
617         // ... and redirect to the target
618         ap_table_setn(r->headers_out, "Location", ap_pstrdup(r->pool,elements.second));
619         return REDIRECT;
620     }
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);
627     }
628 #ifndef _DEBUG
629     catch (...) {
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);
635     }
636 #endif
637
638     ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_handler() server error");
639     return SERVER_ERROR;
640 }
641
642 static SH_AP_TABLE* groups_for_user(request_rec* r, const char* user, char* grpfile)
643 {
644     SH_AP_CONFIGFILE* f;
645     SH_AP_TABLE* grps=ap_make_table(r->pool,15);
646     char l[MAX_STRING_LEN];
647     const char *group_name, *ll, *w;
648
649 #ifdef SHIB_APACHE_13
650     if (!(f=ap_pcfg_openfile(r->pool,grpfile))) {
651 #else
652     if (ap_pcfg_openfile(&f,r->pool,grpfile) != APR_SUCCESS) {
653 #endif
654         ap_log_rerror(APLOG_MARK,APLOG_DEBUG,SH_AP_R(r),"groups_for_user() could not open group file: %s\n",grpfile);
655         return NULL;
656     }
657
658     SH_AP_POOL* sp;
659 #ifdef SHIB_APACHE_13
660     sp=ap_make_sub_pool(r->pool);
661 #else
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");
665         return NULL;
666     }
667 #endif
668
669     while (!(ap_cfg_getline(l,MAX_STRING_LEN,f))) {
670         if ((*l=='#') || (!*l))
671             continue;
672         ll = l;
673         ap_clear_pool(sp);
674
675         group_name=ap_getword(sp,&ll,':');
676
677         while (*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");
681                 break;
682             }
683         }
684     }
685     ap_cfg_closefile(f);
686     ap_destroy_pool(sp);
687     return grps;
688 }
689
690 /*
691  * shib_auth_checker() -- a simple resource manager to
692  * process the .htaccess settings and copy attributes
693  * into the HTTP headers.
694  */
695 extern "C" int shib_auth_checker(request_rec* r)
696 {
697     shib_dir_config* dc=
698         (shib_dir_config*)ap_get_module_config(r->per_dir_config,&mod_shib);
699
700     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() executing");
701
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"))
705         return DECLINED;
706
707     ostringstream threadid;
708     threadid << "[" << getpid() << "] shibrm" << '\0';
709     saml::NDC ndc(threadid.str().c_str());
710
711     // We lock the configuration system for the duration.
712     IConfig* conf=g_Config->getINI();
713     Locker locker(conf);
714     
715     const char* application_id=ap_table_get(r->headers_in,"Shib-Application-ID");
716     const IApplication* application=NULL;
717     if (application_id)
718         application = conf->getApplication(application_id);
719
720     // mod_auth clone
721
722     int m=r->method_number;
723     bool method_restricted=false;
724     const char *t, *w;
725     
726     const array_header* reqs_arr=ap_requires(r);
727     if (!reqs_arr)
728         return OK;
729
730     require_line* reqs=(require_line*)reqs_arr->elts;
731
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);
734
735     vector<bool> auth_OK(reqs_arr->nelts,false);
736
737 #define SHIB_AP_CHECK_IS_OK {       \
738      if (dc->bRequireAll < 1)    \
739          return OK;      \
740      auth_OK[x] = true;      \
741      continue;           \
742 }
743
744     for (int x=0; x<reqs_arr->nelts; x++) {
745         auth_OK[x] = false;
746         if (!(reqs[x].method_mask & (1 << m)))
747             continue;
748         method_restricted=true;
749
750         t = reqs[x].requirement;
751         w = ap_getword_white(r->pool, &t);
752
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.
756             SHIB_AP_CHECK_IS_OK;
757         }
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");
760             SHIB_AP_CHECK_IS_OK;
761         }
762         else if (!strcmp(w,"user") && SH_AP_USER(r)) {
763             bool regexp=false;
764             while (*t) {
765                 w=ap_getword_conf(r->pool,&t);
766                 if (*w=='~') {
767                     regexp=true;
768                     continue;
769                 }
770                 
771                 if (regexp) {
772                     try {
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);
779                             SHIB_AP_CHECK_IS_OK;
780                         }
781                     }
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());
786                     }
787                 }
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);
790                     SHIB_AP_CHECK_IS_OK;
791                 }
792             }
793         }
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);
799             }
800             if (!grpstatus)
801                 return DECLINED;
802     
803             while (*t) {
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);
807                     SHIB_AP_CHECK_IS_OK;
808                 }
809             }
810         }
811         else {
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);
817                 continue;
818             }
819
820             bool regexp=false;
821             const char* vals=ap_table_get(r->headers_in,wrapper->getHeader());
822             while (*t && vals) {
823                 w=ap_getword_conf(r->pool,&t);
824                 if (*w=='~') {
825                     regexp=true;
826                     continue;
827                 }
828
829                 try {
830                     auto_ptr<RegularExpression> re;
831                     if (regexp) {
832                         delete re.release();
833                         auto_ptr<XMLCh> trans(fromUTF8(w));
834                         auto_ptr<RegularExpression> temp(new RegularExpression(trans.get()));
835                         re=temp;
836                     }
837                     
838                     string vals_str(vals);
839                     int j = 0;
840                     for (int i = 0;  i < vals_str.length();  i++) {
841                         if (vals_str.at(i) == ';') {
842                             if (i == 0) {
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);
845                                 return SERVER_ERROR;
846                             }
847
848                             if (vals_str.at(i-1) == '\\') {
849                                 vals_str.erase(i-1, 1);
850                                 i--;
851                                 continue;
852                             }
853
854                             string val = vals_str.substr(j, i-j);
855                             j = i+1;
856                             if (regexp) {
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());
861                                     SHIB_AP_CHECK_IS_OK;
862                                 }
863                             }
864                             else if (val==w) {
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());
867                                 SHIB_AP_CHECK_IS_OK;
868                             }
869                             else {
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());
872                             }
873                         }
874                     }
875     
876                     string val = vals_str.substr(j, vals_str.length()-j);
877                     if (regexp) {
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());
882                             SHIB_AP_CHECK_IS_OK;
883                         }
884                     }
885                     else if (val==w) {
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());
888                         SHIB_AP_CHECK_IS_OK;
889                     }
890                     else {
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());
893                     }
894                 }
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());
899                 }
900             }
901         }
902     }
903
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];
908     }
909     if (auth_all_OK)
910         return OK;
911
912     if (!method_restricted)
913         return OK;
914
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;
919     }
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;
924     }
925
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);
929 }
930
931 /*
932  * shib_exit()
933  *  Cleanup the (per-process) pool info.
934  */
935 #ifdef SHIB_APACHE_13
936 extern "C" void shib_exit(server_rec* s, SH_AP_POOL* p)
937 {
938 #else
939 extern "C" apr_status_t shib_exit(void* data)
940 {
941     server_rec* s = NULL;
942 #endif
943     g_Config->shutdown();
944     g_Config = NULL;
945     ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_exit() done");
946 #ifndef SHIB_APACHE_13
947     return OK;
948 #endif
949 }
950
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
956 };
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 };
959
960 /* 
961  * shire_child_init()
962  *  Things to do when the child process is initialized.
963  *  (or after the configs are read in apache-2)
964  */
965 #ifdef SHIB_APACHE_13
966 extern "C" void shib_child_init(server_rec* s, SH_AP_POOL* p)
967 #else
968 extern "C" int shib_post_config(apr_pool_t* pconf, apr_pool_t* plog,
969                                 apr_pool_t* ptemp, server_rec* s)
970 #endif
971 {
972     // Initialize runtime components.
973
974     ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() starting");
975
976     if (g_Config) {
977         ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init(): already initialized!");
978 #ifdef SHIB_APACHE_13
979         exit(1);
980 #else
981         return OK;
982 #endif
983     }
984
985     try {
986         g_Config=&ShibTargetConfig::getConfig();
987         g_Config->setFeatures(
988             ShibTargetConfig::Listener |
989             ShibTargetConfig::Metadata |
990             ShibTargetConfig::AAP |
991             ShibTargetConfig::RequestMapper |
992             ShibTargetConfig::SHIREExtensions
993             );
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!");
996             exit(1);
997         }
998         
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");
1003         if (props) {
1004             const DOMElement* impl=saml::XML::getFirstChildElement(
1005                 props->getElement(),ShibTargetConfig::SHIBTARGET_NS,Implementation
1006                 );
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))
1010                     g_bApacheConf=true;
1011             }
1012         }
1013     }
1014     catch (...) {
1015         ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize SHIB Target");
1016         exit (1);
1017     }
1018
1019     // Set the cleanup handler
1020     apr_pool_cleanup_register(pconf, NULL, shib_exit, NULL);
1021
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");
1024
1025 #ifndef SHIB_APACHE_13
1026     return OK;
1027 #endif
1028 }
1029
1030 #ifdef SHIB_APACHE_13
1031
1032 // SHIB Module commands
1033
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."},
1041
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!"},
1057
1058   {NULL}
1059 };
1060
1061 extern "C"{
1062 handler_rec shib_handlers[] = {
1063   { "shib-shire-post", shib_post_handler },
1064   { NULL }
1065 };
1066
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 */
1081     NULL,                       /* fixups */
1082     NULL,                       /* logger */
1083     NULL,                       /* header parser */
1084     shib_child_init,            /* child_init */
1085     shib_exit,                  /* child_exit */
1086     NULL                        /* post read-request */
1087 };
1088
1089 #elif defined(SHIB_APACHE_20)
1090
1091 extern "C" void shib_register_hooks (apr_pool_t *p)
1092 {
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);
1097 }
1098
1099 // SHIB Module commands
1100
1101 extern "C" {
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."),
1109
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!"),
1125
1126   {NULL}
1127 };
1128
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 */
1137 };
1138
1139 #else
1140 #error "undefined APACHE version"
1141 #endif
1142
1143 }