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