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