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