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