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