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