Streamline request map plugin, unify authType/requestSession handling.
[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, the 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         const char* providerId,
425         const saml::SAMLAuthenticationStatement* authn,
426         const saml::SAMLResponse* attrs
427     ) const;
428 };
429
430 IPlugIn* htAccessFactory(const DOMElement* e)
431 {
432     return new htAccessControl();
433 }
434
435 class ApacheRequestMapper : public virtual IRequestMapper, public virtual IPropertySet
436 {
437 public:
438     ApacheRequestMapper(const DOMElement* e);
439     ~ApacheRequestMapper() { delete m_mapper; delete m_htaccess; delete m_staKey; delete m_propsKey; }
440     void lock() { m_mapper->lock(); }
441     void unlock() { m_staKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
442     Settings getSettings(ShibTarget* st) const;
443     
444     pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
445     pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
446     pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
447     pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
448     pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
449     const IPropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
450     const DOMElement* getElement() const;
451
452 private:
453     IRequestMapper* m_mapper;
454     ThreadKey* m_staKey;
455     ThreadKey* m_propsKey;
456     IAccessControl* m_htaccess;
457 };
458
459 IPlugIn* ApacheRequestMapFactory(const DOMElement* e)
460 {
461     return new ApacheRequestMapper(e);
462 }
463
464 ApacheRequestMapper::ApacheRequestMapper(const DOMElement* e) : m_mapper(NULL), m_htaccess(NULL), m_staKey(NULL), m_propsKey(NULL)
465 {
466     IPlugIn* p=SAMLConfig::getConfig().getPlugMgr().newPlugin(shibtarget::XML::XMLRequestMapType,e);
467     m_mapper=dynamic_cast<IRequestMapper*>(p);
468     if (!m_mapper) {
469         delete p;
470         throw UnsupportedExtensionException("Embedded request mapper plugin was not of correct type.");
471     }
472     m_htaccess=new htAccessControl();
473     m_staKey=ThreadKey::create(NULL);
474     m_propsKey=ThreadKey::create(NULL);
475 }
476
477 IRequestMapper::Settings ApacheRequestMapper::getSettings(ShibTarget* st) const
478 {
479     Settings s=m_mapper->getSettings(st);
480     m_staKey->setData(dynamic_cast<ShibTargetApache*>(st));
481     m_propsKey->setData((void*)s.first);
482     return pair<const IPropertySet*,IAccessControl*>(this,s.second ? s.second : m_htaccess);
483 }
484
485 pair<bool,bool> ApacheRequestMapper::getBool(const char* name, const char* ns) const
486 {
487     ShibTargetApache* sta=reinterpret_cast<ShibTargetApache*>(m_staKey->getData());
488     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
489     if (sta && !ns) {
490         // Override Apache-settable boolean properties.
491         if (name && !strcmp(name,"requireSession") && sta->m_dc->bRequireSession==1)
492             return make_pair(true,true);
493         else if (name && !strcmp(name,"exportAssertion") && sta->m_dc->bExportAssertion==1)
494             return make_pair(true,true);
495     }
496     return s ? s->getBool(name,ns) : make_pair(false,false);
497 }
498
499 pair<bool,const char*> ApacheRequestMapper::getString(const char* name, const char* ns) const
500 {
501     ShibTargetApache* sta=reinterpret_cast<ShibTargetApache*>(m_staKey->getData());
502     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
503     if (sta && !ns) {
504         // Override Apache-settable string properties.
505         if (name && !strcmp(name,"authType")) {
506             const char *auth_type=ap_auth_type(sta->m_req);
507             if (auth_type) {
508                 // Check for Basic Hijack
509                 if (!strcasecmp(auth_type, "basic") && sta->m_dc->bBasicHijack == 1)
510                     auth_type = "shibboleth";
511                 return make_pair(true,auth_type);
512             }
513         }
514         else if (name && !strcmp(name,"applicationId") && sta->m_dc->szApplicationId)
515             return make_pair(true,sta->m_dc->szApplicationId);
516         else if (name && !strcmp(name,"requireSessionWith") && sta->m_dc->szRequireWith)
517             return make_pair(true,sta->m_dc->szRequireWith);
518     }
519     return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
520 }
521
522 pair<bool,const XMLCh*> ApacheRequestMapper::getXMLString(const char* name, const char* ns) const
523 {
524     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
525     return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
526 }
527
528 pair<bool,unsigned int> ApacheRequestMapper::getUnsignedInt(const char* name, const char* ns) const
529 {
530     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
531     return s ? s->getUnsignedInt(name,ns) : make_pair(false,0);
532 }
533
534 pair<bool,int> ApacheRequestMapper::getInt(const char* name, const char* ns) const
535 {
536     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
537     return s ? s->getInt(name,ns) : make_pair(false,0);
538 }
539
540 const IPropertySet* ApacheRequestMapper::getPropertySet(const char* name, const char* ns) const
541 {
542     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
543     return s ? s->getPropertySet(name,ns) : NULL;
544 }
545
546 const DOMElement* ApacheRequestMapper::getElement() const
547 {
548     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
549     return s ? s->getElement() : NULL;
550 }
551
552 static SH_AP_TABLE* groups_for_user(request_rec* r, const char* user, char* grpfile)
553 {
554     SH_AP_CONFIGFILE* f;
555     SH_AP_TABLE* grps=ap_make_table(r->pool,15);
556     char l[MAX_STRING_LEN];
557     const char *group_name, *ll, *w;
558
559 #ifdef SHIB_APACHE_13
560     if (!(f=ap_pcfg_openfile(r->pool,grpfile))) {
561 #else
562     if (ap_pcfg_openfile(&f,r->pool,grpfile) != APR_SUCCESS) {
563 #endif
564         ap_log_rerror(APLOG_MARK,APLOG_DEBUG,SH_AP_R(r),"groups_for_user() could not open group file: %s\n",grpfile);
565         return NULL;
566     }
567
568     SH_AP_POOL* sp;
569 #ifdef SHIB_APACHE_13
570     sp=ap_make_sub_pool(r->pool);
571 #else
572     if (apr_pool_create(&sp,r->pool) != APR_SUCCESS) {
573         ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,
574             "groups_for_user() could not create a subpool");
575         return NULL;
576     }
577 #endif
578
579     while (!(ap_cfg_getline(l,MAX_STRING_LEN,f))) {
580         if ((*l=='#') || (!*l))
581             continue;
582         ll = l;
583         ap_clear_pool(sp);
584
585         group_name=ap_getword(sp,&ll,':');
586
587         while (*ll) {
588             w=ap_getword_conf(sp,&ll);
589             if (!strcmp(w,user)) {
590                 ap_table_setn(grps,ap_pstrdup(r->pool,group_name),"in");
591                 break;
592             }
593         }
594     }
595     ap_cfg_closefile(f);
596     ap_destroy_pool(sp);
597     return grps;
598 }
599
600 bool htAccessControl::authorized(
601     ShibTarget* st,
602     const char* providerId,
603     const saml::SAMLAuthenticationStatement* authn,
604     const saml::SAMLResponse* attrs
605 ) const
606 {
607     // Make sure the object is our type.
608     ShibTargetApache* sta=dynamic_cast<ShibTargetApache*>(st);
609     if (!sta)
610         throw ConfigurationException("Request wrapper object was not of correct type.");
611
612     // mod_auth clone
613
614     int m=sta->m_req->method_number;
615     bool method_restricted=false;
616     const char *t, *w;
617     
618     const array_header* reqs_arr=ap_requires(sta->m_req);
619     if (!reqs_arr)
620         return true;
621
622     require_line* reqs=(require_line*)reqs_arr->elts;
623     
624     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(sta->m_req),"REQUIRE nelts: %d", reqs_arr->nelts);
625     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(sta->m_req),"REQUIRE all: %d", sta->m_dc->bRequireAll);
626
627     vector<bool> auth_OK(reqs_arr->nelts,false);
628
629 #define SHIB_AP_CHECK_IS_OK {           \
630      if (sta->m_dc->bRequireAll < 1)    \
631          return true;                   \
632      auth_OK[x] = true;                 \
633      continue;                          \
634 }
635
636     for (int x=0; x<reqs_arr->nelts; x++) {
637         auth_OK[x] = false;
638         if (!(reqs[x].method_mask & (1 << m)))
639             continue;
640         method_restricted=true;
641         string remote_user = st->getRemoteUser();
642
643         t = reqs[x].requirement;
644         w = ap_getword_white(sta->m_req->pool, &t);
645
646         if (!strcasecmp(w,"Shibboleth")) {
647             // This is a dummy rule needed because Apache conflates authn and authz.
648             // Without some require rule, AuthType is ignored and no check_user hooks run.
649             SHIB_AP_CHECK_IS_OK;
650         }
651         else if (!strcmp(w,"valid-user")) {
652             st->log(ShibTarget::LogLevelDebug,"htAccessControl plugin accepting valid-user");
653             SHIB_AP_CHECK_IS_OK;
654         }
655         else if (!strcmp(w,"user") && !remote_user.empty()) {
656             bool regexp=false;
657             while (*t) {
658                 w=ap_getword_conf(sta->m_req->pool,&t);
659                 if (*w=='~') {
660                     regexp=true;
661                     continue;
662                 }
663                 
664                 if (regexp) {
665                     try {
666                         // To do regex matching, we have to convert from UTF-8.
667                         auto_ptr<XMLCh> trans(fromUTF8(w));
668                         RegularExpression re(trans.get());
669                         auto_ptr<XMLCh> trans2(fromUTF8(remote_user.c_str()));
670                         if (re.matches(trans2.get())) {
671                             st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin accepting user (") + w + ")");
672                             SHIB_AP_CHECK_IS_OK;
673                         }
674                     }
675                     catch (XMLException& ex) {
676                         auto_ptr_char tmp(ex.getMessage());
677                         st->log(ShibTarget::LogLevelError,
678                             string("htAccessControl plugin caught exception while parsing regular expression (") + w + "): " + tmp.get());
679                     }
680                 }
681                 else if (remote_user==w) {
682                     st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin accepting user (") + w + ")");
683                     SHIB_AP_CHECK_IS_OK;
684                 }
685             }
686         }
687         else if (!strcmp(w,"group")) {
688             SH_AP_TABLE* grpstatus=NULL;
689             if (sta->m_dc->szAuthGrpFile && !remote_user.empty()) {
690                 st->log(ShibTarget::LogLevelDebug,string("htAccessControl plugin using groups file: ") + sta->m_dc->szAuthGrpFile);
691                 grpstatus=groups_for_user(sta->m_req,remote_user.c_str(),sta->m_dc->szAuthGrpFile);
692             }
693             if (!grpstatus)
694                 return false;
695     
696             while (*t) {
697                 w=ap_getword_conf(sta->m_req->pool,&t);
698                 if (ap_table_get(grpstatus,w)) {
699                     st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin accepting group (") + w + ")");
700                     SHIB_AP_CHECK_IS_OK;
701                 }
702             }
703         }
704         else {
705             Iterator<IAAP*> provs=st->getApplication()->getAAPProviders();
706             AAP wrapper(provs,w);
707             if (wrapper.fail()) {
708                 st->log(ShibTarget::LogLevelWarn, string("htAccessControl plugin didn't recognize require rule: ") + w);
709                 continue;
710             }
711
712             bool regexp=false;
713             const char* vals=ap_table_get(sta->m_req->headers_in,wrapper->getHeader());
714             while (*t && vals) {
715                 w=ap_getword_conf(sta->m_req->pool,&t);
716                 if (*w=='~') {
717                     regexp=true;
718                     continue;
719                 }
720
721                 try {
722                     auto_ptr<RegularExpression> re;
723                     if (regexp) {
724                         delete re.release();
725                         auto_ptr<XMLCh> trans(fromUTF8(w));
726                         auto_ptr<RegularExpression> temp(new RegularExpression(trans.get()));
727                         re=temp;
728                     }
729                     
730                     string vals_str(vals);
731                     int j = 0;
732                     for (int i = 0;  i < vals_str.length();  i++) {
733                         if (vals_str.at(i) == ';') {
734                             if (i == 0) {
735                                 st->log(ShibTarget::LogLevelError, string("htAccessControl plugin found invalid header encoding (") +
736                                     vals + "): starts with a semicolon");
737                                 throw SAMLException("Invalid information supplied to authorization plugin.");
738                             }
739
740                             if (vals_str.at(i-1) == '\\') {
741                                 vals_str.erase(i-1, 1);
742                                 i--;
743                                 continue;
744                             }
745
746                             string val = vals_str.substr(j, i-j);
747                             j = i+1;
748                             if (regexp) {
749                                 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
750                                 if (re->matches(trans.get())) {
751                                     st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
752                                        ", got " + val + ": authorization granted");
753                                     SHIB_AP_CHECK_IS_OK;
754                                 }
755                             }
756                             else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
757                                 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
758                                     ", got " + val + ": authorization granted.");
759                                 SHIB_AP_CHECK_IS_OK;
760                             }
761                             else {
762                                 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
763                                     ", got " + val + ": authoritzation not granted.");
764                             }
765                         }
766                     }
767     
768                     string val = vals_str.substr(j, vals_str.length()-j);
769                     if (regexp) {
770                         auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
771                         if (re->matches(trans.get())) {
772                             st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
773                                 ", got " + val + ": authorization granted.");
774                             SHIB_AP_CHECK_IS_OK;
775                         }
776                     }
777                     else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
778                         st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
779                             ", got " + val + ": authorization granted");
780                         SHIB_AP_CHECK_IS_OK;
781                     }
782                     else {
783                             st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
784                                 ", got " + val + ": authorization not granted");
785                     }
786                 }
787                 catch (XMLException& ex) {
788                     auto_ptr_char tmp(ex.getMessage());
789                     st->log(ShibTarget::LogLevelError, string("htAccessControl plugin caught exception while parsing regular expression (")
790                         + w + "): " + tmp.get());
791                 }
792             }
793         }
794     }
795
796     // check if all require directives are true
797     bool auth_all_OK = true;
798     for (int i= 0; i<reqs_arr->nelts; i++) {
799         auth_all_OK &= auth_OK[i];
800     }
801     if (auth_all_OK || !method_restricted)
802         return true;
803
804     return false;
805 }
806
807 #ifndef SHIB_APACHE_13
808 /*
809  * shib_exit()
810  *  Empty cleanup hook, Apache 2.x doesn't check NULL very well...
811  */
812 extern "C" apr_status_t shib_exit(void* data)
813 {
814     if (g_Config) {
815         g_Config->shutdown();
816         g_Config = NULL;
817     }
818     ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,0,NULL,"shib_exit() done\n");
819     return OK;
820 }
821 #endif
822
823
824 /*
825  * shib_child_exit()
826  *  Cleanup the (per-process) pool info.
827  */
828 #ifdef SHIB_APACHE_13
829 extern "C" void shib_child_exit(server_rec* s, SH_AP_POOL* p)
830 {
831 #else
832 extern "C" apr_status_t shib_child_exit(void* data)
833 {
834   server_rec* s = NULL;
835 #endif
836
837     ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit(%d) dealing with g_Config..", (int)getpid());
838     g_Config->shutdown();
839     g_Config = NULL;
840     ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit() done\n");
841
842 #ifndef SHIB_APACHE_13
843     return OK;
844 #endif
845 }
846
847 /* 
848  * shire_child_init()
849  *  Things to do when the child process is initialized.
850  *  (or after the configs are read in apache-2)
851  */
852 #ifdef SHIB_APACHE_13
853 extern "C" void shib_child_init(server_rec* s, SH_AP_POOL* p)
854 #else
855 extern "C" void shib_child_init(apr_pool_t* p, server_rec* s)
856 #endif
857 {
858     // Initialize runtime components.
859
860     ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init(%d) starting", (int)getpid());
861
862     if (g_Config) {
863         ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() already initialized!");
864         exit(1);
865     }
866
867     try {
868         g_Config=&ShibTargetConfig::getConfig();
869         g_Config->setFeatures(
870             ShibTargetConfig::Listener |
871             ShibTargetConfig::Metadata |
872             ShibTargetConfig::AAP |
873             ShibTargetConfig::RequestMapper |
874             ShibTargetConfig::LocalExtensions |
875             ShibTargetConfig::Logging
876             );
877         if (!g_Config->init(g_szSchemaDir)) {
878             ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize libraries");
879             exit(1);
880         }
881         SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::htAccessControlType,&htAccessFactory);
882         SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::ApacheRequestMapType,&ApacheRequestMapFactory);
883         
884         // We hijack the legacy type so that 1.2 config files will load this plugin instead of the basic plugin.
885         SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::LegacyRequestMapType,&ApacheRequestMapFactory);
886         
887         if (!g_Config->load(g_szSHIBConfig)) {
888             ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to load configuration");
889             exit(1);
890         }
891     }
892     catch (...) {
893         ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize system");
894         exit(1);
895     }
896
897     // Set the cleanup handler
898     apr_pool_cleanup_register(p, NULL, &shib_exit, &shib_child_exit);
899
900     ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() done");
901 }
902
903 typedef const char* (*config_fn_t)(void);
904
905 #ifdef SHIB_APACHE_13
906
907 // SHIB Module commands
908
909 static command_rec shire_cmds[] = {
910   {"SHIREConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
911    RSRC_CONF, TAKE1, "Path to shibboleth.xml config file."},
912   {"ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
913    RSRC_CONF, TAKE1, "Path to shibboleth.xml config file."},
914   {"ShibSchemaDir", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
915    RSRC_CONF, TAKE1, "Path to Shibboleth XML schema directory."},
916
917   {"ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
918    (void *) XtOffsetOf (shib_server_config, szScheme),
919    RSRC_CONF, TAKE1, "URL scheme to force into generated URLs for a vhost."},
920    
921   {"ShibDisable", (config_fn_t)ap_set_flag_slot,
922    (void *) XtOffsetOf (shib_dir_config, bOff),
923    OR_AUTHCFG, FLAG, "Disable all Shib module activity here to save processing effort"},
924   {"ShibApplicationId", (config_fn_t)ap_set_string_slot,
925    (void *) XtOffsetOf (shib_dir_config, szApplicationId),
926    OR_AUTHCFG, FLAG, "Set Shibboleth applicationId property for content"},
927   {"ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
928    (void *) XtOffsetOf (shib_dir_config, bBasicHijack),
929    OR_AUTHCFG, FLAG, "Respond to AuthType Basic and convert to shib?"},
930   {"ShibRequireSession", (config_fn_t)ap_set_flag_slot,
931    (void *) XtOffsetOf (shib_dir_config, bRequireSession),
932    OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist."},
933   {"ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
934    (void *) XtOffsetOf (shib_dir_config, szRequireWith),
935    OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist using a specific SessionInitiator"},
936   {"ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
937    (void *) XtOffsetOf (shib_dir_config, bExportAssertion),
938    OR_AUTHCFG, FLAG, "Export SAML attribute assertion(s) to Shib-Attributes header?"},
939   {"AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
940    (void *) XtOffsetOf (shib_dir_config, szAuthGrpFile),
941    OR_AUTHCFG, TAKE1, "text file containing group names and member user IDs"},
942   {"ShibRequireAll", (config_fn_t)ap_set_flag_slot,
943    (void *) XtOffsetOf (shib_dir_config, bRequireAll),
944    OR_AUTHCFG, FLAG, "All require directives must match!"},
945
946   {NULL}
947 };
948
949 extern "C"{
950 handler_rec shib_handlers[] = {
951   { "shib-handler", shib_handler },
952   { NULL }
953 };
954
955 module MODULE_VAR_EXPORT mod_shib = {
956     STANDARD_MODULE_STUFF,
957     NULL,                        /* initializer */
958     create_shib_dir_config,     /* dir config creater */
959     merge_shib_dir_config,      /* dir merger --- default is to override */
960     create_shib_server_config, /* server config */
961     merge_shib_server_config,   /* merge server config */
962     shire_cmds,                 /* command table */
963     shib_handlers,              /* handlers */
964     NULL,                       /* filename translation */
965     shib_check_user,            /* check_user_id */
966     shib_auth_checker,          /* check auth */
967     NULL,                       /* check access */
968     NULL,                       /* type_checker */
969     NULL,                       /* fixups */
970     NULL,                       /* logger */
971     NULL,                       /* header parser */
972     shib_child_init,            /* child_init */
973     shib_child_exit,            /* child_exit */
974     NULL                        /* post read-request */
975 };
976
977 #elif defined(SHIB_APACHE_20)
978
979 extern "C" void shib_register_hooks (apr_pool_t *p)
980 {
981   ap_hook_child_init(shib_child_init, NULL, NULL, APR_HOOK_MIDDLE);
982   ap_hook_check_user_id(shib_check_user, NULL, NULL, APR_HOOK_MIDDLE);
983   ap_hook_auth_checker(shib_auth_checker, NULL, NULL, APR_HOOK_FIRST);
984   ap_hook_handler(shib_handler, NULL, NULL, APR_HOOK_LAST);
985 }
986
987 // SHIB Module commands
988
989 extern "C" {
990 static command_rec shib_cmds[] = {
991   AP_INIT_TAKE1("ShibConfig",
992                 (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
993                 RSRC_CONF, "Path to shibboleth.xml config file."),
994   AP_INIT_TAKE1("ShibSchemaDir",
995      (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
996       RSRC_CONF, "Path to Shibboleth XML schema directory."),
997
998   AP_INIT_TAKE1("ShibURLScheme",
999      (config_fn_t)shib_set_server_string_slot,
1000      (void *) offsetof (shib_server_config, szScheme),
1001       RSRC_CONF, "URL scheme to force into generated URLs for a vhost."),
1002
1003   AP_INIT_FLAG("ShibDisable", (config_fn_t)ap_set_flag_slot,
1004          (void *) offsetof (shib_dir_config, bOff),
1005         OR_AUTHCFG, "Disable all Shib module activity here to save processing effort"),
1006   AP_INIT_FLAG("ShibApplicationId", (config_fn_t)ap_set_string_slot,
1007          (void *) offsetof (shib_dir_config, szApplicationId),
1008         OR_AUTHCFG, "Set Shibboleth applicationId property for content"),
1009   AP_INIT_FLAG("ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1010                (void *) offsetof (shib_dir_config, bBasicHijack),
1011                OR_AUTHCFG, "Respond to AuthType Basic and convert to shib?"),
1012   AP_INIT_FLAG("ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1013          (void *) offsetof (shib_dir_config, bRequireSession),
1014         OR_AUTHCFG, "Initiates a new session if one does not exist."),
1015   AP_INIT_FLAG("ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
1016          (void *) offsetof (shib_dir_config, szRequireWith),
1017         OR_AUTHCFG, "Initiates a new session if one does not exist using a specific SessionInitiator"),
1018   AP_INIT_FLAG("ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1019          (void *) offsetof (shib_dir_config, bExportAssertion),
1020         OR_AUTHCFG, "Export SAML attribute assertion(s) to Shib-Attributes header?"),
1021   AP_INIT_TAKE1("AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
1022                 (void *) offsetof (shib_dir_config, szAuthGrpFile),
1023                 OR_AUTHCFG, "Text file containing group names and member user IDs"),
1024   AP_INIT_FLAG("ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1025                (void *) offsetof (shib_dir_config, bRequireAll),
1026                OR_AUTHCFG, "All require directives must match!"),
1027
1028   {NULL}
1029 };
1030
1031 module AP_MODULE_DECLARE_DATA mod_shib = {
1032     STANDARD20_MODULE_STUFF,
1033     create_shib_dir_config,     /* create dir config */
1034     merge_shib_dir_config,      /* merge dir config --- default is to override */
1035     create_shib_server_config,  /* create server config */
1036     merge_shib_server_config,   /* merge server config */
1037     shib_cmds,                  /* command table */
1038     shib_register_hooks         /* register hooks */
1039 };
1040
1041 #else
1042 #error "undefined APACHE version"
1043 #endif
1044
1045 }