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