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