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