Corrected Apache commands.
[shibboleth/sp.git] / apache / mod_apache.cpp
1 /*
2  * mod_apache.cpp -- the core Apache Module code
3  *
4  * Created by:  Derek Atkins <derek@ihtfp.com>
5  *
6  * $Id$
7  */
8
9 #ifdef SOLARIS2
10 #undef _XOPEN_SOURCE    // causes gethostname conflict in unistd.h
11 #endif
12
13 // SAML Runtime
14 #include <saml/saml.h>
15 #include <shib/shib.h>
16 #include <shib/shib-threads.h>
17 #include <shib-target/shib-target.h>
18 #include <xercesc/util/regx/RegularExpression.hpp>
19
20 #undef _XPG4_2
21
22 // Apache specific header files
23 #include <httpd.h>
24 #include <http_config.h>
25 #include <http_protocol.h>
26 #include <http_main.h>
27 #define CORE_PRIVATE
28 #include <http_core.h>
29 #include <http_log.h>
30
31 #ifndef SHIB_APACHE_13
32 #include <http_request.h>
33 #include <apr_strings.h>
34 #include <apr_pools.h>
35 #endif
36
37 #include <fstream>
38 #include <sstream>
39
40 #ifdef HAVE_UNISTD_H
41 #include <unistd.h>             // for getpid()
42 #endif
43
44 using namespace std;
45 using namespace saml;
46 using namespace shibboleth;
47 using namespace shibtarget;
48
49 extern "C" module MODULE_VAR_EXPORT mod_shib;
50
51 namespace {
52     char* g_szSHIBConfig = NULL;
53     char* g_szSchemaDir = NULL;
54     ShibTargetConfig* g_Config = NULL;
55     static const char* g_UserDataKey = "_shib_check_user_";
56 }
57
58 /********************************************************************************/
59 // Basic Apache Configuration code.
60 //
61
62 // per-server module configuration structure
63 struct shib_server_config
64 {
65     char* szScheme;
66 };
67
68 // creates the per-server configuration
69 extern "C" void* create_shib_server_config(SH_AP_POOL* p, server_rec* s)
70 {
71     shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
72     sc->szScheme = NULL;
73     return sc;
74 }
75
76 // overrides server configuration in virtual servers
77 extern "C" void* merge_shib_server_config (SH_AP_POOL* p, void* base, void* sub)
78 {
79     shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
80     shib_server_config* parent=(shib_server_config*)base;
81     shib_server_config* child=(shib_server_config*)sub;
82
83     if (child->szScheme)
84         sc->szScheme=ap_pstrdup(p,child->szScheme);
85     else if (parent->szScheme)
86         sc->szScheme=ap_pstrdup(p,parent->szScheme);
87     else
88         sc->szScheme=NULL;
89
90     return sc;
91 }
92
93 // per-dir module configuration structure
94 struct shib_dir_config
95 {
96     // RM Configuration
97     char* szAuthGrpFile;    // Auth GroupFile name
98     int bRequireAll;        // all require directives must match, otherwise OR logic
99
100     // Content Configuration
101     char* szApplicationId;  // Shib applicationId value
102     char* szRequireWith;    // require a session using a specific initiator?
103     int bOff;               // flat-out disable all Shib processing
104     int bBasicHijack;       // activate for AuthType Basic?
105     int bRequireSession;    // require a session?
106     int bExportAssertion;   // export SAML assertion to the environment?
107 };
108
109 // creates per-directory config structure
110 extern "C" void* create_shib_dir_config (SH_AP_POOL* p, char* d)
111 {
112     shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
113     dc->bOff = -1;
114     dc->bBasicHijack = -1;
115     dc->bRequireSession = -1;
116     dc->bExportAssertion = -1;
117     dc->bRequireAll = -1;
118     dc->szAuthGrpFile = NULL;
119     dc->szApplicationId = NULL;
120     dc->szRequireWith = NULL;
121     return dc;
122 }
123
124 // overrides server configuration in directories
125 extern "C" void* merge_shib_dir_config (SH_AP_POOL* p, void* base, void* sub)
126 {
127     shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
128     shib_dir_config* parent=(shib_dir_config*)base;
129     shib_dir_config* child=(shib_dir_config*)sub;
130
131     if (child->szAuthGrpFile)
132         dc->szAuthGrpFile=ap_pstrdup(p,child->szAuthGrpFile);
133     else if (parent->szAuthGrpFile)
134         dc->szAuthGrpFile=ap_pstrdup(p,parent->szAuthGrpFile);
135     else
136         dc->szAuthGrpFile=NULL;
137
138     if (child->szApplicationId)
139         dc->szApplicationId=ap_pstrdup(p,child->szApplicationId);
140     else if (parent->szApplicationId)
141         dc->szApplicationId=ap_pstrdup(p,parent->szApplicationId);
142     else
143         dc->szApplicationId=NULL;
144
145     if (child->szRequireWith)
146         dc->szRequireWith=ap_pstrdup(p,child->szRequireWith);
147     else if (parent->szRequireWith)
148         dc->szRequireWith=ap_pstrdup(p,parent->szRequireWith);
149     else
150         dc->szRequireWith=NULL;
151
152     dc->bOff=((child->bOff==-1) ? parent->bOff : child->bOff);
153     dc->bBasicHijack=((child->bBasicHijack==-1) ? parent->bBasicHijack : child->bBasicHijack);
154     dc->bRequireSession=((child->bRequireSession==-1) ? parent->bRequireSession : child->bRequireSession);
155     dc->bExportAssertion=((child->bExportAssertion==-1) ? parent->bExportAssertion : child->bExportAssertion);
156     dc->bRequireAll=((child->bRequireAll==-1) ? parent->bRequireAll : child->bRequireAll);
157     return dc;
158 }
159
160 // generic global slot handlers
161 extern "C" const char* ap_set_global_string_slot(cmd_parms* parms, void*, const char* arg)
162 {
163     *((char**)(parms->info))=ap_pstrdup(parms->pool,arg);
164     return NULL;
165 }
166
167 extern "C" const char* shib_set_server_string_slot(cmd_parms* parms, void*, const char* arg)
168 {
169     char* base=(char*)ap_get_module_config(parms->server->module_config,&mod_shib);
170     int offset=(int)parms->info;
171     *((char**)(base + offset))=ap_pstrdup(parms->pool,arg);
172     return NULL;
173 }
174
175 extern "C" const char* shib_ap_set_file_slot(cmd_parms* parms,
176 #ifdef SHIB_APACHE_13
177                                              char* arg1, char* arg2
178 #else
179                                              void* arg1, const char* arg2
180 #endif
181                                              )
182 {
183   ap_set_file_slot(parms, arg1, arg2);
184   return DECLINE_CMD;
185 }
186
187 /********************************************************************************/
188 // Apache ShibTarget subclass(es) here.
189
190 class ShibTargetApache : public ShibTarget
191 {
192 public:
193   ShibTargetApache(request_rec* req) {
194     m_sc = (shib_server_config*)ap_get_module_config(req->server->module_config, &mod_shib);
195     m_dc = (shib_dir_config*)ap_get_module_config(req->per_dir_config, &mod_shib);
196
197     init(
198         m_sc->szScheme ? m_sc->szScheme : ap_http_method(req),
199             ap_get_server_name(req),
200         (int)ap_get_server_port(req),
201             req->unparsed_uri,
202         ap_table_get(req->headers_in, "Content-type"),
203             req->connection->remote_ip,
204         req->method
205         );
206
207     m_req = req;
208   }
209   ~ShibTargetApache() { }
210
211   virtual void log(ShibLogLevel level, const string &msg) {
212     ShibTarget::log(level,msg);
213 #ifdef SHIB_APACHE_13
214     ap_log_rerror(APLOG_MARK,
215         (level == LogLevelDebug ? APLOG_DEBUG :
216             (level == LogLevelInfo ? APLOG_INFO :
217             (level == LogLevelWarn ? APLOG_WARNING : APLOG_ERR)))|APLOG_NOERRNO, SH_AP_R(m_req), msg.c_str());
218 #else
219     if (level == LogLevelError)
220         ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(m_req), msg.c_str());
221 #endif
222   }
223   virtual string getCookies(void) const {
224     const char *c = ap_table_get(m_req->headers_in, "Cookie");
225     return string(c ? c : "");
226   }
227   virtual void setCookie(const string &name, const string &value) {
228     char* val = ap_psprintf(m_req->pool, "%s=%s", name.c_str(), value.c_str());
229     ap_table_addn(m_req->err_headers_out, "Set-Cookie", val);
230   }
231   virtual string getArgs(void) { return string(m_req->args ? m_req->args : ""); }
232   virtual string getPostData(void) {
233     // Read the posted data
234     if (ap_setup_client_block(m_req, REQUEST_CHUNKED_ERROR))
235         throw FatalProfileException("Apache function (setup_client_block) failed while reading profile submission.");
236     if (!ap_should_client_block(m_req))
237         throw FatalProfileException("Apache function (should_client_block) failed while reading profile submission.");
238     if (m_req->remaining > 1024*1024)
239         throw FatalProfileException("Blocked too-large a submission to profile endpoint.");
240     string cgistr;
241     char buff[HUGE_STRING_LEN];
242     ap_hard_timeout("[mod_shib] getPostData", m_req);
243     memset(buff, 0, sizeof(buff));
244     while (ap_get_client_block(m_req, buff, sizeof(buff)-1) > 0) {
245       ap_reset_timeout(m_req);
246       cgistr += buff;
247       memset(buff, 0, sizeof(buff));
248     }
249     ap_kill_timeout(m_req);
250
251     return cgistr;
252   }
253   virtual void clearHeader(const string &name) {
254     ap_table_unset(m_req->headers_in, name.c_str());
255   }
256   virtual void setHeader(const string &name, const string &value) {
257     ap_table_set(m_req->headers_in, name.c_str(), value.c_str());
258   }
259   virtual string getHeader(const string &name) {
260     const char *hdr = ap_table_get(m_req->headers_in, name.c_str());
261     return string(hdr ? hdr : "");
262   }
263   virtual void setRemoteUser(const string &user) {
264     SH_AP_USER(m_req) = ap_pstrdup(m_req->pool, user.c_str());
265   }
266   virtual string getRemoteUser(void) {
267     return string(SH_AP_USER(m_req) ? SH_AP_USER(m_req) : "");
268   }
269   virtual void* sendPage(
270     const string& msg,
271     int code=200,
272     const string& content_type="text/html",
273         const Iterator<header_t>& headers=EMPTY(header_t)
274     ) {
275     m_req->content_type = ap_psprintf(m_req->pool, content_type.c_str());
276     while (headers.hasNext()) {
277         const header_t& h=headers.next();
278         ap_table_set(m_req->headers_out, h.first.c_str(), h.second.c_str());
279     }
280     ap_send_http_header(m_req);
281     ap_rprintf(m_req, msg.c_str());
282     return (void*)((code==200) ? DONE : code);
283   }
284   virtual void* sendRedirect(const string& url) {
285     ap_table_set(m_req->headers_out, "Location", url.c_str());
286     return (void*)REDIRECT;
287   }
288   virtual void* returnDecline(void) { return (void*)DECLINED; }
289   virtual void* returnOK(void) { return (void*)OK; }
290
291   request_rec* m_req;
292   shib_dir_config* m_dc;
293   shib_server_config* m_sc;
294 };
295
296 /********************************************************************************/
297 // Apache handlers
298
299 extern "C" int shib_check_user(request_rec* r)
300 {
301   // Short-circuit entirely?
302   if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
303     return DECLINED;
304     
305   ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_check_user(%d): ENTER\n", (int)getpid());
306
307   ostringstream threadid;
308   threadid << "[" << getpid() << "] shib_check_user" << '\0';
309   saml::NDC ndc(threadid.str().c_str());
310
311 #ifndef _DEBUG
312   try {
313 #endif
314     ShibTargetApache sta(r);
315
316     // Check user authentication and export information, then set the handler bypass
317     pair<bool,void*> res = sta.doCheckAuthN(true);
318     apr_pool_userdata_setn((const void*)42,g_UserDataKey,NULL,r->pool);
319     if (res.first) return (int)res.second;
320
321     // user auth was okay -- export the assertions now
322     res = sta.doExportAssertions();
323     if (res.first) return (int)res.second;
324
325     // export happened successfully..  this user is ok.
326     return OK;
327
328 #ifndef _DEBUG
329   } catch (...) {
330     ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user threw an uncaught exception!");
331     return SERVER_ERROR;
332   }
333 #endif
334 }
335
336 extern "C" int shib_handler(request_rec* r)
337 {
338   // Short-circuit entirely?
339   if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
340     return DECLINED;
341
342   ostringstream threadid;
343   threadid << "[" << getpid() << "] shib_handler" << '\0';
344   saml::NDC ndc(threadid.str().c_str());
345
346 #ifndef SHIB_APACHE_13
347   // With 2.x, this handler always runs, though last.
348   // We check if shib_check_user ran, because it will detect a handler request
349   // and dispatch it directly.
350   void* data;
351   apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
352   if (data==(const void*)42) {
353     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler skipped since check_user ran");
354     return DECLINED;
355   }
356 #endif
357
358   ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler(%d): ENTER: %s", (int)getpid(), r->handler);
359
360 #ifndef _DEBUG
361   try {
362 #endif
363     ShibTargetApache sta(r);
364
365     pair<bool,void*> res = sta.doHandler();
366     if (res.first) return (int)res.second;
367
368     ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "doHandler() did not do anything.");
369     return SERVER_ERROR;
370
371 #ifndef _DEBUG
372   } catch (...) {
373     ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler threw an uncaught exception!");
374     return SERVER_ERROR;
375   }
376 #endif
377 }
378
379 /*
380  * shib_auth_checker() -- a simple resource manager to
381  * process the .htaccess settings
382  */
383 extern "C" int shib_auth_checker(request_rec* r)
384 {
385   // Short-circuit entirely?
386   if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
387     return DECLINED;
388
389   ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_auth_checker(%d): ENTER", (int)getpid());
390
391   ostringstream threadid;
392   threadid << "[" << getpid() << "] shib_auth_checker" << '\0';
393   saml::NDC ndc(threadid.str().c_str());
394
395 #ifndef _DEBUG
396   try {
397 #endif
398     ShibTargetApache sta(r);
399
400     pair<bool,void*> res = sta.doCheckAuthZ();
401     if (res.first) return (int)res.second;
402
403     // We're all okay.
404     return OK;
405
406 #ifndef _DEBUG
407   } catch (...) {
408     ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an uncaught exception!");
409     return SERVER_ERROR;
410   }
411 #endif
412 }
413
414 // Access control plugin that enforces htaccess rules
415 class htAccessControl : virtual public IAccessControl
416 {
417 public:
418     htAccessControl() {}
419     ~htAccessControl() {}
420     void lock() {}
421     void unlock() {}
422     bool authorized(
423         ShibTarget* st,
424         ISessionCacheEntry* entry
425     ) const;
426 };
427
428 IPlugIn* htAccessFactory(const DOMElement* e)
429 {
430     return new htAccessControl();
431 }
432
433 class ApacheRequestMapper : public virtual IRequestMapper, public virtual IPropertySet
434 {
435 public:
436     ApacheRequestMapper(const DOMElement* e);
437     ~ApacheRequestMapper() { delete m_mapper; delete m_htaccess; delete m_staKey; delete m_propsKey; }
438     void lock() { m_mapper->lock(); }
439     void unlock() { m_staKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
440     Settings getSettings(ShibTarget* st) const;
441     
442     pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
443     pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
444     pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
445     pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
446     pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
447     const IPropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
448     const DOMElement* getElement() const;
449
450 private:
451     IRequestMapper* m_mapper;
452     ThreadKey* m_staKey;
453     ThreadKey* m_propsKey;
454     IAccessControl* m_htaccess;
455 };
456
457 IPlugIn* ApacheRequestMapFactory(const DOMElement* e)
458 {
459     return new ApacheRequestMapper(e);
460 }
461
462 ApacheRequestMapper::ApacheRequestMapper(const DOMElement* e) : m_mapper(NULL), m_htaccess(NULL), m_staKey(NULL), m_propsKey(NULL)
463 {
464     IPlugIn* p=SAMLConfig::getConfig().getPlugMgr().newPlugin(shibtarget::XML::XMLRequestMapType,e);
465     m_mapper=dynamic_cast<IRequestMapper*>(p);
466     if (!m_mapper) {
467         delete p;
468         throw UnsupportedExtensionException("Embedded request mapper plugin was not of correct type.");
469     }
470     m_htaccess=new htAccessControl();
471     m_staKey=ThreadKey::create(NULL);
472     m_propsKey=ThreadKey::create(NULL);
473 }
474
475 IRequestMapper::Settings ApacheRequestMapper::getSettings(ShibTarget* st) const
476 {
477     Settings s=m_mapper->getSettings(st);
478     m_staKey->setData(dynamic_cast<ShibTargetApache*>(st));
479     m_propsKey->setData((void*)s.first);
480     return pair<const IPropertySet*,IAccessControl*>(this,s.second ? s.second : m_htaccess);
481 }
482
483 pair<bool,bool> ApacheRequestMapper::getBool(const char* name, const char* ns) const
484 {
485     ShibTargetApache* sta=reinterpret_cast<ShibTargetApache*>(m_staKey->getData());
486     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
487     if (sta && !ns) {
488         // Override Apache-settable boolean properties.
489         if (name && !strcmp(name,"requireSession") && sta->m_dc->bRequireSession==1)
490             return make_pair(true,true);
491         else if (name && !strcmp(name,"exportAssertion") && sta->m_dc->bExportAssertion==1)
492             return make_pair(true,true);
493     }
494     return s ? s->getBool(name,ns) : make_pair(false,false);
495 }
496
497 pair<bool,const char*> ApacheRequestMapper::getString(const char* name, const char* ns) const
498 {
499     ShibTargetApache* sta=reinterpret_cast<ShibTargetApache*>(m_staKey->getData());
500     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
501     if (sta && !ns) {
502         // Override Apache-settable string properties.
503         if (name && !strcmp(name,"authType")) {
504             const char *auth_type=ap_auth_type(sta->m_req);
505             if (auth_type) {
506                 // Check for Basic Hijack
507                 if (!strcasecmp(auth_type, "basic") && sta->m_dc->bBasicHijack == 1)
508                     auth_type = "shibboleth";
509                 return make_pair(true,auth_type);
510             }
511         }
512         else if (name && !strcmp(name,"applicationId") && sta->m_dc->szApplicationId)
513             return pair<bool,const char*>(true,sta->m_dc->szApplicationId);
514         else if (name && !strcmp(name,"requireSessionWith") && sta->m_dc->szRequireWith)
515             return pair<bool,const char*>(true,sta->m_dc->szRequireWith);
516     }
517     return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
518 }
519
520 pair<bool,const XMLCh*> ApacheRequestMapper::getXMLString(const char* name, const char* ns) const
521 {
522     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
523     return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
524 }
525
526 pair<bool,unsigned int> ApacheRequestMapper::getUnsignedInt(const char* name, const char* ns) const
527 {
528     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
529     return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
530 }
531
532 pair<bool,int> ApacheRequestMapper::getInt(const char* name, const char* ns) const
533 {
534     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
535     return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
536 }
537
538 const IPropertySet* ApacheRequestMapper::getPropertySet(const char* name, const char* ns) const
539 {
540     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
541     return s ? s->getPropertySet(name,ns) : NULL;
542 }
543
544 const DOMElement* ApacheRequestMapper::getElement() const
545 {
546     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
547     return s ? s->getElement() : NULL;
548 }
549
550 static SH_AP_TABLE* groups_for_user(request_rec* r, const char* user, char* grpfile)
551 {
552     SH_AP_CONFIGFILE* f;
553     SH_AP_TABLE* grps=ap_make_table(r->pool,15);
554     char l[MAX_STRING_LEN];
555     const char *group_name, *ll, *w;
556
557 #ifdef SHIB_APACHE_13
558     if (!(f=ap_pcfg_openfile(r->pool,grpfile))) {
559 #else
560     if (ap_pcfg_openfile(&f,r->pool,grpfile) != APR_SUCCESS) {
561 #endif
562         ap_log_rerror(APLOG_MARK,APLOG_DEBUG,SH_AP_R(r),"groups_for_user() could not open group file: %s\n",grpfile);
563         return NULL;
564     }
565
566     SH_AP_POOL* sp;
567 #ifdef SHIB_APACHE_13
568     sp=ap_make_sub_pool(r->pool);
569 #else
570     if (apr_pool_create(&sp,r->pool) != APR_SUCCESS) {
571         ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,
572             "groups_for_user() could not create a subpool");
573         return NULL;
574     }
575 #endif
576
577     while (!(ap_cfg_getline(l,MAX_STRING_LEN,f))) {
578         if ((*l=='#') || (!*l))
579             continue;
580         ll = l;
581         ap_clear_pool(sp);
582
583         group_name=ap_getword(sp,&ll,':');
584
585         while (*ll) {
586             w=ap_getword_conf(sp,&ll);
587             if (!strcmp(w,user)) {
588                 ap_table_setn(grps,ap_pstrdup(r->pool,group_name),"in");
589                 break;
590             }
591         }
592     }
593     ap_cfg_closefile(f);
594     ap_destroy_pool(sp);
595     return grps;
596 }
597
598 bool htAccessControl::authorized(
599     ShibTarget* st,
600     ISessionCacheEntry* entry
601 ) const
602 {
603     // Make sure the object is our type.
604     ShibTargetApache* sta=dynamic_cast<ShibTargetApache*>(st);
605     if (!sta)
606         throw ConfigurationException("Request wrapper object was not of correct type.");
607
608     // mod_auth clone
609
610     int m=sta->m_req->method_number;
611     bool method_restricted=false;
612     const char *t, *w;
613     
614     const array_header* reqs_arr=ap_requires(sta->m_req);
615     if (!reqs_arr)
616         return true;
617
618     require_line* reqs=(require_line*)reqs_arr->elts;
619     
620     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(sta->m_req),"REQUIRE nelts: %d", reqs_arr->nelts);
621     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(sta->m_req),"REQUIRE all: %d", sta->m_dc->bRequireAll);
622
623     vector<bool> auth_OK(reqs_arr->nelts,false);
624
625 #define SHIB_AP_CHECK_IS_OK {           \
626      if (sta->m_dc->bRequireAll < 1)    \
627          return true;                   \
628      auth_OK[x] = true;                 \
629      continue;                          \
630 }
631
632     for (int x=0; x<reqs_arr->nelts; x++) {
633         auth_OK[x] = false;
634         if (!(reqs[x].method_mask & (1 << m)))
635             continue;
636         method_restricted=true;
637         string remote_user = st->getRemoteUser();
638
639         t = reqs[x].requirement;
640         w = ap_getword_white(sta->m_req->pool, &t);
641
642         if (!strcasecmp(w,"shibboleth")) {
643             // This is a dummy rule needed because Apache conflates authn and authz.
644             // Without some require rule, AuthType is ignored and no check_user hooks run.
645             SHIB_AP_CHECK_IS_OK;
646         }
647         else if (!strcmp(w,"valid-user") && entry) {
648             st->log(ShibTarget::LogLevelDebug,"htAccessControl plugin accepting valid-user based on active session");
649             SHIB_AP_CHECK_IS_OK;
650         }
651         else if (!strcmp(w,"user") && !remote_user.empty()) {
652             bool regexp=false;
653             while (*t) {
654                 w=ap_getword_conf(sta->m_req->pool,&t);
655                 if (*w=='~') {
656                     regexp=true;
657                     continue;
658                 }
659                 
660                 if (regexp) {
661                     try {
662                         // To do regex matching, we have to convert from UTF-8.
663                         auto_ptr<XMLCh> trans(fromUTF8(w));
664                         RegularExpression re(trans.get());
665                         auto_ptr<XMLCh> trans2(fromUTF8(remote_user.c_str()));
666                         if (re.matches(trans2.get())) {
667                             st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin accepting user (") + w + ")");
668                             SHIB_AP_CHECK_IS_OK;
669                         }
670                     }
671                     catch (XMLException& ex) {
672                         auto_ptr_char tmp(ex.getMessage());
673                         st->log(ShibTarget::LogLevelError,
674                             string("htAccessControl plugin caught exception while parsing regular expression (") + w + "): " + tmp.get());
675                     }
676                 }
677                 else if (remote_user==w) {
678                     st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin accepting user (") + w + ")");
679                     SHIB_AP_CHECK_IS_OK;
680                 }
681             }
682         }
683         else if (!strcmp(w,"group")) {
684             SH_AP_TABLE* grpstatus=NULL;
685             if (sta->m_dc->szAuthGrpFile && !remote_user.empty()) {
686                 st->log(ShibTarget::LogLevelDebug,string("htAccessControl plugin using groups file: ") + sta->m_dc->szAuthGrpFile);
687                 grpstatus=groups_for_user(sta->m_req,remote_user.c_str(),sta->m_dc->szAuthGrpFile);
688             }
689             if (!grpstatus)
690                 return false;
691     
692             while (*t) {
693                 w=ap_getword_conf(sta->m_req->pool,&t);
694                 if (ap_table_get(grpstatus,w)) {
695                     st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin accepting group (") + w + ")");
696                     SHIB_AP_CHECK_IS_OK;
697                 }
698             }
699         }
700         else {
701             Iterator<IAAP*> provs=st->getApplication()->getAAPProviders();
702             AAP wrapper(provs,w);
703             if (wrapper.fail()) {
704                 st->log(ShibTarget::LogLevelWarn, string("htAccessControl plugin didn't recognize require rule: ") + w);
705                 continue;
706             }
707
708             bool regexp=false;
709             const char* vals=ap_table_get(sta->m_req->headers_in,wrapper->getHeader());
710             while (*t && vals) {
711                 w=ap_getword_conf(sta->m_req->pool,&t);
712                 if (*w=='~') {
713                     regexp=true;
714                     continue;
715                 }
716
717                 try {
718                     auto_ptr<RegularExpression> re;
719                     if (regexp) {
720                         delete re.release();
721                         auto_ptr<XMLCh> trans(fromUTF8(w));
722                         auto_ptr<RegularExpression> temp(new RegularExpression(trans.get()));
723                         re=temp;
724                     }
725                     
726                     string vals_str(vals);
727                     int j = 0;
728                     for (int i = 0;  i < vals_str.length();  i++) {
729                         if (vals_str.at(i) == ';') {
730                             if (i == 0) {
731                                 st->log(ShibTarget::LogLevelError, string("htAccessControl plugin found invalid header encoding (") +
732                                     vals + "): starts with a semicolon");
733                                 throw SAMLException("Invalid information supplied to authorization plugin.");
734                             }
735
736                             if (vals_str.at(i-1) == '\\') {
737                                 vals_str.erase(i-1, 1);
738                                 i--;
739                                 continue;
740                             }
741
742                             string val = vals_str.substr(j, i-j);
743                             j = i+1;
744                             if (regexp) {
745                                 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
746                                 if (re->matches(trans.get())) {
747                                     st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
748                                        ", got " + val + ": authorization granted");
749                                     SHIB_AP_CHECK_IS_OK;
750                                 }
751                             }
752                             else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
753                                 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
754                                     ", got " + val + ": authorization granted.");
755                                 SHIB_AP_CHECK_IS_OK;
756                             }
757                             else {
758                                 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
759                                     ", got " + val + ": authoritzation not granted.");
760                             }
761                         }
762                     }
763     
764                     string val = vals_str.substr(j, vals_str.length()-j);
765                     if (regexp) {
766                         auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
767                         if (re->matches(trans.get())) {
768                             st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
769                                 ", got " + val + ": authorization granted.");
770                             SHIB_AP_CHECK_IS_OK;
771                         }
772                     }
773                     else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
774                         st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
775                             ", got " + val + ": authorization granted");
776                         SHIB_AP_CHECK_IS_OK;
777                     }
778                     else {
779                             st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
780                                 ", got " + val + ": authorization not granted");
781                     }
782                 }
783                 catch (XMLException& ex) {
784                     auto_ptr_char tmp(ex.getMessage());
785                     st->log(ShibTarget::LogLevelError, string("htAccessControl plugin caught exception while parsing regular expression (")
786                         + w + "): " + tmp.get());
787                 }
788             }
789         }
790     }
791
792     // check if all require directives are true
793     bool auth_all_OK = true;
794     for (int i= 0; i<reqs_arr->nelts; i++) {
795         auth_all_OK &= auth_OK[i];
796     }
797     if (auth_all_OK || !method_restricted)
798         return true;
799
800     return false;
801 }
802
803 #ifndef SHIB_APACHE_13
804 /*
805  * shib_exit()
806  *  Empty cleanup hook, Apache 2.x doesn't check NULL very well...
807  */
808 extern "C" apr_status_t shib_exit(void* data)
809 {
810     if (g_Config) {
811         g_Config->shutdown();
812         g_Config = NULL;
813     }
814     ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,0,NULL,"shib_exit() done\n");
815     return OK;
816 }
817 #endif
818
819
820 /*
821  * shib_child_exit()
822  *  Cleanup the (per-process) pool info.
823  */
824 #ifdef SHIB_APACHE_13
825 extern "C" void shib_child_exit(server_rec* s, SH_AP_POOL* p)
826 {
827 #else
828 extern "C" apr_status_t shib_child_exit(void* data)
829 {
830   server_rec* s = NULL;
831 #endif
832
833     ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit(%d) dealing with g_Config..", (int)getpid());
834     g_Config->shutdown();
835     g_Config = NULL;
836     ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit() done\n");
837
838 #ifndef SHIB_APACHE_13
839     return OK;
840 #endif
841 }
842
843 /* 
844  * shire_child_init()
845  *  Things to do when the child process is initialized.
846  *  (or after the configs are read in apache-2)
847  */
848 #ifdef SHIB_APACHE_13
849 extern "C" void shib_child_init(server_rec* s, SH_AP_POOL* p)
850 #else
851 extern "C" void shib_child_init(apr_pool_t* p, server_rec* s)
852 #endif
853 {
854     // Initialize runtime components.
855
856     ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init(%d) starting", (int)getpid());
857
858     if (g_Config) {
859         ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() already initialized!");
860         exit(1);
861     }
862
863     try {
864         g_Config=&ShibTargetConfig::getConfig();
865         g_Config->setFeatures(
866             ShibTargetConfig::Listener |
867             ShibTargetConfig::Metadata |
868             ShibTargetConfig::AAP |
869             ShibTargetConfig::RequestMapper |
870             ShibTargetConfig::LocalExtensions |
871             ShibTargetConfig::Logging
872             );
873         if (!g_Config->init(g_szSchemaDir)) {
874             ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize libraries");
875             exit(1);
876         }
877         SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::htAccessControlType,&htAccessFactory);
878         SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::NativeRequestMapType,&ApacheRequestMapFactory);
879         // We hijack the legacy type so that 1.2 config files will load this plugin
880         SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::LegacyRequestMapType,&ApacheRequestMapFactory);
881         
882         if (!g_Config->load(g_szSHIBConfig)) {
883             ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to load configuration");
884             exit(1);
885         }
886     }
887     catch (...) {
888         ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize system");
889         exit(1);
890     }
891
892     // Set the cleanup handler
893     apr_pool_cleanup_register(p, NULL, &shib_exit, &shib_child_exit);
894
895     ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() done");
896 }
897
898 typedef const char* (*config_fn_t)(void);
899
900 #ifdef SHIB_APACHE_13
901
902 // SHIB Module commands
903
904 static command_rec shire_cmds[] = {
905   {"SHIREConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
906    RSRC_CONF, TAKE1, "Path to shibboleth.xml config file."},
907   {"ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
908    RSRC_CONF, TAKE1, "Path to shibboleth.xml config file."},
909   {"ShibSchemaDir", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
910    RSRC_CONF, TAKE1, "Path to Shibboleth XML schema directory."},
911
912   {"ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
913    (void *) XtOffsetOf (shib_server_config, szScheme),
914    RSRC_CONF, TAKE1, "URL scheme to force into generated URLs for a vhost."},
915    
916   {"ShibDisable", (config_fn_t)ap_set_flag_slot,
917    (void *) XtOffsetOf (shib_dir_config, bOff),
918    OR_AUTHCFG, FLAG, "Disable all Shib module activity here to save processing effort"},
919   {"ShibApplicationId", (config_fn_t)ap_set_string_slot,
920    (void *) XtOffsetOf (shib_dir_config, szApplicationId),
921    OR_AUTHCFG, FLAG, "Set Shibboleth applicationId property for content"},
922   {"ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
923    (void *) XtOffsetOf (shib_dir_config, bBasicHijack),
924    OR_AUTHCFG, FLAG, "Respond to AuthType Basic and convert to shib?"},
925   {"ShibRequireSession", (config_fn_t)ap_set_flag_slot,
926    (void *) XtOffsetOf (shib_dir_config, bRequireSession),
927    OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist."},
928   {"ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
929    (void *) XtOffsetOf (shib_dir_config, szRequireWith),
930    OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist using a specific SessionInitiator"},
931   {"ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
932    (void *) XtOffsetOf (shib_dir_config, bExportAssertion),
933    OR_AUTHCFG, FLAG, "Export SAML attribute assertion(s) to Shib-Attributes header?"},
934   {"AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
935    (void *) XtOffsetOf (shib_dir_config, szAuthGrpFile),
936    OR_AUTHCFG, TAKE1, "text file containing group names and member user IDs"},
937   {"ShibRequireAll", (config_fn_t)ap_set_flag_slot,
938    (void *) XtOffsetOf (shib_dir_config, bRequireAll),
939    OR_AUTHCFG, FLAG, "All require directives must match!"},
940
941   {NULL}
942 };
943
944 extern "C"{
945 handler_rec shib_handlers[] = {
946   { "shib-handler", shib_handler },
947   { NULL }
948 };
949
950 module MODULE_VAR_EXPORT mod_shib = {
951     STANDARD_MODULE_STUFF,
952     NULL,                        /* initializer */
953     create_shib_dir_config,     /* dir config creater */
954     merge_shib_dir_config,      /* dir merger --- default is to override */
955     create_shib_server_config, /* server config */
956     merge_shib_server_config,   /* merge server config */
957     shire_cmds,                 /* command table */
958     shib_handlers,              /* handlers */
959     NULL,                       /* filename translation */
960     shib_check_user,            /* check_user_id */
961     shib_auth_checker,          /* check auth */
962     NULL,                       /* check access */
963     NULL,                       /* type_checker */
964     NULL,                       /* fixups */
965     NULL,                       /* logger */
966     NULL,                       /* header parser */
967     shib_child_init,            /* child_init */
968     shib_child_exit,            /* child_exit */
969     NULL                        /* post read-request */
970 };
971
972 #elif defined(SHIB_APACHE_20)
973
974 extern "C" void shib_register_hooks (apr_pool_t *p)
975 {
976   ap_hook_child_init(shib_child_init, NULL, NULL, APR_HOOK_MIDDLE);
977   ap_hook_check_user_id(shib_check_user, NULL, NULL, APR_HOOK_MIDDLE);
978   ap_hook_auth_checker(shib_auth_checker, NULL, NULL, APR_HOOK_FIRST);
979   ap_hook_handler(shib_handler, NULL, NULL, APR_HOOK_LAST);
980 }
981
982 // SHIB Module commands
983
984 extern "C" {
985 static command_rec shib_cmds[] = {
986   AP_INIT_TAKE1("ShibConfig",
987                 (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
988                 RSRC_CONF, "Path to shibboleth.xml config file."),
989   AP_INIT_TAKE1("ShibSchemaDir",
990      (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
991       RSRC_CONF, "Path to Shibboleth XML schema directory."),
992
993   AP_INIT_TAKE1("ShibURLScheme",
994      (config_fn_t)shib_set_server_string_slot,
995      (void *) offsetof (shib_server_config, szScheme),
996       RSRC_CONF, "URL scheme to force into generated URLs for a vhost."),
997
998   AP_INIT_FLAG("ShibDisable", (config_fn_t)ap_set_flag_slot,
999          (void *) offsetof (shib_dir_config, bOff),
1000         OR_AUTHCFG, "Disable all Shib module activity here to save processing effort"),
1001   AP_INIT_TAKE1("ShibApplicationId", (config_fn_t)ap_set_string_slot,
1002          (void *) offsetof (shib_dir_config, szApplicationId),
1003         OR_AUTHCFG, "Set Shibboleth applicationId property for content"),
1004   AP_INIT_FLAG("ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1005                (void *) offsetof (shib_dir_config, bBasicHijack),
1006                OR_AUTHCFG, "Respond to AuthType Basic and convert to shib?"),
1007   AP_INIT_FLAG("ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1008          (void *) offsetof (shib_dir_config, bRequireSession),
1009         OR_AUTHCFG, "Initiates a new session if one does not exist."),
1010   AP_INIT_TAKE1("ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
1011          (void *) offsetof (shib_dir_config, szRequireWith),
1012         OR_AUTHCFG, "Initiates a new session if one does not exist using a specific SessionInitiator"),
1013   AP_INIT_FLAG("ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1014          (void *) offsetof (shib_dir_config, bExportAssertion),
1015         OR_AUTHCFG, "Export SAML attribute assertion(s) to Shib-Attributes header?"),
1016   AP_INIT_TAKE1("AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
1017                 (void *) offsetof (shib_dir_config, szAuthGrpFile),
1018                 OR_AUTHCFG, "Text file containing group names and member user IDs"),
1019   AP_INIT_FLAG("ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1020                (void *) offsetof (shib_dir_config, bRequireAll),
1021                OR_AUTHCFG, "All require directives must match!"),
1022
1023   {NULL}
1024 };
1025
1026 module AP_MODULE_DECLARE_DATA mod_shib = {
1027     STANDARD20_MODULE_STUFF,
1028     create_shib_dir_config,     /* create dir config */
1029     merge_shib_dir_config,      /* merge dir config --- default is to override */
1030     create_shib_server_config,  /* create server config */
1031     merge_shib_server_config,   /* merge server config */
1032     shib_cmds,                  /* command table */
1033     shib_register_hooks         /* register hooks */
1034 };
1035
1036 #else
1037 #error "undefined APACHE version"
1038 #endif
1039
1040 }