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