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