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