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