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