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