Fix for shibd init script install.
[shibboleth/cpp-sp.git] / apache / mod_apache.cpp
1 /*
2  *  Copyright 2001-2005 Internet2
3  * 
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /*
18  * mod_apache.cpp -- the core Apache Module code
19  *
20  * Created by:  Derek Atkins <derek@ihtfp.com>
21  *
22  * $Id$
23  */
24
25 #ifdef SOLARIS2
26 #undef _XOPEN_SOURCE    // causes gethostname conflict in unistd.h
27 #endif
28
29 // SAML Runtime
30 #include <saml/saml.h>
31 #include <shib/shib.h>
32 #include <shib/shib-threads.h>
33 #include <shib-target/shib-target.h>
34 #include <xercesc/util/regx/RegularExpression.hpp>
35
36 #undef _XPG4_2
37
38 // Apache specific header files
39 #include <httpd.h>
40 #include <http_config.h>
41 #include <http_protocol.h>
42 #include <http_main.h>
43 #define CORE_PRIVATE
44 #include <http_core.h>
45 #include <http_log.h>
46 #include <http_request.h>
47
48 #ifndef SHIB_APACHE_13
49 #include <apr_strings.h>
50 #include <apr_pools.h>
51 #endif
52
53 #include <fstream>
54 #include <sstream>
55
56 #ifdef HAVE_UNISTD_H
57 #include <unistd.h>             // for getpid()
58 #endif
59
60 using namespace shibtarget;
61 using namespace shibboleth;
62 using namespace saml;
63 using namespace std;
64
65 extern "C" module MODULE_VAR_EXPORT mod_shib;
66
67 namespace {
68     char* g_szSHIBConfig = NULL;
69     char* g_szSchemaDir = NULL;
70     ShibTargetConfig* g_Config = NULL;
71     string g_unsetHeaderValue;
72     bool g_checkSpoofing = true;
73     bool g_catchAll = true;
74     static const char* g_UserDataKey = "_shib_check_user_";
75 }
76
77 /* Apache 2.2.x headers must be accumulated and set in the output filter.
78    Apache 2.0.49+ supports the filter method.
79    Apache 1.3.x and lesser 2.0.x must write the headers directly. */
80
81 #if (defined(SHIB_APACHE_20) || defined(SHIB_APACHE_22)) && AP_MODULE_MAGIC_AT_LEAST(20020903,6)
82 #define SHIB_DEFERRED_HEADERS
83 #endif
84
85 /********************************************************************************/
86 // Basic Apache Configuration code.
87 //
88
89 // per-server module configuration structure
90 struct shib_server_config
91 {
92     char* szScheme;
93 };
94
95 // creates the per-server configuration
96 extern "C" void* create_shib_server_config(SH_AP_POOL* p, server_rec* s)
97 {
98     shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
99     sc->szScheme = NULL;
100     return sc;
101 }
102
103 // overrides server configuration in virtual servers
104 extern "C" void* merge_shib_server_config (SH_AP_POOL* p, void* base, void* sub)
105 {
106     shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
107     shib_server_config* parent=(shib_server_config*)base;
108     shib_server_config* child=(shib_server_config*)sub;
109
110     if (child->szScheme)
111         sc->szScheme=ap_pstrdup(p,child->szScheme);
112     else if (parent->szScheme)
113         sc->szScheme=ap_pstrdup(p,parent->szScheme);
114     else
115         sc->szScheme=NULL;
116
117     return sc;
118 }
119
120 // per-dir module configuration structure
121 struct shib_dir_config
122 {
123     // RM Configuration
124     char* szAuthGrpFile;    // Auth GroupFile name
125     int bRequireAll;        // all require directives must match, otherwise OR logic
126
127     // Content Configuration
128     char* szApplicationId;  // Shib applicationId value
129     char* szRequireWith;    // require a session using a specific initiator?
130     char* szRedirectToSSL;  // redirect non-SSL requests to SSL port
131     int bOff;               // flat-out disable all Shib processing
132     int bBasicHijack;       // activate for AuthType Basic?
133     int bRequireSession;    // require a session?
134     int bExportAssertion;   // export SAML assertion to the environment?
135     int bUseEnvVars;        // use environment variables?
136     int bUseHeaders;        // use HTTP headers?
137 };
138
139 // creates per-directory config structure
140 extern "C" void* create_shib_dir_config (SH_AP_POOL* p, char* d)
141 {
142     shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
143     dc->bOff = -1;
144     dc->bBasicHijack = -1;
145     dc->bRequireSession = -1;
146     dc->bExportAssertion = -1;
147     dc->bRequireAll = -1;
148     dc->szRedirectToSSL = NULL;
149     dc->szAuthGrpFile = NULL;
150     dc->szApplicationId = NULL;
151     dc->szRequireWith = NULL;
152     dc->bUseEnvVars = -1;
153     dc->bUseHeaders = -1;
154     return dc;
155 }
156
157 // overrides server configuration in directories
158 extern "C" void* merge_shib_dir_config (SH_AP_POOL* p, void* base, void* sub)
159 {
160     shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
161     shib_dir_config* parent=(shib_dir_config*)base;
162     shib_dir_config* child=(shib_dir_config*)sub;
163
164     if (child->szAuthGrpFile)
165         dc->szAuthGrpFile=ap_pstrdup(p,child->szAuthGrpFile);
166     else if (parent->szAuthGrpFile)
167         dc->szAuthGrpFile=ap_pstrdup(p,parent->szAuthGrpFile);
168     else
169         dc->szAuthGrpFile=NULL;
170
171     if (child->szApplicationId)
172         dc->szApplicationId=ap_pstrdup(p,child->szApplicationId);
173     else if (parent->szApplicationId)
174         dc->szApplicationId=ap_pstrdup(p,parent->szApplicationId);
175     else
176         dc->szApplicationId=NULL;
177
178     if (child->szRequireWith)
179         dc->szRequireWith=ap_pstrdup(p,child->szRequireWith);
180     else if (parent->szRequireWith)
181         dc->szRequireWith=ap_pstrdup(p,parent->szRequireWith);
182     else
183         dc->szRequireWith=NULL;
184
185     if (child->szRedirectToSSL)
186         dc->szRedirectToSSL=ap_pstrdup(p,child->szRedirectToSSL);
187     else if (parent->szRedirectToSSL)
188         dc->szRedirectToSSL=ap_pstrdup(p,parent->szRedirectToSSL);
189     else
190         dc->szRedirectToSSL=NULL;
191
192     dc->bOff=((child->bOff==-1) ? parent->bOff : child->bOff);
193     dc->bBasicHijack=((child->bBasicHijack==-1) ? parent->bBasicHijack : child->bBasicHijack);
194     dc->bRequireSession=((child->bRequireSession==-1) ? parent->bRequireSession : child->bRequireSession);
195     dc->bExportAssertion=((child->bExportAssertion==-1) ? parent->bExportAssertion : child->bExportAssertion);
196     dc->bRequireAll=((child->bRequireAll==-1) ? parent->bRequireAll : child->bRequireAll);
197     dc->bUseEnvVars=((child->bUseEnvVars==-1) ? parent->bUseEnvVars : child->bUseEnvVars);
198     dc->bUseHeaders=((child->bUseHeaders==-1) ? parent->bUseHeaders : child->bUseHeaders);
199     return dc;
200 }
201
202 // per-request module structure
203 struct shib_request_config
204 {
205     SH_AP_TABLE *env;        // environment vars 
206 #ifdef SHIB_DEFERRED_HEADERS
207     SH_AP_TABLE *hdr_out;    // headers to browser
208 #endif
209 };
210
211 // create a request record
212 static shib_request_config *init_request_config(request_rec *r)
213 {
214     shib_request_config* rc=(shib_request_config*)ap_pcalloc(r->pool,sizeof(shib_request_config));
215     ap_set_module_config (r->request_config, &mod_shib, rc);
216     memset(rc, 0, sizeof(shib_request_config));
217     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_init_rc\n");
218     return rc;
219 }
220
221 // generic global slot handlers
222 extern "C" const char* ap_set_global_string_slot(cmd_parms* parms, void*, const char* arg)
223 {
224     *((char**)(parms->info))=ap_pstrdup(parms->pool,arg);
225     return NULL;
226 }
227
228 extern "C" const char* shib_set_server_string_slot(cmd_parms* parms, void*, const char* arg)
229 {
230     char* base=(char*)ap_get_module_config(parms->server->module_config,&mod_shib);
231     long offset=(long)parms->info;
232     *((char**)(base + offset))=ap_pstrdup(parms->pool,arg);
233     return NULL;
234 }
235
236 extern "C" const char* shib_ap_set_file_slot(cmd_parms* parms,
237 #ifdef SHIB_APACHE_13
238                                              char* arg1, char* arg2
239 #else
240                                              void* arg1, const char* arg2
241 #endif
242                                              )
243 {
244   ap_set_file_slot(parms, arg1, arg2);
245   return DECLINE_CMD;
246 }
247
248 /********************************************************************************/
249 // Apache ShibTarget subclass(es) here.
250
251 class ShibTargetApache : public ShibTarget
252 {
253 public:
254   ShibTargetApache(request_rec* req, bool handler) : m_handler(handler) {
255     m_sc = (shib_server_config*)ap_get_module_config(req->server->module_config, &mod_shib);
256     m_dc = (shib_dir_config*)ap_get_module_config(req->per_dir_config, &mod_shib);
257     m_rc = (shib_request_config*)ap_get_module_config(req->request_config, &mod_shib);
258
259     init(
260         m_sc->szScheme ? m_sc->szScheme : ap_http_method(req),
261             ap_get_server_name(req),
262         (int)ap_get_server_port(req),
263             req->unparsed_uri,
264         ap_table_get(req->headers_in, "Content-type"),
265             req->connection->remote_ip,
266         req->method
267         );
268
269     m_req = req;
270   }
271   ~ShibTargetApache() { }
272
273   virtual void log(ShibLogLevel level, const string &msg) {
274     ShibTarget::log(level,msg);
275 #ifdef SHIB_APACHE_13
276     ap_log_rerror(APLOG_MARK,
277         (level == LogLevelDebug ? APLOG_DEBUG :
278             (level == LogLevelInfo ? APLOG_INFO :
279             (level == LogLevelWarn ? APLOG_WARNING : APLOG_ERR)))|APLOG_NOERRNO, SH_AP_R(m_req), msg.c_str());
280 #else
281     if (level == LogLevelError)
282         ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(m_req), msg.c_str());
283 #endif
284   }
285   virtual string getCookies(void) const {
286     const char *c = ap_table_get(m_req->headers_in, "Cookie");
287     return string(c ? c : "");
288   }
289   virtual void setCookie(const string &name, const string &value) {
290     char* val = ap_psprintf(m_req->pool, "%s=%s", name.c_str(), value.c_str());
291 #ifdef SHIB_DEFERRED_HEADERS
292     if (!m_rc) {
293       // this happens on subrequests
294       ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_setheader: no_m_rc");
295       m_rc = init_request_config(m_req);
296     }
297     if (m_handler)
298         ap_table_addn(m_rc->hdr_out, "Set-Cookie", val);
299     else
300 #endif
301     ap_table_addn(m_req->err_headers_out, "Set-Cookie", val);
302   }
303   virtual string getArgs(void) { return string(m_req->args ? m_req->args : ""); }
304   virtual string getPostData(void) {
305     // Read the posted data
306 #ifdef SHIB_APACHE_13
307     if (ap_setup_client_block(m_req, REQUEST_CHUNKED_DECHUNK))
308         throw FatalProfileException("Apache function (setup_client_block) failed while reading profile submission.");
309     if (!ap_should_client_block(m_req))
310         throw FatalProfileException("Apache function (should_client_block) failed while reading profile submission.");
311     if (m_req->remaining > 1024*1024)
312         throw FatalProfileException("Blocked too-large a submission to profile endpoint.");
313     int len;
314     string cgistr;
315     char buff[HUGE_STRING_LEN];
316     ap_hard_timeout("[mod_shib] getPostData", m_req);
317     while ((len=ap_get_client_block(m_req, buff, sizeof(buff))) > 0) {
318       ap_reset_timeout(m_req);
319       cgistr.append(buff, len);
320     }
321     ap_kill_timeout(m_req);
322     return cgistr;
323 #else
324     string cgistr;
325     const char *data;
326     apr_size_t len;
327     int seen_eos = 0;
328     apr_bucket_brigade* bb = apr_brigade_create(m_req->pool, m_req->connection->bucket_alloc);
329     do {
330         apr_bucket *bucket;
331         apr_status_t rv = ap_get_brigade(m_req->input_filters, bb, AP_MODE_READBYTES, APR_BLOCK_READ, HUGE_STRING_LEN);
332         if (rv != APR_SUCCESS)
333             throw FatalProfileException("Apache function (ap_get_brigade) failed while reading profile submission.");
334
335         for (bucket = APR_BRIGADE_FIRST(bb); bucket != APR_BRIGADE_SENTINEL(bb); bucket = APR_BUCKET_NEXT(bucket)) {
336             if (APR_BUCKET_IS_EOS(bucket)) {
337                 seen_eos = 1;
338                 break;
339             }
340
341             /* We can't do much with this. */
342             if (APR_BUCKET_IS_FLUSH(bucket))
343                 continue;
344
345             /* read */
346             apr_bucket_read(bucket, &data, &len, APR_BLOCK_READ);
347             if (len > 0)
348                 cgistr.append(data, len);
349         }
350         apr_brigade_cleanup(bb);
351     } while (!seen_eos);
352     apr_brigade_destroy(bb);
353     return cgistr;
354 #endif
355   }
356   virtual void clearHeader(const string &name) {
357     if (m_dc->bUseEnvVars == 1) {
358         // ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_clear_header: env");
359         if (m_rc && m_rc->env) ap_table_unset(m_rc->env, name.c_str());
360     }
361     if (m_dc->bUseHeaders != 0) {
362         // ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_clear_header: hdr");
363         if (g_checkSpoofing && ap_is_initial_req(m_req)) {
364             if (m_allhttp.empty()) {
365                 // First time, so populate set with "CGI" versions of client-supplied headers.
366 #ifdef SHIB_APACHE_13
367                 array_header *hdrs_arr = ap_table_elts(m_req->headers_in);
368                 table_entry *hdrs = (table_entry *) hdrs_arr->elts;
369 #else
370                 const apr_array_header_t *hdrs_arr = apr_table_elts(m_req->headers_in);
371                 const apr_table_entry_t *hdrs = (const apr_table_entry_t *) hdrs_arr->elts;
372 #endif
373                 for (int i = 0; i < hdrs_arr->nelts; ++i) {
374                     if (!hdrs[i].key)
375                         continue;
376                     string cgiversion("HTTP_");
377                     const char* pch = hdrs[i].key;
378                     while (*pch) {
379                         cgiversion += (isalnum(*pch) ? toupper(*pch) : '_');
380                         pch++;
381                     }
382                     m_allhttp.insert(cgiversion);
383                 }
384             }
385
386             // Map to the expected CGI variable name.
387             string transformed("HTTP_");
388             const char* pch = name.c_str();
389             while (*pch) {
390                 transformed += (isalnum(*pch) ? toupper(*pch) : '_');
391                 pch++;
392             }
393             if (m_allhttp.count(transformed) > 0)
394                 throw SAMLException("Attempt to spoof header ($1) was detected.", params(1, name.c_str()));
395         }
396
397         ap_table_unset(m_req->headers_in, name.c_str());
398         ap_table_set(m_req->headers_in, name.c_str(), g_unsetHeaderValue.c_str());
399     }
400   }
401   virtual void setHeader(const string &name, const string &value) {
402     if (m_dc->bUseEnvVars == 1) {
403        if (!m_rc) {
404           // this happens on subrequests
405           ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_setheader: no_m_rc");
406           m_rc = init_request_config(m_req);
407        }
408        if (!m_rc->env)
409            m_rc->env = ap_make_table(m_req->pool, 10);
410        //ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_set_env: %s=%s", name.c_str(), value.c_str()?value.c_str():"Null");
411        ap_table_set(m_rc->env, name.c_str(), value.c_str() ? value.c_str() : "");
412     }
413     if (m_dc->bUseHeaders != 0) {
414        //ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_set_hdr: %s=%s", name.c_str(), value.c_str()?value.c_str():"Null");
415        ap_table_set(m_req->headers_in, name.c_str(), value.c_str() ? value.c_str() : "");
416     }
417   }
418   virtual string getHeader(const string &name) {
419     const char *hdr;
420     if (m_dc->bUseEnvVars == 1) {
421        if (m_rc && m_rc->env)
422            hdr = ap_table_get(m_rc->env, name.c_str());
423        else
424            hdr = NULL;
425        //ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_get_hdr_env: %s=%s", name.c_str(), hdr?hdr:"NULL");
426     }
427     else {
428        hdr = ap_table_get(m_req->headers_in, name.c_str());
429        //ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_get_hdr: %s=%s", name.c_str(), hdr?hdr:"NULL");
430     }
431     return string(hdr ? hdr : "");
432   }
433   virtual void setRemoteUser(const string &user) {
434     SH_AP_USER(m_req) = ap_pstrdup(m_req->pool, user.c_str());
435   }
436   virtual string getRemoteUser(void) {
437     return string(SH_AP_USER(m_req) ? SH_AP_USER(m_req) : "");
438   }
439   virtual void* sendPage(
440     const string& msg,
441     int code=200,
442     const string& content_type="text/html",
443         const Iterator<header_t>& headers=EMPTY(header_t)
444     ) {
445     m_req->content_type = ap_psprintf(m_req->pool, content_type.c_str());
446     while (headers.hasNext()) {
447         const header_t& h=headers.next();
448         ap_table_set(m_req->headers_out, h.first.c_str(), h.second.c_str());
449     }
450     ap_send_http_header(m_req);
451     ap_rprintf(m_req, msg.c_str());
452     return (void*)((code==200) ? DONE : code);
453   }
454   virtual void* sendRedirect(const string& url) {
455     ap_table_set(m_req->headers_out, "Location", url.c_str());
456     return (void*)REDIRECT;
457   }
458   virtual void* returnDecline(void) { return (void*)DECLINED; }
459   virtual void* returnOK(void) { return (void*)OK; }
460
461   bool m_handler;
462   request_rec* m_req;
463   shib_dir_config* m_dc;
464   shib_server_config* m_sc;
465   shib_request_config* m_rc;
466   set<string> m_allhttp;
467 };
468
469 /********************************************************************************/
470 // Apache handlers
471
472 extern "C" int shib_check_user(request_rec* r)
473 {
474     // Short-circuit entirely?
475     if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
476         return DECLINED;
477         
478     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_check_user(%d): ENTER", (int)getpid());
479     
480     ostringstream threadid;
481     threadid << "[" << getpid() << "] shib_check_user" << '\0';
482     saml::NDC ndc(threadid.str().c_str());
483     
484     try {
485         ShibTargetApache sta(r, false);
486     
487         // Check user authentication and export information, then set the handler bypass
488         pair<bool,void*> res = sta.doCheckAuthN(true);
489         apr_pool_userdata_setn((const void*)42,g_UserDataKey,NULL,r->pool);
490         if (res.first) return (int)(long)res.second;
491     
492         // user auth was okay -- export the assertions now
493         res = sta.doExportAssertions();
494         if (res.first) return (int)(long)res.second;
495     
496         // export happened successfully..  this user is ok.
497         return OK;
498     }
499     catch (exception& e) {
500         ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user threw an exception: %s", e.what());
501         return SERVER_ERROR;
502     }
503     catch (...) {
504         if (g_catchAll) {
505             ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user threw an uncaught exception!");
506             return SERVER_ERROR;
507         }
508         throw;
509     }
510 }
511
512 extern "C" int shib_handler(request_rec* r)
513 {
514     // Short-circuit entirely?
515     if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
516         return DECLINED;
517     
518     ostringstream threadid;
519     threadid << "[" << getpid() << "] shib_handler" << '\0';
520     saml::NDC ndc(threadid.str().c_str());
521
522 #ifndef SHIB_APACHE_13
523     // With 2.x, this handler always runs, though last.
524     // We check if shib_check_user ran, because it will detect a handler request
525     // and dispatch it directly.
526     void* data;
527     apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
528     if (data==(const void*)42) {
529         ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler skipped since check_user ran");
530         return DECLINED;
531     }
532 #endif
533
534     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler(%d): ENTER: %s", (int)getpid(), r->handler);
535
536     try {
537         ShibTargetApache sta(r, true);
538     
539         pair<bool,void*> res = sta.doHandler();
540         if (res.first) return (int)(long)res.second;
541     
542         ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "doHandler() did not do anything.");
543         return SERVER_ERROR;
544     }
545     catch (exception& e) {
546         ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler threw an exception: %s", e.what());
547         return SERVER_ERROR;
548     }
549     catch (...) {
550         if (g_catchAll) {
551             ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler threw an uncaught exception!");
552             return SERVER_ERROR;
553         }
554         throw;
555     }
556 }
557
558 /*
559  * shib_auth_checker() -- a simple resource manager to
560  * process the .htaccess settings
561  */
562 extern "C" int shib_auth_checker(request_rec* r)
563 {
564     // Short-circuit entirely?
565     if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
566         return DECLINED;
567     
568     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_auth_checker(%d): ENTER", (int)getpid());
569     
570     ostringstream threadid;
571     threadid << "[" << getpid() << "] shib_auth_checker" << '\0';
572     saml::NDC ndc(threadid.str().c_str());
573     
574     try {
575         ShibTargetApache sta(r, false);
576     
577         pair<bool,void*> res = sta.doCheckAuthZ();
578         if (res.first) return (int)(long)res.second;
579     
580         // We're all okay.
581         return OK;
582     }
583     catch (exception& e) {
584         ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an exception: %s", e.what());
585         return SERVER_ERROR;
586     }
587     catch (...) {
588         if (g_catchAll) {
589             ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an uncaught exception!");
590             return SERVER_ERROR;
591         }
592         throw;
593     }
594 }
595
596 // Access control plugin that enforces htaccess rules
597 class htAccessControl : virtual public IAccessControl
598 {
599 public:
600     htAccessControl() {}
601     ~htAccessControl() {}
602     void lock() {}
603     void unlock() {}
604     bool authorized(
605         ShibTarget* st,
606         ISessionCacheEntry* entry
607     ) const;
608 };
609
610 IPlugIn* htAccessFactory(const DOMElement* e)
611 {
612     return new htAccessControl();
613 }
614
615 class ApacheRequestMapper : public virtual IRequestMapper, public virtual IPropertySet
616 {
617 public:
618     ApacheRequestMapper(const DOMElement* e);
619     ~ApacheRequestMapper() { delete m_mapper; delete m_htaccess; delete m_staKey; delete m_propsKey; }
620     void lock() { m_mapper->lock(); }
621     void unlock() { m_staKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
622     Settings getSettings(ShibTarget* st) const;
623     
624     pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
625     pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
626     pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
627     pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
628     pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
629     const IPropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
630     const DOMElement* getElement() const;
631
632 private:
633     IRequestMapper* m_mapper;
634     ThreadKey* m_staKey;
635     ThreadKey* m_propsKey;
636     IAccessControl* m_htaccess;
637 };
638
639 IPlugIn* ApacheRequestMapFactory(const DOMElement* e)
640 {
641     return new ApacheRequestMapper(e);
642 }
643
644 ApacheRequestMapper::ApacheRequestMapper(const DOMElement* e) : m_mapper(NULL), m_staKey(NULL), m_propsKey(NULL), m_htaccess(NULL)
645 {
646     IPlugIn* p=saml::SAMLConfig::getConfig().getPlugMgr().newPlugin(shibtarget::XML::XMLRequestMapType,e);
647     m_mapper=dynamic_cast<IRequestMapper*>(p);
648     if (!m_mapper) {
649         delete p;
650         throw UnsupportedExtensionException("Embedded request mapper plugin was not of correct type.");
651     }
652     m_htaccess=new htAccessControl();
653     m_staKey=ThreadKey::create(NULL);
654     m_propsKey=ThreadKey::create(NULL);
655 }
656
657 IRequestMapper::Settings ApacheRequestMapper::getSettings(ShibTarget* st) const
658 {
659     Settings s=m_mapper->getSettings(st);
660     m_staKey->setData(dynamic_cast<ShibTargetApache*>(st));
661     m_propsKey->setData((void*)s.first);
662     return pair<const IPropertySet*,IAccessControl*>(this,s.second ? s.second : m_htaccess);
663 }
664
665 pair<bool,bool> ApacheRequestMapper::getBool(const char* name, const char* ns) const
666 {
667     ShibTargetApache* sta=reinterpret_cast<ShibTargetApache*>(m_staKey->getData());
668     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
669     if (sta && !ns) {
670         // Override Apache-settable boolean properties.
671         if (name && !strcmp(name,"requireSession") && sta->m_dc->bRequireSession != -1)
672             return make_pair(true, sta->m_dc->bRequireSession==1);
673         else if (name && !strcmp(name,"exportAssertion") && sta->m_dc->bExportAssertion != -1)
674             return make_pair(true, sta->m_dc->bExportAssertion==1);
675     }
676     return s ? s->getBool(name,ns) : make_pair(false,false);
677 }
678
679 pair<bool,const char*> ApacheRequestMapper::getString(const char* name, const char* ns) const
680 {
681     ShibTargetApache* sta=reinterpret_cast<ShibTargetApache*>(m_staKey->getData());
682     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
683     if (sta && !ns) {
684         // Override Apache-settable string properties.
685         if (name && !strcmp(name,"authType")) {
686             const char *auth_type=ap_auth_type(sta->m_req);
687             if (auth_type) {
688                 // Check for Basic Hijack
689                 if (!strcasecmp(auth_type, "basic") && sta->m_dc->bBasicHijack == 1)
690                     auth_type = "shibboleth";
691                 return make_pair(true,auth_type);
692             }
693         }
694         else if (name && !strcmp(name,"applicationId") && sta->m_dc->szApplicationId)
695             return pair<bool,const char*>(true,sta->m_dc->szApplicationId);
696         else if (name && !strcmp(name,"requireSessionWith") && sta->m_dc->szRequireWith)
697             return pair<bool,const char*>(true,sta->m_dc->szRequireWith);
698         else if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
699             return pair<bool,const char*>(true,sta->m_dc->szRedirectToSSL);
700     }
701     return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
702 }
703
704 pair<bool,const XMLCh*> ApacheRequestMapper::getXMLString(const char* name, const char* ns) const
705 {
706     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
707     return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
708 }
709
710 pair<bool,unsigned int> ApacheRequestMapper::getUnsignedInt(const char* name, const char* ns) const
711 {
712     ShibTargetApache* sta=reinterpret_cast<ShibTargetApache*>(m_staKey->getData());
713     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
714     if (sta && !ns) {
715         // Override Apache-settable int properties.
716         if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
717             return pair<bool,unsigned int>(true,strtol(sta->m_dc->szRedirectToSSL,NULL,10));
718     }
719     return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
720 }
721
722 pair<bool,int> ApacheRequestMapper::getInt(const char* name, const char* ns) const
723 {
724     ShibTargetApache* sta=reinterpret_cast<ShibTargetApache*>(m_staKey->getData());
725     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
726     if (sta && !ns) {
727         // Override Apache-settable int properties.
728         if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
729             return pair<bool,int>(true,atoi(sta->m_dc->szRedirectToSSL));
730     }
731     return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
732 }
733
734 const IPropertySet* ApacheRequestMapper::getPropertySet(const char* name, const char* ns) const
735 {
736     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
737     return s ? s->getPropertySet(name,ns) : NULL;
738 }
739
740 const DOMElement* ApacheRequestMapper::getElement() const
741 {
742     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
743     return s ? s->getElement() : NULL;
744 }
745
746 static SH_AP_TABLE* groups_for_user(request_rec* r, const char* user, char* grpfile)
747 {
748     SH_AP_CONFIGFILE* f;
749     SH_AP_TABLE* grps=ap_make_table(r->pool,15);
750     char l[MAX_STRING_LEN];
751     const char *group_name, *ll, *w;
752
753 #ifdef SHIB_APACHE_13
754     if (!(f=ap_pcfg_openfile(r->pool,grpfile))) {
755 #else
756     if (ap_pcfg_openfile(&f,r->pool,grpfile) != APR_SUCCESS) {
757 #endif
758         ap_log_rerror(APLOG_MARK,APLOG_DEBUG,SH_AP_R(r),"groups_for_user() could not open group file: %s",grpfile);
759         return NULL;
760     }
761
762     SH_AP_POOL* sp;
763 #ifdef SHIB_APACHE_13
764     sp=ap_make_sub_pool(r->pool);
765 #else
766     if (apr_pool_create(&sp,r->pool) != APR_SUCCESS) {
767         ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,
768             "groups_for_user() could not create a subpool");
769         return NULL;
770     }
771 #endif
772
773     while (!(ap_cfg_getline(l,MAX_STRING_LEN,f))) {
774         if ((*l=='#') || (!*l))
775             continue;
776         ll = l;
777         ap_clear_pool(sp);
778
779         group_name=ap_getword(sp,&ll,':');
780
781         while (*ll) {
782             w=ap_getword_conf(sp,&ll);
783             if (!strcmp(w,user)) {
784                 ap_table_setn(grps,ap_pstrdup(r->pool,group_name),"in");
785                 break;
786             }
787         }
788     }
789     ap_cfg_closefile(f);
790     ap_destroy_pool(sp);
791     return grps;
792 }
793
794 bool htAccessControl::authorized(
795     ShibTarget* st,
796     ISessionCacheEntry* entry
797 ) const
798 {
799     // Make sure the object is our type.
800     ShibTargetApache* sta=dynamic_cast<ShibTargetApache*>(st);
801     if (!sta)
802         throw ConfigurationException("Request wrapper object was not of correct type.");
803
804     // mod_auth clone
805
806     int m=sta->m_req->method_number;
807     bool method_restricted=false;
808     const char *t, *w;
809     
810     const array_header* reqs_arr=ap_requires(sta->m_req);
811     if (!reqs_arr)
812         return true;
813
814     require_line* reqs=(require_line*)reqs_arr->elts;
815     
816     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(sta->m_req),"REQUIRE nelts: %d", reqs_arr->nelts);
817     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(sta->m_req),"REQUIRE all: %d", sta->m_dc->bRequireAll);
818
819     vector<bool> auth_OK(reqs_arr->nelts,false);
820
821 #define SHIB_AP_CHECK_IS_OK {           \
822      if (sta->m_dc->bRequireAll < 1)    \
823          return true;                   \
824      auth_OK[x] = true;                 \
825      continue;                          \
826 }
827
828     for (int x=0; x<reqs_arr->nelts; x++) {
829         auth_OK[x] = false;
830         if (!(reqs[x].method_mask & (1 << m)))
831             continue;
832         method_restricted=true;
833         string remote_user = st->getRemoteUser();
834
835         t = reqs[x].requirement;
836         w = ap_getword_white(sta->m_req->pool, &t);
837
838         if (!strcasecmp(w,"shibboleth")) {
839             // This is a dummy rule needed because Apache conflates authn and authz.
840             // Without some require rule, AuthType is ignored and no check_user hooks run.
841             SHIB_AP_CHECK_IS_OK;
842         }
843         else if (!strcmp(w,"valid-user")) {
844             if (entry) {
845                 st->log(ShibTarget::LogLevelDebug,"htAccessControl plugin accepting valid-user based on active session");
846                 SHIB_AP_CHECK_IS_OK;
847             }
848             else
849                 st->log(ShibTarget::LogLevelError,"htAccessControl plugin rejecting access for valid-user rule, no session is active");
850         }
851         else if (!strcmp(w,"user") && !remote_user.empty()) {
852             bool regexp=false;
853             while (*t) {
854                 w=ap_getword_conf(sta->m_req->pool,&t);
855                 if (*w=='~') {
856                     regexp=true;
857                     continue;
858                 }
859                 
860                 if (regexp) {
861                     try {
862                         // To do regex matching, we have to convert from UTF-8.
863                         auto_ptr<XMLCh> trans(fromUTF8(w));
864                         RegularExpression re(trans.get());
865                         auto_ptr<XMLCh> trans2(fromUTF8(remote_user.c_str()));
866                         if (re.matches(trans2.get())) {
867                             st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin accepting user (") + w + ")");
868                             SHIB_AP_CHECK_IS_OK;
869                         }
870                     }
871                     catch (XMLException& ex) {
872                         auto_ptr_char tmp(ex.getMessage());
873                         st->log(ShibTarget::LogLevelError,
874                             string("htAccessControl plugin caught exception while parsing regular expression (") + w + "): " + tmp.get());
875                     }
876                 }
877                 else if (remote_user==w) {
878                     st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin accepting user (") + w + ")");
879                     SHIB_AP_CHECK_IS_OK;
880                 }
881             }
882         }
883         else if (!strcmp(w,"group")) {
884             SH_AP_TABLE* grpstatus=NULL;
885             if (sta->m_dc->szAuthGrpFile && !remote_user.empty()) {
886                 st->log(ShibTarget::LogLevelDebug,string("htAccessControl plugin using groups file: ") + sta->m_dc->szAuthGrpFile);
887                 grpstatus=groups_for_user(sta->m_req,remote_user.c_str(),sta->m_dc->szAuthGrpFile);
888             }
889             if (!grpstatus)
890                 return false;
891     
892             while (*t) {
893                 w=ap_getword_conf(sta->m_req->pool,&t);
894                 if (ap_table_get(grpstatus,w)) {
895                     st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin accepting group (") + w + ")");
896                     SHIB_AP_CHECK_IS_OK;
897                 }
898             }
899         }
900         else {
901             Iterator<IAAP*> provs=st->getApplication()->getAAPProviders();
902             AAP wrapper(provs,w);
903             if (wrapper.fail()) {
904                 st->log(ShibTarget::LogLevelWarn, string("htAccessControl plugin didn't recognize require rule: ") + w);
905                 continue;
906             }
907
908             bool regexp=false;
909             const char* vals;
910             if (!strcmp(wrapper->getHeader(),"REMOTE_USER"))
911                 vals=remote_user.c_str();
912             else
913                 if (sta->m_dc->bUseEnvVars==1) {
914                    if (sta->m_rc && sta->m_rc->env) vals=ap_table_get(sta->m_rc->env,wrapper->getHeader());
915                    else vals = NULL;
916                 } else {
917                    vals=ap_table_get(sta->m_req->headers_in,wrapper->getHeader());
918                 }
919
920             while (*t && vals && *vals) {
921                 w=ap_getword_conf(sta->m_req->pool,&t);
922                 if (*w=='~') {
923                     regexp=true;
924                     continue;
925                 }
926
927                 try {
928                     auto_ptr<RegularExpression> re;
929                     if (regexp) {
930                         delete re.release();
931                         auto_ptr<XMLCh> trans(fromUTF8(w));
932                         auto_ptr<RegularExpression> temp(new RegularExpression(trans.get()));
933                         re=temp;
934                     }
935                     
936                     string vals_str(vals);
937                     unsigned int j = 0;
938                     for (unsigned int i = 0;  i < vals_str.length();  i++) {
939                         if (vals_str.at(i) == ';') {
940                             if (i == 0) {
941                                 st->log(ShibTarget::LogLevelError, string("htAccessControl plugin found invalid header encoding (") +
942                                     vals + "): starts with a semicolon");
943                                 throw SAMLException("Invalid information supplied to authorization plugin.");
944                             }
945
946                             if (vals_str.at(i-1) == '\\') {
947                                 vals_str.erase(i-1, 1);
948                                 i--;
949                                 continue;
950                             }
951
952                             string val = vals_str.substr(j, i-j);
953                             j = i+1;
954                             if (regexp) {
955                                 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
956                                 if (re->matches(trans.get())) {
957                                     st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
958                                        ", got " + val + ": authorization granted");
959                                     SHIB_AP_CHECK_IS_OK;
960                                 }
961                             }
962                             else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
963                                 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
964                                     ", got " + val + ": authorization granted.");
965                                 SHIB_AP_CHECK_IS_OK;
966                             }
967                             else {
968                                 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
969                                     ", got " + val + ": authorization not granted.");
970                             }
971                         }
972                     }
973     
974                     string val = vals_str.substr(j, vals_str.length()-j);
975                     if (regexp) {
976                         auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
977                         if (re->matches(trans.get())) {
978                             st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
979                                 ", got " + val + ": authorization granted.");
980                             SHIB_AP_CHECK_IS_OK;
981                         }
982                     }
983                     else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
984                         st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
985                             ", got " + val + ": authorization granted");
986                         SHIB_AP_CHECK_IS_OK;
987                     }
988                     else {
989                             st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
990                                 ", got " + val + ": authorization not granted");
991                     }
992                 }
993                 catch (XMLException& ex) {
994                     auto_ptr_char tmp(ex.getMessage());
995                     st->log(ShibTarget::LogLevelError, string("htAccessControl plugin caught exception while parsing regular expression (")
996                         + w + "): " + tmp.get());
997                 }
998             }
999         }
1000     }
1001
1002     // check if all require directives are true
1003     bool auth_all_OK = true;
1004     for (int i= 0; i<reqs_arr->nelts; i++) {
1005         auth_all_OK &= auth_OK[i];
1006     }
1007     if (auth_all_OK || !method_restricted)
1008         return true;
1009
1010     return false;
1011 }
1012
1013 // Initial look at a request - create the per-request structure
1014 static int shib_post_read(request_rec *r)
1015 {
1016     shib_request_config* rc = init_request_config(r);
1017
1018     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_post_read");
1019
1020 #ifdef SHIB_DEFERRED_HEADERS
1021     rc->hdr_out = ap_make_table(r->pool, 5);
1022 #endif
1023     return DECLINED;
1024 }
1025
1026 // fixups: set environment vars
1027
1028 extern "C" int shib_fixups(request_rec* r)
1029 {
1030   shib_request_config *rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
1031   shib_dir_config *dc = (shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib);
1032   if (dc->bOff==1 || dc->bUseEnvVars!=1) 
1033     return DECLINED;
1034     
1035   ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_fixup(%d): ENTER", (int)getpid());
1036
1037   if (rc==NULL || rc->env==NULL || ap_is_empty_table(rc->env))
1038         return DECLINED;
1039
1040   ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_fixup adding %d vars", ap_table_elts(rc->env)->nelts);
1041   r->subprocess_env = ap_overlay_tables(r->pool, r->subprocess_env, rc->env);
1042
1043   return OK;
1044 }
1045
1046 #ifdef SHIB_APACHE_13
1047 /*
1048  * shib_child_exit()
1049  *  Cleanup the (per-process) pool info.
1050  */
1051 extern "C" void shib_child_exit(server_rec* s, SH_AP_POOL* p)
1052 {
1053     if (g_Config) {
1054         ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit(%d) dealing with g_Config..", (int)getpid());
1055         g_Config->shutdown();
1056         g_Config = NULL;
1057         ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit() done");
1058     }
1059 }
1060 #else
1061 /*
1062  * shib_exit()
1063  *  Apache 2.x doesn't allow for per-child cleanup, causes CGI forks to hang.
1064  */
1065 extern "C" apr_status_t shib_exit(void* data)
1066 {
1067     if (g_Config) {
1068         g_Config->shutdown();
1069         g_Config = NULL;
1070     }
1071     ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,0,NULL,"shib_exit() done");
1072     return OK;
1073 }
1074 #endif
1075
1076 /* 
1077  * shire_child_init()
1078  *  Things to do when the child process is initialized.
1079  *  (or after the configs are read in apache-2)
1080  */
1081 #ifdef SHIB_APACHE_13
1082 extern "C" void shib_child_init(server_rec* s, SH_AP_POOL* p)
1083 #else
1084 extern "C" void shib_child_init(apr_pool_t* p, server_rec* s)
1085 #endif
1086 {
1087     // Initialize runtime components.
1088
1089     ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init(%d) starting", (int)getpid());
1090
1091     if (g_Config) {
1092         ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() already initialized!");
1093         exit(1);
1094     }
1095
1096     try {
1097         g_Config=&ShibTargetConfig::getConfig();
1098         g_Config->setFeatures(
1099             ShibTargetConfig::Listener |
1100             ShibTargetConfig::Metadata |
1101             ShibTargetConfig::AAP |
1102             ShibTargetConfig::RequestMapper |
1103             ShibTargetConfig::LocalExtensions |
1104             ShibTargetConfig::Logging
1105             );
1106         if (!g_Config->init(g_szSchemaDir)) {
1107             ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize libraries");
1108             exit(1);
1109         }
1110         PlugManager& mgr = SAMLConfig::getConfig().getPlugMgr();
1111         mgr.regFactory(shibtarget::XML::htAccessControlType,&htAccessFactory);
1112         mgr.regFactory(shibtarget::XML::NativeRequestMapType,&ApacheRequestMapFactory);
1113         // We hijack the legacy type so that 1.2 config files will load this plugin
1114         mgr.regFactory(shibtarget::XML::LegacyRequestMapType,&ApacheRequestMapFactory);
1115         
1116         if (!g_Config->load(g_szSHIBConfig)) {
1117             ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to load configuration");
1118             exit(1);
1119         }
1120
1121         IConfig* conf=g_Config->getINI();
1122         saml::Locker locker(conf);
1123         const IPropertySet* props=conf->getPropertySet("Local");
1124         if (props) {
1125             pair<bool,const char*> unsetValue=props->getString("unsetHeaderValue");
1126             if (unsetValue.first)
1127                 g_unsetHeaderValue = unsetValue.second;
1128             pair<bool,bool> flag=props->getBool("checkSpoofing");
1129             g_checkSpoofing = !flag.first || flag.second;
1130             flag=props->getBool("catchAll");
1131             g_catchAll = !flag.first || flag.second;
1132         }
1133     }
1134     catch (exception&) {
1135         ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize system");
1136         exit(1);
1137     }
1138
1139     // Set the cleanup handler
1140     apr_pool_cleanup_register(p, NULL, &shib_exit, apr_pool_cleanup_null);
1141
1142     ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() done");
1143 }
1144
1145 // Output filters 
1146 #ifdef SHIB_DEFERRED_HEADERS
1147 static void set_output_filter(request_rec *r)
1148 {
1149     ap_add_output_filter("SHIB_HEADERS_OUT", NULL, r, r->connection);
1150 }
1151
1152 static void set_error_filter(request_rec *r)
1153 {
1154     ap_add_output_filter("SHIB_HEADERS_ERR", NULL, r, r->connection);
1155 }
1156
1157 static int _table_add(void *v, const char *key, const char *value)       
1158 {        
1159     apr_table_addn((apr_table_t*)v, key, value);         
1160     return 1;    
1161 }        
1162          
1163 static apr_status_t do_output_filter(ap_filter_t *f, apr_bucket_brigade *in)
1164 {
1165     request_rec *r = f->r;
1166     shib_request_config *rc = (shib_request_config*) ap_get_module_config(r->request_config, &mod_shib);
1167
1168     if (rc) {
1169         ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_out_filter: merging %d headers", apr_table_elts(rc->hdr_out)->nelts);
1170         apr_table_do(_table_add,r->headers_out, rc->hdr_out,NULL);
1171         // can't use overlap call because it will collapse Set-Cookie headers
1172         // apr_table_overlap(r->headers_out, rc->hdr_out, APR_OVERLAP_TABLES_MERGE);
1173     }
1174
1175     /* remove ourselves from the filter chain */
1176     ap_remove_output_filter(f);
1177
1178     /* send the data up the stack */
1179     return ap_pass_brigade(f->next,in);
1180 }
1181
1182 static apr_status_t do_error_filter(ap_filter_t *f, apr_bucket_brigade *in)
1183 {
1184     request_rec *r = f->r;
1185     shib_request_config *rc = (shib_request_config*) ap_get_module_config(r->request_config, &mod_shib);
1186
1187     if (rc) {
1188         ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_err_filter: merging %d headers", apr_table_elts(rc->hdr_out)->nelts);
1189         apr_table_do(_table_add,r->err_headers_out, rc->hdr_out,NULL);
1190         // can't use overlap call because it will collapse Set-Cookie headers
1191         // apr_table_overlap(r->err_headers_out, rc->hdr_err, APR_OVERLAP_TABLES_MERGE);
1192     }
1193
1194     /* remove ourselves from the filter chain */
1195     ap_remove_output_filter(f);
1196
1197     /* send the data up the stack */
1198     return ap_pass_brigade(f->next,in);
1199 }
1200 #endif // SHIB_DEFERRED_HEADERS
1201
1202
1203 typedef const char* (*config_fn_t)(void);
1204
1205 #ifdef SHIB_APACHE_13
1206
1207 // SHIB Module commands
1208
1209 static command_rec shire_cmds[] = {
1210   {"SHIREConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1211    RSRC_CONF, TAKE1, "Path to shibboleth.xml config file"},
1212   {"ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1213    RSRC_CONF, TAKE1, "Path to shibboleth.xml config file"},
1214   {"ShibSchemaDir", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1215    RSRC_CONF, TAKE1, "Path to Shibboleth XML schema directory"},
1216
1217   {"ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
1218    (void *) XtOffsetOf (shib_server_config, szScheme),
1219    RSRC_CONF, TAKE1, "URL scheme to force into generated URLs for a vhost"},
1220    
1221   {"ShibDisable", (config_fn_t)ap_set_flag_slot,
1222    (void *) XtOffsetOf (shib_dir_config, bOff),
1223    OR_AUTHCFG, FLAG, "Disable all Shib module activity here to save processing effort"},
1224   {"ShibApplicationId", (config_fn_t)ap_set_string_slot,
1225    (void *) XtOffsetOf (shib_dir_config, szApplicationId),
1226    OR_AUTHCFG, TAKE1, "Set Shibboleth applicationId property for content"},
1227   {"ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1228    (void *) XtOffsetOf (shib_dir_config, bBasicHijack),
1229    OR_AUTHCFG, FLAG, "Respond to AuthType Basic and convert to shibboleth"},
1230   {"ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1231    (void *) XtOffsetOf (shib_dir_config, bRequireSession),
1232    OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist"},
1233   {"ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
1234    (void *) XtOffsetOf (shib_dir_config, szRequireWith),
1235    OR_AUTHCFG, TAKE1, "Initiates a new session if one does not exist using a specific SessionInitiator"},
1236   {"ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1237    (void *) XtOffsetOf (shib_dir_config, bExportAssertion),
1238    OR_AUTHCFG, FLAG, "Export SAML attribute assertion(s) to Shib-Attributes header"},
1239   {"ShibRedirectToSSL", (config_fn_t)ap_set_string_slot,
1240    (void *) XtOffsetOf (shib_dir_config, szRedirectToSSL),
1241    OR_AUTHCFG, TAKE1, "Redirect non-SSL requests to designated port" },
1242   {"AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
1243    (void *) XtOffsetOf (shib_dir_config, szAuthGrpFile),
1244    OR_AUTHCFG, TAKE1, "text file containing group names and member user IDs"},
1245   {"ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1246    (void *) XtOffsetOf (shib_dir_config, bRequireAll),
1247    OR_AUTHCFG, FLAG, "All require directives must match"},
1248   {"ShibUseEnvironment", (config_fn_t)ap_set_flag_slot,
1249    (void *) XtOffsetOf (shib_dir_config, bUseEnvVars),
1250    OR_AUTHCFG, FLAG, "Export attributes using environment variables"},
1251   {"ShibUseHeaders", (config_fn_t)ap_set_flag_slot,
1252    (void *) XtOffsetOf (shib_dir_config, bUseHeaders),
1253    OR_AUTHCFG, FLAG, "Export attributes using custom HTTP headers (default)"},
1254
1255   {NULL}
1256 };
1257
1258 extern "C"{
1259 handler_rec shib_handlers[] = {
1260   { "shib-handler", shib_handler },
1261   { NULL }
1262 };
1263
1264 module MODULE_VAR_EXPORT mod_shib = {
1265     STANDARD_MODULE_STUFF,
1266     NULL,                        /* initializer */
1267     create_shib_dir_config,     /* dir config creater */
1268     merge_shib_dir_config,      /* dir merger --- default is to override */
1269     create_shib_server_config, /* server config */
1270     merge_shib_server_config,   /* merge server config */
1271     shire_cmds,                 /* command table */
1272     shib_handlers,              /* handlers */
1273     NULL,                       /* filename translation */
1274     shib_check_user,            /* check_user_id */
1275     shib_auth_checker,          /* check auth */
1276     NULL,                       /* check access */
1277     NULL,                       /* type_checker */
1278     shib_fixups,                /* fixups */
1279     NULL,                       /* logger */
1280     NULL,                       /* header parser */
1281     shib_child_init,            /* child_init */
1282     shib_child_exit,            /* child_exit */
1283     shib_post_read              /* post read-request */
1284 };
1285
1286 #elif defined(SHIB_APACHE_20) || defined(SHIB_APACHE_22)
1287
1288 extern "C" void shib_register_hooks (apr_pool_t *p)
1289 {
1290 #ifdef SHIB_DEFERRED_HEADERS
1291   ap_register_output_filter("SHIB_HEADERS_OUT", do_output_filter, NULL, AP_FTYPE_CONTENT_SET);
1292   ap_hook_insert_filter(set_output_filter, NULL, NULL, APR_HOOK_LAST);
1293   ap_register_output_filter("SHIB_HEADERS_ERR", do_error_filter, NULL, AP_FTYPE_CONTENT_SET);
1294   ap_hook_insert_error_filter(set_error_filter, NULL, NULL, APR_HOOK_LAST);
1295   ap_hook_post_read_request(shib_post_read, NULL, NULL, APR_HOOK_MIDDLE);
1296 #endif
1297   ap_hook_child_init(shib_child_init, NULL, NULL, APR_HOOK_MIDDLE);
1298   ap_hook_check_user_id(shib_check_user, NULL, NULL, APR_HOOK_MIDDLE);
1299   ap_hook_auth_checker(shib_auth_checker, NULL, NULL, APR_HOOK_FIRST);
1300   ap_hook_handler(shib_handler, NULL, NULL, APR_HOOK_LAST);
1301   ap_hook_fixups(shib_fixups, NULL, NULL, APR_HOOK_MIDDLE);
1302 }
1303
1304 // SHIB Module commands
1305
1306 extern "C" {
1307 static command_rec shib_cmds[] = {
1308   AP_INIT_TAKE1("ShibConfig",
1309                 (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1310                 RSRC_CONF, "Path to shibboleth.xml config file"),
1311   AP_INIT_TAKE1("ShibSchemaDir",
1312      (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1313       RSRC_CONF, "Path to Shibboleth XML schema directory"),
1314
1315   AP_INIT_TAKE1("ShibURLScheme",
1316      (config_fn_t)shib_set_server_string_slot,
1317      (void *) offsetof (shib_server_config, szScheme),
1318       RSRC_CONF, "URL scheme to force into generated URLs for a vhost"),
1319
1320   AP_INIT_FLAG("ShibDisable", (config_fn_t)ap_set_flag_slot,
1321         (void *) offsetof (shib_dir_config, bOff),
1322         OR_AUTHCFG, "Disable all Shib module activity here to save processing effort"),
1323   AP_INIT_TAKE1("ShibApplicationId", (config_fn_t)ap_set_string_slot,
1324         (void *) offsetof (shib_dir_config, szApplicationId),
1325         OR_AUTHCFG, "Set Shibboleth applicationId property for content"),
1326   AP_INIT_FLAG("ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1327         (void *) offsetof (shib_dir_config, bBasicHijack),
1328         OR_AUTHCFG, "Respond to AuthType Basic and convert to shibboleth"),
1329   AP_INIT_FLAG("ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1330         (void *) offsetof (shib_dir_config, bRequireSession),
1331         OR_AUTHCFG, "Initiates a new session if one does not exist"),
1332   AP_INIT_TAKE1("ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
1333         (void *) offsetof (shib_dir_config, szRequireWith),
1334         OR_AUTHCFG, "Initiates a new session if one does not exist using a specific SessionInitiator"),
1335   AP_INIT_FLAG("ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1336         (void *) offsetof (shib_dir_config, bExportAssertion),
1337         OR_AUTHCFG, "Export SAML attribute assertion(s) to Shib-Attributes header"),
1338   AP_INIT_TAKE1("ShibRedirectToSSL", (config_fn_t)ap_set_string_slot,
1339         (void *) offsetof (shib_dir_config, szRedirectToSSL),
1340         OR_AUTHCFG, "Redirect non-SSL requests to designated port"),
1341   AP_INIT_TAKE1("AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
1342                 (void *) offsetof (shib_dir_config, szAuthGrpFile),
1343                 OR_AUTHCFG, "Text file containing group names and member user IDs"),
1344   AP_INIT_FLAG("ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1345         (void *) offsetof (shib_dir_config, bRequireAll),
1346         OR_AUTHCFG, "All require directives must match"),
1347   AP_INIT_FLAG("ShibUseEnvironment", (config_fn_t)ap_set_flag_slot,
1348         (void *) offsetof (shib_dir_config, bUseEnvVars),
1349         OR_AUTHCFG, "Export attributes using environment variables"),
1350   AP_INIT_FLAG("ShibUseHeaders", (config_fn_t)ap_set_flag_slot,
1351         (void *) offsetof (shib_dir_config, bUseHeaders),
1352         OR_AUTHCFG, "Export attributes using custom HTTP headers (default)"),
1353
1354   {NULL}
1355 };
1356
1357 module AP_MODULE_DECLARE_DATA mod_shib = {
1358     STANDARD20_MODULE_STUFF,
1359     create_shib_dir_config,     /* create dir config */
1360     merge_shib_dir_config,      /* merge dir config --- default is to override */
1361     create_shib_server_config,  /* create server config */
1362     merge_shib_server_config,   /* merge server config */
1363     shib_cmds,                  /* command table */
1364     shib_register_hooks         /* register hooks */
1365 };
1366
1367 #else
1368 #error "undefined APACHE version"
1369 #endif
1370
1371 }