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