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