Added redirectToSSL option to block non-SSL access.
[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=ap_table_get(sta->m_req->headers_in,wrapper->getHeader());
759             while (*t && vals) {
760                 w=ap_getword_conf(sta->m_req->pool,&t);
761                 if (*w=='~') {
762                     regexp=true;
763                     continue;
764                 }
765
766                 try {
767                     auto_ptr<RegularExpression> re;
768                     if (regexp) {
769                         delete re.release();
770                         auto_ptr<XMLCh> trans(fromUTF8(w));
771                         auto_ptr<RegularExpression> temp(new RegularExpression(trans.get()));
772                         re=temp;
773                     }
774                     
775                     string vals_str(vals);
776                     unsigned int j = 0;
777                     for (unsigned int i = 0;  i < vals_str.length();  i++) {
778                         if (vals_str.at(i) == ';') {
779                             if (i == 0) {
780                                 st->log(ShibTarget::LogLevelError, string("htAccessControl plugin found invalid header encoding (") +
781                                     vals + "): starts with a semicolon");
782                                 throw SAMLException("Invalid information supplied to authorization plugin.");
783                             }
784
785                             if (vals_str.at(i-1) == '\\') {
786                                 vals_str.erase(i-1, 1);
787                                 i--;
788                                 continue;
789                             }
790
791                             string val = vals_str.substr(j, i-j);
792                             j = i+1;
793                             if (regexp) {
794                                 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
795                                 if (re->matches(trans.get())) {
796                                     st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
797                                        ", got " + val + ": authorization granted");
798                                     SHIB_AP_CHECK_IS_OK;
799                                 }
800                             }
801                             else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
802                                 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
803                                     ", got " + val + ": authorization granted.");
804                                 SHIB_AP_CHECK_IS_OK;
805                             }
806                             else {
807                                 st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
808                                     ", got " + val + ": authoritzation not granted.");
809                             }
810                         }
811                     }
812     
813                     string val = vals_str.substr(j, vals_str.length()-j);
814                     if (regexp) {
815                         auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
816                         if (re->matches(trans.get())) {
817                             st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
818                                 ", got " + val + ": authorization granted.");
819                             SHIB_AP_CHECK_IS_OK;
820                         }
821                     }
822                     else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
823                         st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
824                             ", got " + val + ": authorization granted");
825                         SHIB_AP_CHECK_IS_OK;
826                     }
827                     else {
828                             st->log(ShibTarget::LogLevelDebug, string("htAccessControl plugin expecting ") + w +
829                                 ", got " + val + ": authorization not granted");
830                     }
831                 }
832                 catch (XMLException& ex) {
833                     auto_ptr_char tmp(ex.getMessage());
834                     st->log(ShibTarget::LogLevelError, string("htAccessControl plugin caught exception while parsing regular expression (")
835                         + w + "): " + tmp.get());
836                 }
837             }
838         }
839     }
840
841     // check if all require directives are true
842     bool auth_all_OK = true;
843     for (int i= 0; i<reqs_arr->nelts; i++) {
844         auth_all_OK &= auth_OK[i];
845     }
846     if (auth_all_OK || !method_restricted)
847         return true;
848
849     return false;
850 }
851
852 #ifndef SHIB_APACHE_13
853 /*
854  * shib_exit()
855  *  Empty cleanup hook, Apache 2.x doesn't check NULL very well...
856  */
857 extern "C" apr_status_t shib_exit(void* data)
858 {
859     if (g_Config) {
860         g_Config->shutdown();
861         g_Config = NULL;
862     }
863     ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,0,NULL,"shib_exit() done\n");
864     return OK;
865 }
866 #endif
867
868
869 /*
870  * shib_child_exit()
871  *  Cleanup the (per-process) pool info.
872  */
873 #ifdef SHIB_APACHE_13
874 extern "C" void shib_child_exit(server_rec* s, SH_AP_POOL* p)
875 {
876 #else
877 extern "C" apr_status_t shib_child_exit(void* data)
878 {
879   server_rec* s = NULL;
880 #endif
881
882     ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit(%d) dealing with g_Config..", (int)getpid());
883     g_Config->shutdown();
884     g_Config = NULL;
885     ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit() done\n");
886
887 #ifndef SHIB_APACHE_13
888     return OK;
889 #endif
890 }
891
892 /* 
893  * shire_child_init()
894  *  Things to do when the child process is initialized.
895  *  (or after the configs are read in apache-2)
896  */
897 #ifdef SHIB_APACHE_13
898 extern "C" void shib_child_init(server_rec* s, SH_AP_POOL* p)
899 #else
900 extern "C" void shib_child_init(apr_pool_t* p, server_rec* s)
901 #endif
902 {
903     // Initialize runtime components.
904
905     ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init(%d) starting", (int)getpid());
906
907     if (g_Config) {
908         ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() already initialized!");
909         exit(1);
910     }
911
912     try {
913         g_Config=&ShibTargetConfig::getConfig();
914         g_Config->setFeatures(
915             ShibTargetConfig::Listener |
916             ShibTargetConfig::Metadata |
917             ShibTargetConfig::AAP |
918             ShibTargetConfig::RequestMapper |
919             ShibTargetConfig::LocalExtensions |
920             ShibTargetConfig::Logging
921             );
922         if (!g_Config->init(g_szSchemaDir)) {
923             ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize libraries");
924             exit(1);
925         }
926         SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::htAccessControlType,&htAccessFactory);
927         SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::NativeRequestMapType,&ApacheRequestMapFactory);
928         // We hijack the legacy type so that 1.2 config files will load this plugin
929         SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::LegacyRequestMapType,&ApacheRequestMapFactory);
930         
931         if (!g_Config->load(g_szSHIBConfig)) {
932             ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to load configuration");
933             exit(1);
934         }
935     }
936     catch (...) {
937         ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize system");
938         exit(1);
939     }
940
941     // Set the cleanup handler
942     apr_pool_cleanup_register(p, NULL, &shib_exit, &shib_child_exit);
943
944     ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() done");
945 }
946
947 typedef const char* (*config_fn_t)(void);
948
949 #ifdef SHIB_APACHE_13
950
951 // SHIB Module commands
952
953 static command_rec shire_cmds[] = {
954   {"SHIREConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
955    RSRC_CONF, TAKE1, "Path to shibboleth.xml config file"},
956   {"ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
957    RSRC_CONF, TAKE1, "Path to shibboleth.xml config file"},
958   {"ShibSchemaDir", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
959    RSRC_CONF, TAKE1, "Path to Shibboleth XML schema directory"},
960
961   {"ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
962    (void *) XtOffsetOf (shib_server_config, szScheme),
963    RSRC_CONF, TAKE1, "URL scheme to force into generated URLs for a vhost"},
964    
965   {"ShibDisable", (config_fn_t)ap_set_flag_slot,
966    (void *) XtOffsetOf (shib_dir_config, bOff),
967    OR_AUTHCFG, FLAG, "Disable all Shib module activity here to save processing effort"},
968   {"ShibApplicationId", (config_fn_t)ap_set_string_slot,
969    (void *) XtOffsetOf (shib_dir_config, szApplicationId),
970    OR_AUTHCFG, TAKE1, "Set Shibboleth applicationId property for content"},
971   {"ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
972    (void *) XtOffsetOf (shib_dir_config, bBasicHijack),
973    OR_AUTHCFG, FLAG, "Respond to AuthType Basic and convert to shibboleth"},
974   {"ShibRequireSession", (config_fn_t)ap_set_flag_slot,
975    (void *) XtOffsetOf (shib_dir_config, bRequireSession),
976    OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist"},
977   {"ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
978    (void *) XtOffsetOf (shib_dir_config, szRequireWith),
979    OR_AUTHCFG, TAKE1, "Initiates a new session if one does not exist using a specific SessionInitiator"},
980   {"ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
981    (void *) XtOffsetOf (shib_dir_config, bExportAssertion),
982    OR_AUTHCFG, FLAG, "Export SAML attribute assertion(s) to Shib-Attributes header"},
983   {"ShibRedirectToSSL", (config_fn_t)ap_set_string_slot,
984    (void *) XtOffsetOf (shib_dir_config, szRedirectToSSL),
985    OR_AUTHCFG, TAKE1, "Redirect non-SSL requests to designated port" },
986   {"AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
987    (void *) XtOffsetOf (shib_dir_config, szAuthGrpFile),
988    OR_AUTHCFG, TAKE1, "text file containing group names and member user IDs"},
989   {"ShibRequireAll", (config_fn_t)ap_set_flag_slot,
990    (void *) XtOffsetOf (shib_dir_config, bRequireAll),
991    OR_AUTHCFG, FLAG, "All require directives must match"},
992
993   {NULL}
994 };
995
996 extern "C"{
997 handler_rec shib_handlers[] = {
998   { "shib-handler", shib_handler },
999   { NULL }
1000 };
1001
1002 module MODULE_VAR_EXPORT mod_shib = {
1003     STANDARD_MODULE_STUFF,
1004     NULL,                        /* initializer */
1005     create_shib_dir_config,     /* dir config creater */
1006     merge_shib_dir_config,      /* dir merger --- default is to override */
1007     create_shib_server_config, /* server config */
1008     merge_shib_server_config,   /* merge server config */
1009     shire_cmds,                 /* command table */
1010     shib_handlers,              /* handlers */
1011     NULL,                       /* filename translation */
1012     shib_check_user,            /* check_user_id */
1013     shib_auth_checker,          /* check auth */
1014     NULL,                       /* check access */
1015     NULL,                       /* type_checker */
1016     NULL,                       /* fixups */
1017     NULL,                       /* logger */
1018     NULL,                       /* header parser */
1019     shib_child_init,            /* child_init */
1020     shib_child_exit,            /* child_exit */
1021     NULL                        /* post read-request */
1022 };
1023
1024 #elif defined(SHIB_APACHE_20)
1025
1026 extern "C" void shib_register_hooks (apr_pool_t *p)
1027 {
1028   ap_hook_child_init(shib_child_init, NULL, NULL, APR_HOOK_MIDDLE);
1029   ap_hook_check_user_id(shib_check_user, NULL, NULL, APR_HOOK_MIDDLE);
1030   ap_hook_auth_checker(shib_auth_checker, NULL, NULL, APR_HOOK_FIRST);
1031   ap_hook_handler(shib_handler, NULL, NULL, APR_HOOK_LAST);
1032 }
1033
1034 // SHIB Module commands
1035
1036 extern "C" {
1037 static command_rec shib_cmds[] = {
1038   AP_INIT_TAKE1("ShibConfig",
1039                 (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1040                 RSRC_CONF, "Path to shibboleth.xml config file"),
1041   AP_INIT_TAKE1("ShibSchemaDir",
1042      (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1043       RSRC_CONF, "Path to Shibboleth XML schema directory"),
1044
1045   AP_INIT_TAKE1("ShibURLScheme",
1046      (config_fn_t)shib_set_server_string_slot,
1047      (void *) offsetof (shib_server_config, szScheme),
1048       RSRC_CONF, "URL scheme to force into generated URLs for a vhost"),
1049
1050   AP_INIT_FLAG("ShibDisable", (config_fn_t)ap_set_flag_slot,
1051         (void *) offsetof (shib_dir_config, bOff),
1052         OR_AUTHCFG, "Disable all Shib module activity here to save processing effort"),
1053   AP_INIT_TAKE1("ShibApplicationId", (config_fn_t)ap_set_string_slot,
1054         (void *) offsetof (shib_dir_config, szApplicationId),
1055         OR_AUTHCFG, "Set Shibboleth applicationId property for content"),
1056   AP_INIT_FLAG("ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1057         (void *) offsetof (shib_dir_config, bBasicHijack),
1058         OR_AUTHCFG, "Respond to AuthType Basic and convert to shibboleth"),
1059   AP_INIT_FLAG("ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1060         (void *) offsetof (shib_dir_config, bRequireSession),
1061         OR_AUTHCFG, "Initiates a new session if one does not exist"),
1062   AP_INIT_TAKE1("ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
1063         (void *) offsetof (shib_dir_config, szRequireWith),
1064         OR_AUTHCFG, "Initiates a new session if one does not exist using a specific SessionInitiator"),
1065   AP_INIT_FLAG("ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1066         (void *) offsetof (shib_dir_config, bExportAssertion),
1067         OR_AUTHCFG, "Export SAML attribute assertion(s) to Shib-Attributes header"),
1068   AP_INIT_TAKE1("ShibRedirectToSSL", (config_fn_t)ap_set_string_slot,
1069         (void *) offsetof (shib_dir_config, szRedirectToSSL),
1070         OR_AUTHCFG, "Redirect non-SSL requests to designated port"),
1071   AP_INIT_TAKE1("AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
1072                 (void *) offsetof (shib_dir_config, szAuthGrpFile),
1073                 OR_AUTHCFG, "Text file containing group names and member user IDs"),
1074   AP_INIT_FLAG("ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1075         (void *) offsetof (shib_dir_config, bRequireAll),
1076         OR_AUTHCFG, "All require directives must match"),
1077
1078   {NULL}
1079 };
1080
1081 module AP_MODULE_DECLARE_DATA mod_shib = {
1082     STANDARD20_MODULE_STUFF,
1083     create_shib_dir_config,     /* create dir config */
1084     merge_shib_dir_config,      /* merge dir config --- default is to override */
1085     create_shib_server_config,  /* create server config */
1086     merge_shib_server_config,   /* merge server config */
1087     shib_cmds,                  /* command table */
1088     shib_register_hooks         /* register hooks */
1089 };
1090
1091 #else
1092 #error "undefined APACHE version"
1093 #endif
1094
1095 }