New profile API, consolidated RPCs, simplified cache.
[shibboleth/sp.git] / apache / mod_apache.cpp
1 /*
2  * mod_apache.cpp -- the core Apache Module code
3  *
4  * Created by:  Derek Atkins <derek@ihtfp.com>
5  *
6  * $Id$
7  */
8
9 #ifdef SOLARIS2
10 #undef _XOPEN_SOURCE    // causes gethostname conflict in unistd.h
11 #endif
12
13 // SAML Runtime
14 #include <saml/saml.h>
15 #include <shib/shib.h>
16 #include <shib/shib-threads.h>
17 #include <shib-target/shib-target.h>
18 #include <xercesc/util/regx/RegularExpression.hpp>
19
20 #undef _XPG4_2
21
22 // Apache specific header files
23 #include <httpd.h>
24 #include <http_config.h>
25 #include <http_protocol.h>
26 #include <http_main.h>
27 #define CORE_PRIVATE
28 #include <http_core.h>
29 #include <http_log.h>
30
31 #ifndef SHIB_APACHE_13
32 #include <http_request.h>
33 #include <apr_strings.h>
34 #include <apr_pools.h>
35 #endif
36
37 #include <fstream>
38 #include <sstream>
39
40 #ifdef HAVE_UNISTD_H
41 #include <unistd.h>             // for getpid()
42 #endif
43
44 using namespace std;
45 using namespace saml;
46 using namespace shibboleth;
47 using namespace shibtarget;
48
49 extern "C" module MODULE_VAR_EXPORT mod_shib;
50 #if 0
51 int shib_handler(request_rec* r, const IApplication* application, SHIRE& shire);
52 #endif
53
54 namespace {
55     char* g_szSHIBConfig = NULL;
56     char* g_szSchemaDir = NULL;
57     ShibTargetConfig* g_Config = NULL;
58     static const char* g_UserDataKey = "_shib_check_user_";
59 }
60
61 /********************************************************************************/
62 // Basic Apache Configuration code.
63 //
64
65 // per-server module configuration structure
66 struct shib_server_config
67 {
68     char* szScheme;
69 };
70
71 // creates the per-server configuration
72 extern "C" void* create_shib_server_config(SH_AP_POOL* p, server_rec* s)
73 {
74     shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
75     sc->szScheme = NULL;
76     return sc;
77 }
78
79 // overrides server configuration in virtual servers
80 extern "C" void* merge_shib_server_config (SH_AP_POOL* p, void* base, void* sub)
81 {
82     shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
83     shib_server_config* parent=(shib_server_config*)base;
84     shib_server_config* child=(shib_server_config*)sub;
85
86     if (child->szScheme)
87         sc->szScheme=ap_pstrdup(p,child->szScheme);
88     else if (parent->szScheme)
89         sc->szScheme=ap_pstrdup(p,parent->szScheme);
90     else
91         sc->szScheme=NULL;
92
93     return sc;
94 }
95
96 // per-dir module configuration structure
97 struct shib_dir_config
98 {
99     // RM Configuration
100     char* szAuthGrpFile;    // Auth GroupFile name
101     int bRequireAll;        // all require directives must match, otherwise OR logic
102
103     // SHIRE Configuration
104     int bBasicHijack;       // activate for AuthType Basic?
105     int bRequireSession;    // require a session?
106     int bExportAssertion;   // export SAML assertion to the environment?
107 };
108
109 // creates per-directory config structure
110 extern "C" void* create_shib_dir_config (SH_AP_POOL* p, char* d)
111 {
112     shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
113     dc->bBasicHijack = -1;
114     dc->bRequireSession = -1;
115     dc->bExportAssertion = -1;
116     dc->bRequireAll = -1;
117     dc->szAuthGrpFile = NULL;
118     return dc;
119 }
120
121 // overrides server configuration in directories
122 extern "C" void* merge_shib_dir_config (SH_AP_POOL* p, void* base, void* sub)
123 {
124     shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
125     shib_dir_config* parent=(shib_dir_config*)base;
126     shib_dir_config* child=(shib_dir_config*)sub;
127
128     if (child->szAuthGrpFile)
129         dc->szAuthGrpFile=ap_pstrdup(p,child->szAuthGrpFile);
130     else if (parent->szAuthGrpFile)
131         dc->szAuthGrpFile=ap_pstrdup(p,parent->szAuthGrpFile);
132     else
133         dc->szAuthGrpFile=NULL;
134
135     dc->bBasicHijack=((child->bBasicHijack==-1) ? parent->bBasicHijack : child->bBasicHijack);
136     dc->bRequireSession=((child->bRequireSession==-1) ? parent->bRequireSession : child->bRequireSession);
137     dc->bExportAssertion=((child->bExportAssertion==-1) ? parent->bExportAssertion : child->bExportAssertion);
138     dc->bRequireAll=((child->bRequireAll==-1) ? parent->bRequireAll : child->bRequireAll);
139     return dc;
140 }
141
142 // generic global slot handlers
143 extern "C" const char* ap_set_global_string_slot(cmd_parms* parms, void*, const char* arg)
144 {
145     *((char**)(parms->info))=ap_pstrdup(parms->pool,arg);
146     return NULL;
147 }
148
149 extern "C" const char* shib_set_server_string_slot(cmd_parms* parms, void*, const char* arg)
150 {
151     char* base=(char*)ap_get_module_config(parms->server->module_config,&mod_shib);
152     int offset=(int)parms->info;
153     *((char**)(base + offset))=ap_pstrdup(parms->pool,arg);
154     return NULL;
155 }
156
157 extern "C" const char* shib_ap_set_file_slot(cmd_parms* parms,
158 #ifdef SHIB_APACHE_13
159                                              char* arg1, char* arg2
160 #else
161                                              void* arg1, const char* arg2
162 #endif
163                                              )
164 {
165   ap_set_file_slot(parms, arg1, arg2);
166   return DECLINE_CMD;
167 }
168
169 /********************************************************************************/
170 // Some other useful helper function(s)
171
172 static SH_AP_TABLE* groups_for_user(request_rec* r, const char* user, char* grpfile)
173 {
174     SH_AP_CONFIGFILE* f;
175     SH_AP_TABLE* grps=ap_make_table(r->pool,15);
176     char l[MAX_STRING_LEN];
177     const char *group_name, *ll, *w;
178
179 #ifdef SHIB_APACHE_13
180     if (!(f=ap_pcfg_openfile(r->pool,grpfile))) {
181 #else
182     if (ap_pcfg_openfile(&f,r->pool,grpfile) != APR_SUCCESS) {
183 #endif
184         ap_log_rerror(APLOG_MARK,APLOG_DEBUG,SH_AP_R(r),"groups_for_user() could not open group file: %s\n",grpfile);
185         return NULL;
186     }
187
188     SH_AP_POOL* sp;
189 #ifdef SHIB_APACHE_13
190     sp=ap_make_sub_pool(r->pool);
191 #else
192     if (apr_pool_create(&sp,r->pool) != APR_SUCCESS) {
193         ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,
194             "groups_for_user() could not create a subpool");
195         return NULL;
196     }
197 #endif
198
199     while (!(ap_cfg_getline(l,MAX_STRING_LEN,f))) {
200         if ((*l=='#') || (!*l))
201             continue;
202         ll = l;
203         ap_clear_pool(sp);
204
205         group_name=ap_getword(sp,&ll,':');
206
207         while (*ll) {
208             w=ap_getword_conf(sp,&ll);
209             if (!strcmp(w,user)) {
210                 ap_table_setn(grps,ap_pstrdup(r->pool,group_name),"in");
211                 break;
212             }
213         }
214     }
215     ap_cfg_closefile(f);
216     ap_destroy_pool(sp);
217     return grps;
218 }
219
220 /********************************************************************************/
221 // Apache ShibTarget subclass(es) here.
222
223 class HTGroupTableApache : public HTGroupTable
224 {
225 public:
226   HTGroupTableApache(request_rec* r, const char *user, char *grpfile) {
227     groups = groups_for_user(r, user, grpfile);
228     if (!groups)
229       throw ShibTargetException(SHIBRPC_OK, "EEP");
230   }
231   ~HTGroupTableApache() {}
232   bool lookup(const char *entry) { return (ap_table_get(groups, entry)!=NULL); }
233   SH_AP_TABLE* groups;
234 };
235
236 class ShibTargetApache : public ShibTarget
237 {
238 public:
239   ShibTargetApache(request_rec* req) {
240     m_sc = (shib_server_config*)
241       ap_get_module_config(req->server->module_config, &mod_shib);
242
243     m_dc = (shib_dir_config*)ap_get_module_config(req->per_dir_config, &mod_shib);
244
245     const char* ct = ap_table_get(req->headers_in, "Content-type");
246
247     init(g_Config, string(m_sc->szScheme ? m_sc->szScheme : ap_http_method(req)),
248          string(ap_get_server_name(req)), (int)ap_get_server_port(req),
249          string(req->unparsed_uri), string(ct ? ct : ""),
250          string(req->connection->remote_ip), string(req->method));
251
252     m_req = req;
253   }
254   ~ShibTargetApache() { }
255
256   virtual void log(ShibLogLevel level, const string &msg) {
257     ap_log_rerror(APLOG_MARK,
258                   (level == LogLevelDebug ? APLOG_DEBUG :
259                    (level == LogLevelInfo ? APLOG_INFO :
260                     (level == LogLevelWarn ? APLOG_WARNING :
261                      APLOG_ERR)))|APLOG_NOERRNO, SH_AP_R(m_req),
262                   msg.c_str());
263   }
264   virtual string getCookies(void) {
265     const char *c = ap_table_get(m_req->headers_in, "Cookie");
266     return string(c ? c : "");
267   }
268   virtual void setCookie(const string &name, const string &value) {
269     char* val = ap_psprintf(m_req->pool, "%s=%s", name.c_str(), value.c_str());
270     ap_table_setn(m_req->err_headers_out, "Set-Cookie", val);
271   }
272   virtual string getArgs(void) { return string(m_req->args ? m_req->args : ""); }
273   virtual string getPostData(void) {
274     // Read the posted data
275     if (ap_setup_client_block(m_req, REQUEST_CHUNKED_ERROR))
276       throw ShibTargetException(SHIBRPC_OK, "CGI setup_client_block failed");
277     if (!ap_should_client_block(m_req))
278       throw ShibTargetException(SHIBRPC_OK, "CGI should_client_block failed");
279     if (m_req->remaining > 1024*1024)
280       throw ShibTargetException (SHIBRPC_OK, "CGI length too long...");
281
282     string cgistr;
283     char buff[HUGE_STRING_LEN];
284     ap_hard_timeout("[mod_shib] getPostData", m_req);
285     memset(buff, 0, sizeof(buff));
286     while (ap_get_client_block(m_req, buff, sizeof(buff)-1) > 0) {
287       ap_reset_timeout(m_req);
288       cgistr += buff;
289       memset(buff, 0, sizeof(buff));
290     }
291     ap_kill_timeout(m_req);
292
293     return cgistr;
294   }
295   virtual void clearHeader(const string &name) {
296     ap_table_unset(m_req->headers_in, name.c_str());
297   }
298   virtual void setHeader(const string &name, const string &value) {
299     ap_table_set(m_req->headers_in, name.c_str(), value.c_str());
300   }
301   virtual string getHeader(const string &name) {
302     const char *hdr = ap_table_get(m_req->headers_in, name.c_str());
303     return string(hdr ? hdr : "");
304   }
305   virtual void setRemoteUser(const string &user) {
306     SH_AP_USER(m_req) = ap_pstrdup(m_req->pool, user.c_str());
307   }
308   virtual string getRemoteUser(void) {
309     return string(SH_AP_USER(m_req) ? SH_AP_USER(m_req) : "");
310   }
311   // override so we can look at the actual auth type and maybe override it.
312   virtual string getAuthType(void) {
313     const char *auth_type=ap_auth_type(m_req);
314     if (!auth_type)
315         return string("");
316     if (strcasecmp(auth_type, "shibboleth")) {
317       if (!strcasecmp(auth_type, "basic") && m_dc->bBasicHijack == 1) {
318         core_dir_config* conf= (core_dir_config*)
319           ap_get_module_config(m_req->per_dir_config,
320                                ap_find_linked_module("http_core.c"));
321         auth_type = conf->ap_auth_type = "shibboleth";
322       }
323     }
324     return string(auth_type);
325   }
326   // Override this function because we want to add the Apache Directory override
327   virtual pair<bool,bool> getRequireSession(IRequestMapper::Settings &settings) {
328     pair<bool,bool> requireSession = settings.first->getBool("requireSession");
329     if (!requireSession.first || !requireSession.second)
330       if (m_dc->bRequireSession == 1)
331         requireSession.second=true;
332
333     return requireSession;
334   }
335
336   virtual HTAccessInfo* getAccessInfo(void) { 
337     int m = m_req->method_number;
338     const array_header* reqs_arr = ap_requires(m_req);
339     if (!reqs_arr)
340       return NULL;
341
342     require_line* reqs = (require_line*) reqs_arr->elts;
343
344     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req),
345                   "REQUIRE nelts: %d", reqs_arr->nelts);
346     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req),
347                   "REQUIRE all: %d", m_dc->bRequireAll);
348
349     HTAccessInfo* ht = new HTAccessInfo();
350     ht->requireAll = (m_dc->bRequireAll >= 0);
351     ht->elements.reserve(reqs_arr->nelts);
352     for (int x = 0; x < reqs_arr->nelts; x++) {
353       HTAccessInfo::RequireLine* rline = new HTAccessInfo::RequireLine();
354       rline->use_line = (reqs[x].method_mask & (1 << m));
355       rline->tokens.reserve(6); // No reason to reserve specifically 6 tokens
356       const char* t = reqs[x].requirement;
357       const char* w = ap_getword_white(m_req->pool, &t);
358       rline->tokens.push_back(w);
359       while (*t) {
360         w = ap_getword_conf(m_req->pool, &t);
361         rline->tokens.push_back(w);
362       }
363       ht->elements.push_back(rline);
364     }
365     return ht;
366   }
367   virtual HTGroupTable* getGroupTable(string &user) {
368     if (m_dc->szAuthGrpFile && !user.empty()) {
369       ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req),
370                     "getGroupTable() using groups file: %s\n",
371                     m_dc->szAuthGrpFile);
372       try {
373         HTGroupTableApache *gt = new HTGroupTableApache(m_req, user.c_str(),
374                                                         m_dc->szAuthGrpFile);
375         return gt;
376       } catch (...) { }
377     }
378     return NULL;
379   }
380
381   virtual void* sendPage(
382     const string &msg,
383     const string content_type,
384         const saml::Iterator<header_t>& headers=EMPTY(header_t),
385     int code=200
386     ) {
387     m_req->content_type = ap_psprintf(m_req->pool, content_type.c_str());
388     while (headers.hasNext()) {
389         const header_t& h=headers.next();
390         ap_table_setn(m_req->headers_out, h.first.c_str(), h.second.c_str());
391     }
392     ap_send_http_header(m_req);
393     ap_rprintf(m_req, msg.c_str());
394     return (void*)DONE;
395   }
396   virtual void* sendRedirect(const string url) {
397     ap_table_set(m_req->headers_out, "Location", url.c_str());
398     return (void*)REDIRECT;
399   }
400   virtual void* returnDecline(void) { return (void*)DECLINED; }
401   virtual void* returnOK(void) { return (void*)OK; }
402
403   request_rec* m_req;
404   shib_dir_config* m_dc;
405   shib_server_config* m_sc;
406 };
407
408 /********************************************************************************/
409 // Apache handlers
410
411 extern "C" int shib_check_user(request_rec* r)
412 {
413   ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
414                 "shib_check_user(%d): ENTER\n", (int)getpid());
415
416   ostringstream threadid;
417   threadid << "[" << getpid() << "] shib_check_user" << '\0';
418   saml::NDC ndc(threadid.str().c_str());
419
420 #ifndef _DEBUG
421   try {
422 #endif
423     ShibTargetApache sta(r);
424
425     // Check user authentication, the set the post handler bypass
426     pair<bool,void*> res = sta.doCheckAuthN((sta.m_dc->bRequireSession == 1), true);
427     apr_pool_userdata_setn((const void*)42,g_UserDataKey,NULL,r->pool);
428     if (res.first) return (int)res.second;
429
430     // user auth was okay -- export the assertions now
431     res = sta.doExportAssertions((sta.m_dc->bExportAssertion == 1));
432     if (res.first) return (int)res.second;
433
434     // export happened successfully..  this user is ok.
435     return OK;
436
437 #ifndef _DEBUG
438   } catch (...) {
439     ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r),
440                   "shib_check_user threw an uncaught exception!");
441     return SERVER_ERROR;
442   }
443 #endif
444 }
445
446 extern "C" int shib_post_handler(request_rec* r)
447 {
448   ostringstream threadid;
449   threadid << "[" << getpid() << "] shib_post_handler" << '\0';
450   saml::NDC ndc(threadid.str().c_str());
451
452 #ifndef SHIB_APACHE_13
453   // With 2.x, this handler always runs, though last.
454   // We check if shib_check_user ran, because it will detect a SHIRE request
455   // and dispatch it directly.
456   void* data;
457   apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
458   if (data==(const void*)42) {
459     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_post_handler skipped since check_user ran");
460     return DECLINED;
461   }
462 #endif
463
464   ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
465                 "shib_post_handler(%d): ENTER", (int)getpid());
466
467 #ifndef _DEBUG
468   try {
469 #endif
470     ShibTargetApache sta(r);
471
472     pair<bool,void*> res = sta.doHandleProfile();
473     if (res.first) return (int)res.second;
474
475     ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r),
476                   "doHandleProfile() did not do anything.");
477     return SERVER_ERROR;
478
479 #ifndef _DEBUG
480   } catch (...) {
481     ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r),
482                   "shib_post_handler threw an uncaught exception!");
483     return SERVER_ERROR;
484   }
485 #endif
486 }
487
488 /*
489  * shib_auth_checker() -- a simple resource manager to
490  * process the .htaccess settings and copy attributes
491  * into the HTTP headers.
492  */
493 extern "C" int shib_auth_checker(request_rec* r)
494 {
495   ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
496                 "shib_check_user(%d): ENTER", (int)getpid());
497
498   ostringstream threadid;
499   threadid << "[" << getpid() << "] shib_auth_checker" << '\0';
500   saml::NDC ndc(threadid.str().c_str());
501
502 #ifndef _DEBUG
503   try {
504 #endif
505     ShibTargetApache sta(r);
506
507     pair<bool,void*> res = sta.doCheckAuthZ();
508     if (res.first) return (int)res.second;
509
510     // We're all okay.
511     return OK;
512
513 #ifndef _DEBUG
514   } catch (...) {
515     ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r),
516                   "shib_auth_checker threw an uncaught exception!");
517     return SERVER_ERROR;
518   }
519 #endif
520 }
521
522 #if 0
523 static char* shib_get_targeturl(request_rec* r, const char* scheme=NULL)
524 {
525     // On 1.3, this is always canonical, but on 2.0, UseCanonicalName comes into play.
526     // However, we also have a setting to forcibly replace the scheme for esoteric cases.
527     if (scheme) {
528         unsigned port = ap_get_server_port(r);
529         if ((!strcmp(scheme,"http") && port==80) || (!strcmp(scheme,"https") && port==443)) {
530             return ap_pstrcat(r->pool, scheme, "://", ap_get_server_name(r), r->unparsed_uri, NULL);
531         }
532         return ap_psprintf(r->pool, "%s://%s:%u%s", scheme, ap_get_server_name(r), port, r->unparsed_uri);
533     }
534     return ap_construct_url(r->pool,r->unparsed_uri,r);
535 }
536
537 extern "C" int shib_check_user(request_rec* r)
538 {
539     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: ENTER");
540     shib_dir_config* dc=(shib_dir_config*)ap_get_module_config(r->per_dir_config,&mod_shib);
541     shib_server_config* sc=(shib_server_config*)ap_get_module_config(r->server->module_config,&mod_shib);
542
543     ostringstream threadid;
544     threadid << "[" << getpid() << "] shib_check_user" << '\0';
545     saml::NDC ndc(threadid.str().c_str());
546
547     const char* targeturl=shib_get_targeturl(r,sc->szScheme);
548
549     // We lock the configuration system for the duration.
550     IConfig* conf=g_Config->getINI();
551     Locker locker(conf);
552     
553     // Map request to application and content settings.
554     IRequestMapper* mapper=conf->getRequestMapper();
555     Locker locker2(mapper);
556     IRequestMapper::Settings settings=mapper->getSettingsFromParsedURL(
557         (sc-> szScheme ? sc-> szScheme : ap_http_method(r)), ap_get_server_name(r), ap_get_server_port(r), r->unparsed_uri
558         );
559     pair<bool,const char*> application_id=settings.first->getString("applicationId");
560     const IApplication* application=conf->getApplication(application_id.second);
561     if (!application) {
562         ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
563            "shib_check_user: unable to map request to application settings, check configuration");
564         return SERVER_ERROR;
565     }
566     
567     // Declare SHIRE object for this request.
568     SHIRE shire(application);
569     
570     const char* shireURL=shire.getShireURL(targeturl);
571     if (!shireURL) {
572         ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
573            "shib_check_user: unable to map request to proper shireURL setting, check configuration");
574         return SERVER_ERROR;
575     }
576     
577     // Get location of this application's assertion consumer service and see if this is it.
578     if (strstr(targeturl,shireURL)) {
579         return shib_handler(r,application,shire);
580     }
581
582     // We can short circuit the handler if we run this...
583     apr_pool_userdata_setn((const void*)42,g_UserDataKey,NULL,r->pool);
584
585     // Regular access to arbitrary resource...check AuthType
586     const char *auth_type=ap_auth_type(r);
587     if (!auth_type)
588         return DECLINED;
589
590     if (strcasecmp(auth_type,"shibboleth")) {
591         if (!strcasecmp(auth_type,"basic") && dc->bBasicHijack==1) {
592             core_dir_config* conf=
593                 (core_dir_config*)ap_get_module_config(r->per_dir_config,
594                     ap_find_linked_module("http_core.c"));
595             conf->ap_auth_type="shibboleth";
596         }
597         else
598             return DECLINED;
599     }
600
601     pair<bool,bool> requireSession = settings.first->getBool("requireSession");
602     if (!requireSession.first || !requireSession.second)
603         if (dc->bRequireSession==1)
604             requireSession.second=true;
605
606     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: session check for %s",targeturl);
607
608     pair<const char*,const char*> shib_cookie=shire.getCookieNameProps();   // always returns *something*
609
610     // We're in charge, so check for cookie.
611     const char* session_id=NULL;
612     const char* cookies=ap_table_get(r->headers_in,"Cookie");
613
614     if (cookies) {
615         ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: cookies found: %s",cookies);
616         if (session_id=strstr(cookies,shib_cookie.first)) {
617             // Yep, we found a cookie -- pull it out (our session_id)
618             session_id+=strlen(shib_cookie.first) + 1; /* Skip over the '=' */
619             char* cookiebuf = ap_pstrdup(r->pool,session_id);
620             char* cookieend = strchr(cookiebuf,';');
621             if (cookieend)
622                 *cookieend = '\0';    /* Ignore anyting after a ; */
623             session_id=cookiebuf;
624         }
625     }
626
627     if (!session_id || !*session_id) {
628         // If no session required, bail now.
629         if (!requireSession.second)
630             return OK;
631
632         // No acceptable cookie, and we require a session.  Generate an AuthnRequest.
633         ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: no cookie found -- redirecting to WAYF");
634         ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(targeturl)));
635         return REDIRECT;
636     }
637
638     // Make sure this session is still valid.
639     RPCError* status = NULL;
640     ShibMLP markupProcessor;
641     markupProcessor.insert("requestURL", targeturl);
642
643     try {
644         status = shire.sessionIsValid(session_id, r->connection->remote_ip);
645     }
646     catch (ShibTargetException &e) {
647         ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): %s", e.what());
648         markupProcessor.insert("errorType", "Session Processing Error");
649         markupProcessor.insert("errorText", e.what());
650         markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
651         return shib_error_page(r, application, "shire", markupProcessor);
652     }
653 #ifndef _DEBUG
654     catch (...) {
655         ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): caught unexpected error");
656         markupProcessor.insert("errorType", "Session Processing Error");
657         markupProcessor.insert("errorText", "Unexpected Exception");
658         markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
659         return shib_error_page(r, application, "shire", markupProcessor);
660     }
661 #endif
662
663     // Check the status
664     if (status->isError()) {
665         ap_log_rerror(APLOG_MARK,APLOG_INFO|APLOG_NOERRNO,SH_AP_R(r),
666                       "shib_check_user() session invalid: %s", status->getText());
667
668         // If no session required, bail now.
669         if (!requireSession.second)
670             return OK;  // XXX: Or should this be DECLINED?
671                         // Has to be OK because DECLINED will just cause Apache to fail when it can't locate
672                         // anything to process the AuthType. No session plus requireSession false means 
673                         // do not authenticate the user.
674         else if (status->isRetryable()) {
675             // Oops, session is invalid. Generate AuthnRequest.
676             ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(targeturl)));
677             delete status;
678             return REDIRECT;
679         }
680         else {
681             // return the error page to the user
682             markupProcessor.insert(*status);
683             delete status;
684             return shib_error_page(r, application, "shire", markupProcessor);
685         }
686     }
687
688     delete status;
689     // set the authtype
690 #ifdef SHIB_APACHE_13
691     if (r->connection)
692         r->connection->ap_auth_type = "shibboleth";
693 #else
694     r->ap_auth_type = "shibboleth";
695 #endif
696     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: session successfully verified");
697
698     // This is code transferred in from the auth check to export the attributes.
699     // We could even combine the isSessionValid/getAssertions API...?
700
701     RM rm(application);
702     vector<SAMLAssertion*> assertions;
703     SAMLAuthenticationStatement* sso_statement=NULL;
704
705     try {
706         status = rm.getAssertions(session_id, r->connection->remote_ip, assertions, &sso_statement);
707     }
708     catch (ShibTargetException &e) {
709         ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): %s", e.what());
710         markupProcessor.insert("errorType", "Attribute Processing Error");
711         markupProcessor.insert("errorText", e.what());
712         markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
713         return shib_error_page(r, application, "rm", markupProcessor);
714     }
715 #ifndef _DEBUG
716     catch (...) {
717         ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): caught unexpected error");
718         markupProcessor.insert("errorType", "Attribute Processing Error");
719         markupProcessor.insert("errorText", "Unexpected Exception");
720         markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
721         return shib_error_page(r, application, "rm", markupProcessor);
722     }
723 #endif
724
725     if (status->isError()) {
726         ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
727             "shib_check_user() getAssertions failed: %s", status->getText());
728
729         markupProcessor.insert(*status);
730         delete status;
731         return shib_error_page(r, application, "rm", markupProcessor);
732     }
733     delete status;
734
735     // Do we have an access control plugin?
736     if (settings.second) {
737         Locker acllock(settings.second);
738         if (!settings.second->authorized(*sso_statement,assertions)) {
739             for (int k = 0; k < assertions.size(); k++)
740                 delete assertions[k];
741             delete sso_statement;
742             ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): access control provider denied access");
743             return shib_error_page(r, application, "access", markupProcessor);
744         }
745     }
746
747     // Get the AAP providers, which contain the attribute policy info.
748     Iterator<IAAP*> provs=application->getAAPProviders();
749
750     // Clear out the list of mapped attributes
751     while (provs.hasNext()) {
752         IAAP* aap=provs.next();
753         aap->lock();
754         try {
755             Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
756             while (rules.hasNext()) {
757                 const char* header=rules.next()->getHeader();
758                 if (header)
759                     ap_table_unset(r->headers_in,header);
760             }
761         }
762         catch(...) {
763             aap->unlock();
764             for (int k = 0; k < assertions.size(); k++)
765                 delete assertions[k];
766             delete sso_statement;
767             ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
768                 "shib_check_user(): caught unexpected error while clearing headers");
769             markupProcessor.insert("errorType", "Attribute Processing Error");
770             markupProcessor.insert("errorText", "Unexpected Exception");
771             markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
772             return shib_error_page(r, application, "rm", markupProcessor);
773         }
774         aap->unlock();
775     }
776     provs.reset();
777     
778     // Maybe export the first assertion.
779     ap_table_unset(r->headers_in,"Shib-Attributes");
780     pair<bool,bool> exp=settings.first->getBool("exportAssertion");
781     if (!exp.first || !exp.second)
782         if (dc->bExportAssertion==1)
783             exp.second=true;
784     if (exp.second && assertions.size()) {
785         string assertion;
786         RM::serialize(*(assertions[0]), assertion);
787         ap_table_set(r->headers_in,"Shib-Attributes", assertion.c_str());
788     }
789
790     // Export the SAML AuthnMethod and the origin site name, and possibly the NameIdentifier.
791     ap_table_unset(r->headers_in,"Shib-Origin-Site");
792     ap_table_unset(r->headers_in,"Shib-Authentication-Method");
793     ap_table_unset(r->headers_in,"Shib-NameIdentifier-Format");
794     auto_ptr_char os(sso_statement->getSubject()->getNameIdentifier()->getNameQualifier());
795     auto_ptr_char am(sso_statement->getAuthMethod());
796     ap_table_set(r->headers_in,"Shib-Origin-Site", os.get());
797     ap_table_set(r->headers_in,"Shib-Authentication-Method", am.get());
798     
799     // Export NameID?
800     AAP wrapper(provs,sso_statement->getSubject()->getNameIdentifier()->getFormat(),Constants::SHIB_ATTRIBUTE_NAMESPACE_URI);
801     if (!wrapper.fail() && wrapper->getHeader()) {
802         auto_ptr_char form(sso_statement->getSubject()->getNameIdentifier()->getFormat());
803         auto_ptr_char nameid(sso_statement->getSubject()->getNameIdentifier()->getName());
804         ap_table_set(r->headers_in,"Shib-NameIdentifier-Format",form.get());
805         if (!strcmp(wrapper->getHeader(),"REMOTE_USER"))
806             SH_AP_USER(r)=ap_pstrdup(r->pool,nameid.get());
807         else
808             ap_table_set(r->headers_in,wrapper->getHeader(),nameid.get());
809     }
810     
811     ap_table_unset(r->headers_in,"Shib-Application-ID");
812     ap_table_set(r->headers_in,"Shib-Application-ID",application_id.second);
813
814     // Export the attributes.
815     Iterator<SAMLAssertion*> a_iter(assertions);
816     while (a_iter.hasNext()) {
817         SAMLAssertion* assert=a_iter.next();
818         Iterator<SAMLStatement*> statements=assert->getStatements();
819         while (statements.hasNext()) {
820             SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());
821             if (!astate)
822                 continue;
823             Iterator<SAMLAttribute*> attrs=astate->getAttributes();
824             while (attrs.hasNext()) {
825                 SAMLAttribute* attr=attrs.next();
826         
827                 // Are we supposed to export it?
828                 AAP wrapper(provs,attr->getName(),attr->getNamespace());
829                 if (wrapper.fail() || !wrapper->getHeader())
830                     continue;
831                 
832                 Iterator<string> vals=attr->getSingleByteValues();
833                 if (!strcmp(wrapper->getHeader(),"REMOTE_USER") && vals.hasNext())
834                     SH_AP_USER(r)=ap_pstrdup(r->pool,vals.next().c_str());
835                 else {
836                     int it=0;
837                     char* header = (char*)ap_table_get(r->headers_in, wrapper->getHeader());
838                     if (header) {
839                         header=ap_pstrdup(r->pool, header);
840                         it++;
841                     }
842                     else
843                         header = ap_pstrdup(r->pool, "");
844                     for (; vals.hasNext(); it++) {
845                         string value = vals.next();
846                         for (string::size_type pos = value.find_first_of(";", string::size_type(0));
847                                 pos != string::npos;
848                                 pos = value.find_first_of(";", pos)) {
849                             value.insert(pos, "\\");
850                             pos += 2;
851                         }
852                         header=ap_pstrcat(r->pool, header, (it ? ";" : ""), value.c_str(), NULL);
853                     }
854                     ap_table_setn(r->headers_in, wrapper->getHeader(), header);
855                }
856             }
857         }
858     }
859
860     // clean up memory
861     for (int k = 0; k < assertions.size(); k++)
862         delete assertions[k];
863     delete sso_statement;
864
865     return OK;
866 }
867
868 extern "C" int shib_post_handler(request_rec* r)
869 {
870     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
871                 "shib_post_handler(%d): ENTER", (int)getpid());
872     shib_server_config* sc=(shib_server_config*)ap_get_module_config(r->server->module_config,&mod_shib);
873
874 #ifndef SHIB_APACHE_13
875     // With 2.x, this handler always runs, though last.
876     // We check if shib_check_user ran, because it will detect a SHIRE request
877     // and dispatch it directly.
878     void* data;
879     apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
880     if (data==(const void*)42) {
881         ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_post_handler skipped since check_user ran");
882         return DECLINED;
883     }
884 #endif
885     
886     ostringstream threadid;
887     threadid << "[" << getpid() << "] shib_post_handler" << '\0';
888     saml::NDC ndc(threadid.str().c_str());
889
890     // We lock the configuration system for the duration.
891     IConfig* conf=g_Config->getINI();
892     Locker locker(conf);
893     
894     // Map request to application and content settings.
895     IRequestMapper* mapper=conf->getRequestMapper();
896     Locker locker2(mapper);
897     IRequestMapper::Settings settings=mapper->getSettingsFromParsedURL(
898         (sc->szScheme ? sc->szScheme : ap_http_method(r)), ap_get_server_name(r), ap_get_server_port(r), r->unparsed_uri
899         );
900     pair<bool,const char*> application_id=settings.first->getString("applicationId");
901     const IApplication* application=conf->getApplication(application_id.second);
902     if (!application) {
903         ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
904            "shib_post_handler: unable to map request to application settings, check configuration");
905         return SERVER_ERROR;
906     }
907     
908     // Declare SHIRE object for this request.
909     SHIRE shire(application);
910     
911     return shib_handler(r, application, shire);
912 }
913
914 int shib_handler(request_rec* r, const IApplication* application, SHIRE& shire)
915 {
916     shib_server_config* sc=(shib_server_config*)ap_get_module_config(r->server->module_config,&mod_shib);
917
918     const char* targeturl=shib_get_targeturl(r,sc->szScheme);
919
920     const char* shireURL=shire.getShireURL(targeturl);
921     if (!shireURL) {
922         ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
923            "shib_post_handler: unable to map request to proper shireURL setting, check configuration");
924         return SERVER_ERROR;
925     }
926
927     // Make sure we only process the SHIRE requests.
928     if (!strstr(targeturl,shireURL))
929         return DECLINED;
930
931     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler() running");
932
933     const IPropertySet* sessionProps=application->getPropertySet("Sessions");
934     if (!sessionProps) {
935         ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
936            "shib_post_handler: unable to map request to application session settings, check configuration");
937         return SERVER_ERROR;
938     }
939
940     pair<const char*,const char*> shib_cookie=shire.getCookieNameProps();   // always returns something
941
942     ShibMLP markupProcessor;
943     markupProcessor.insert("requestURL", targeturl);
944
945     // Process SHIRE request
946     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() Beginning SHIRE processing");
947       
948     try {
949         pair<bool,bool> shireSSL=sessionProps->getBool("shireSSL");
950       
951         // Make sure this is SSL, if it should be
952         if ((!shireSSL.first || shireSSL.second) && strcmp(ap_http_method(r),"https"))
953             throw ShibTargetException(SHIBRPC_OK, "blocked non-SSL access to session creation service");
954
955         // If this is a GET, we manufacture an AuthnRequest.
956         if (!strcasecmp(r->method,"GET")) {
957             const char* areq=r->args ? shire.getLazyAuthnRequest(r->args) : NULL;
958             if (!areq)
959                 throw ShibTargetException(SHIBRPC_OK, "malformed arguments to request a new session");
960             ap_table_setn(r->headers_out, "Location", ap_pstrdup(r->pool,areq));
961             return REDIRECT;
962         }
963         else if (strcasecmp(r->method,"POST")) {
964             throw ShibTargetException(SHIBRPC_OK, "blocked non-POST to SHIRE POST processor");
965         }
966
967         // Sure sure this POST is an appropriate content type
968         const char *ct = ap_table_get(r->headers_in, "Content-type");
969         if (!ct || strcasecmp(ct, "application/x-www-form-urlencoded"))
970             throw ShibTargetException(SHIBRPC_OK,
971                                       ap_psprintf(r->pool, "blocked bad content-type to SHIRE POST processor: %s", (ct ? ct : "")));
972
973         // Read the posted data
974         if (ap_setup_client_block(r, REQUEST_CHUNKED_ERROR))
975             throw ShibTargetException(SHIBRPC_OK, "CGI setup_client_block failed");
976         if (!ap_should_client_block(r))
977             throw ShibTargetException(SHIBRPC_OK, "CGI should_client_block failed");
978         if (r->remaining > 1024*1024)
979             throw ShibTargetException (SHIBRPC_OK, "CGI length too long...");
980
981         string cgistr;
982         char buff[HUGE_STRING_LEN];
983         ap_hard_timeout("[mod_shib] CGI Parser", r);
984         memset(buff, 0, sizeof(buff));
985         while (ap_get_client_block(r, buff, sizeof(buff)-1) > 0) {
986             ap_reset_timeout(r);
987             cgistr += buff;
988             memset(buff, 0, sizeof(buff));
989         }
990         ap_kill_timeout(r);
991
992         // Parse the submission.
993         pair<const char*,const char*> elements=shire.getFormSubmission(cgistr.c_str(),cgistr.length());
994     
995         // Make sure the SAML Response parameter exists
996         if (!elements.first || !*elements.first)
997             throw ShibTargetException(SHIBRPC_OK, "SHIRE POST failed to find SAMLResponse form element");
998     
999         // Make sure the target parameter exists
1000         if (!elements.second || !*elements.second)
1001             throw ShibTargetException(SHIBRPC_OK, "SHIRE POST failed to find TARGET form element");
1002     
1003         ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1004             "shib_handler() Processing POST for target: %s", elements.second);
1005
1006         // process the post
1007         string cookie;
1008         RPCError* status = shire.sessionCreate(elements.first, r->connection->remote_ip, cookie);
1009
1010         if (status->isError()) {
1011             ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
1012                     "shib_handler() POST process failed (%d): %s", status->getCode(), status->getText());
1013
1014             if (status->isRetryable()) {
1015                 delete status;
1016                 ap_log_rerror(APLOG_MARK,APLOG_INFO|APLOG_NOERRNO,SH_AP_R(r),
1017                         "shib_handler() retryable error, generating new AuthnRequest");
1018                 ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(elements.second)));
1019                 return REDIRECT;
1020             }
1021
1022             // return this error to the user.
1023             markupProcessor.insert(*status);
1024             delete status;
1025             return shib_error_page(r, application, "shire", markupProcessor);
1026         }
1027         delete status;
1028
1029         ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1030                   "shib_handler() POST process succeeded.  New session: %s", cookie.c_str());
1031
1032         // We've got a good session, set the cookie...
1033         char* val = ap_psprintf(r->pool,"%s=%s%s",shib_cookie.first,cookie.c_str(),shib_cookie.second);
1034         ap_table_setn(r->err_headers_out, "Set-Cookie", val);
1035         ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() setting cookie: %s", val);
1036
1037         // ... and redirect to the target
1038         ap_table_setn(r->headers_out, "Location", ap_pstrdup(r->pool,elements.second));
1039         return REDIRECT;
1040     }
1041     catch (ShibTargetException &e) {
1042         ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() caught exception: %s", e.what());
1043         markupProcessor.insert("errorType", "Session Creation Service Error");
1044         markupProcessor.insert("errorText", e.what());
1045         markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
1046         return shib_error_page(r, application, "shire", markupProcessor);
1047     }
1048 #ifndef _DEBUG
1049     catch (...) {
1050         ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler(): unexpected exception");
1051         markupProcessor.insert("errorType", "Session Creation Service Error");
1052         markupProcessor.insert("errorText", "Unknown Exception");
1053         markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
1054         return shib_error_page(r, application, "shire", markupProcessor);
1055     }
1056 #endif
1057
1058     ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_handler() server error");
1059     return SERVER_ERROR;
1060 }
1061
1062 static int shib_error_page(request_rec* r, const IApplication* app, const char* page, ShibMLP& mlp)
1063 {
1064     const IPropertySet* props=app->getPropertySet("Errors");
1065     if (props) {
1066         pair<bool,const char*> p=props->getString(page);
1067         if (p.first) {
1068             ifstream infile(p.second);
1069             if (!infile.fail()) {
1070                 const char* res = mlp.run(infile,props);
1071                 if (res) {
1072                     r->content_type = ap_psprintf(r->pool, "text/html");
1073                     ap_send_http_header(r);
1074                     ap_rprintf(r, res);
1075                     return DONE;
1076                 }
1077             }
1078         }
1079     }
1080
1081     ap_log_rerror(APLOG_MARK,APLOG_ERR,SH_AP_R(r),
1082         "shib_error_page() could not process shire error template for application %s",app->getId());
1083     return SERVER_ERROR;
1084 }
1085
1086 /*
1087  * shib_auth_checker() -- a simple resource manager to
1088  * process the .htaccess settings and copy attributes
1089  * into the HTTP headers.
1090  */
1091 extern "C" int shib_auth_checker(request_rec* r)
1092 {
1093     shib_dir_config* dc=
1094         (shib_dir_config*)ap_get_module_config(r->per_dir_config,&mod_shib);
1095
1096     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() executing");
1097
1098     // Regular access to arbitrary resource...check AuthType
1099     const char* auth_type=ap_auth_type(r);
1100     if (!auth_type || strcasecmp(auth_type,"shibboleth"))
1101         return DECLINED;
1102
1103     ostringstream threadid;
1104     threadid << "[" << getpid() << "] shibrm" << '\0';
1105     saml::NDC ndc(threadid.str().c_str());
1106
1107     // We lock the configuration system for the duration.
1108     IConfig* conf=g_Config->getINI();
1109     Locker locker(conf);
1110     
1111     const char* application_id=ap_table_get(r->headers_in,"Shib-Application-ID");
1112     const IApplication* application=NULL;
1113     if (application_id)
1114         application = conf->getApplication(application_id);
1115
1116     // mod_auth clone
1117
1118     int m=r->method_number;
1119     bool method_restricted=false;
1120     const char *t, *w;
1121     
1122     const array_header* reqs_arr=ap_requires(r);
1123     if (!reqs_arr)
1124         return OK;
1125
1126     require_line* reqs=(require_line*)reqs_arr->elts;
1127
1128     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"REQUIRE nelts: %d", reqs_arr->nelts);
1129     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"REQUIRE all: %d", dc->bRequireAll);
1130
1131     vector<bool> auth_OK(reqs_arr->nelts,false);
1132
1133 #define SHIB_AP_CHECK_IS_OK {       \
1134      if (dc->bRequireAll < 1)    \
1135          return OK;      \
1136      auth_OK[x] = true;      \
1137      continue;           \
1138 }
1139
1140     for (int x=0; x<reqs_arr->nelts; x++) {
1141         auth_OK[x] = false;
1142         if (!(reqs[x].method_mask & (1 << m)))
1143             continue;
1144         method_restricted=true;
1145
1146         t = reqs[x].requirement;
1147         w = ap_getword_white(r->pool, &t);
1148
1149         if (!strcasecmp(w,"Shibboleth")) {
1150             // This is a dummy rule needed because Apache conflates authn and authz.
1151             // Without some require rule, AuthType is ignored and no check_user hooks run.
1152             SHIB_AP_CHECK_IS_OK;
1153         }
1154         else if (!strcmp(w,"valid-user") && application_id) {
1155             ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting valid-user");
1156             SHIB_AP_CHECK_IS_OK;
1157         }
1158         else if (!strcmp(w,"user") && SH_AP_USER(r)) {
1159             bool regexp=false;
1160             while (*t) {
1161                 w=ap_getword_conf(r->pool,&t);
1162                 if (*w=='~') {
1163                     regexp=true;
1164                     continue;
1165                 }
1166                 
1167                 if (regexp) {
1168                     try {
1169                         // To do regex matching, we have to convert from UTF-8.
1170                         auto_ptr<XMLCh> trans(fromUTF8(w));
1171                         RegularExpression re(trans.get());
1172                         auto_ptr<XMLCh> trans2(fromUTF8(SH_AP_USER(r)));
1173                         if (re.matches(trans2.get())) {
1174                             ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting user: %s",w);
1175                             SHIB_AP_CHECK_IS_OK;
1176                         }
1177                     }
1178                     catch (XMLException& ex) {
1179                         auto_ptr_char tmp(ex.getMessage());
1180                         ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
1181                                         "shib_auth_checker caught exception while parsing regular expression (%s): %s",w,tmp.get());
1182                     }
1183                 }
1184                 else if (!strcmp(SH_AP_USER(r),w)) {
1185                     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting user: %s",w);
1186                     SHIB_AP_CHECK_IS_OK;
1187                 }
1188             }
1189         }
1190         else if (!strcmp(w,"group")) {
1191             SH_AP_TABLE* grpstatus=NULL;
1192             if (dc->szAuthGrpFile && SH_AP_USER(r)) {
1193                 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() using groups file: %s\n",dc->szAuthGrpFile);
1194                 grpstatus=groups_for_user(r,SH_AP_USER(r),dc->szAuthGrpFile);
1195             }
1196             if (!grpstatus)
1197                 return DECLINED;
1198     
1199             while (*t) {
1200                 w=ap_getword_conf(r->pool,&t);
1201                 if (ap_table_get(grpstatus,w)) {
1202                     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting group: %s",w);
1203                     SHIB_AP_CHECK_IS_OK;
1204                 }
1205             }
1206         }
1207         else {
1208             Iterator<IAAP*> provs=application ? application->getAAPProviders() : EMPTY(IAAP*);
1209             AAP wrapper(provs,w);
1210             if (wrapper.fail()) {
1211                 ap_log_rerror(APLOG_MARK,APLOG_WARNING|APLOG_NOERRNO,SH_AP_R(r),
1212                     "shib_auth_checker() didn't recognize require rule: %s\n",w);
1213                 continue;
1214             }
1215
1216             bool regexp=false;
1217             const char* vals=ap_table_get(r->headers_in,wrapper->getHeader());
1218             while (*t && vals) {
1219                 w=ap_getword_conf(r->pool,&t);
1220                 if (*w=='~') {
1221                     regexp=true;
1222                     continue;
1223                 }
1224
1225                 try {
1226                     auto_ptr<RegularExpression> re;
1227                     if (regexp) {
1228                         delete re.release();
1229                         auto_ptr<XMLCh> trans(fromUTF8(w));
1230                         auto_ptr<RegularExpression> temp(new RegularExpression(trans.get()));
1231                         re=temp;
1232                     }
1233                     
1234                     string vals_str(vals);
1235                     int j = 0;
1236                     for (int i = 0;  i < vals_str.length();  i++) {
1237                         if (vals_str.at(i) == ';') {
1238                             if (i == 0) {
1239                                 ap_log_rerror(APLOG_MARK,APLOG_WARNING|APLOG_NOERRNO,SH_AP_R(r),
1240                                                 "shib_auth_checker() invalid header encoding %s: starts with semicolon", vals);
1241                                 return SERVER_ERROR;
1242                             }
1243
1244                             if (vals_str.at(i-1) == '\\') {
1245                                 vals_str.erase(i-1, 1);
1246                                 i--;
1247                                 continue;
1248                             }
1249
1250                             string val = vals_str.substr(j, i-j);
1251                             j = i+1;
1252                             if (regexp) {
1253                                 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
1254                                 if (re->matches(trans.get())) {
1255                                     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1256                                                     "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
1257                                     SHIB_AP_CHECK_IS_OK;
1258                                 }
1259                             }
1260                             else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
1261                                 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1262                                                 "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
1263                                 SHIB_AP_CHECK_IS_OK;
1264                             }
1265                             else {
1266                                 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1267                                                 "shib_auth_checker() expecting %s, got %s: authorization not granted", w, val.c_str());
1268                             }
1269                         }
1270                     }
1271     
1272                     string val = vals_str.substr(j, vals_str.length()-j);
1273                     if (regexp) {
1274                         auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
1275                         if (re->matches(trans.get())) {
1276                             ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1277                                             "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
1278                             SHIB_AP_CHECK_IS_OK;
1279                         }
1280                     }
1281                     else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
1282                         ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1283                                         "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
1284                         SHIB_AP_CHECK_IS_OK;
1285                     }
1286                     else {
1287                         ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
1288                                         "shib_auth_checker() expecting %s, got %s: authorization not granted", w, val.c_str());
1289                     }
1290                 }
1291                 catch (XMLException& ex) {
1292                     auto_ptr_char tmp(ex.getMessage());
1293                     ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
1294                                     "shib_auth_checker caught exception while parsing regular expression (%s): %s",w,tmp.get());
1295                 }
1296             }
1297         }
1298     }
1299
1300     // check if all require directives are true
1301     bool auth_all_OK = true;
1302     for (int i= 0; i<reqs_arr->nelts; i++) {
1303         auth_all_OK &= auth_OK[i];
1304     }
1305     if (auth_all_OK)
1306         return OK;
1307
1308     if (!method_restricted)
1309         return OK;
1310
1311     if (!application_id) {
1312         ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
1313            "shib_auth_checker: Shib-Application-ID header not found in request");
1314         return HTTP_FORBIDDEN;
1315     }
1316     else if (!application) {
1317         ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
1318            "shib_auth_checker: unable to map request to application settings, check configuration");
1319         return HTTP_FORBIDDEN;
1320     }
1321
1322     ShibMLP markupProcessor;
1323     markupProcessor.insert("requestURL", ap_construct_url(r->pool,r->unparsed_uri,r));
1324     return shib_error_page(r, application, "access", markupProcessor);
1325 }
1326 #endif /* 0 */
1327
1328 #ifndef SHIB_APACHE_13
1329 /*
1330  * shib_exit()
1331  *  Empty cleanup hook, Apache 2.x doesn't check NULL very well...
1332  */
1333 extern "C" apr_status_t shib_exit(void* data)
1334 {
1335     ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,0,NULL,"shib_exit() done\n");
1336     return OK;
1337 }
1338 #endif
1339
1340
1341 /*
1342  * shib_child_exit()
1343  *  Cleanup the (per-process) pool info.
1344  */
1345 #ifdef SHIB_APACHE_13
1346 extern "C" void shib_child_exit(server_rec* s, SH_AP_POOL* p)
1347 {
1348 #else
1349 extern "C" apr_status_t shib_child_exit(void* data)
1350 {
1351   server_rec* s = NULL;
1352 #endif
1353
1354     ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit(%d) dealing with g_Config..", (int)getpid());
1355     g_Config->shutdown();
1356     g_Config = NULL;
1357     ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit() done\n");
1358
1359 #ifndef SHIB_APACHE_13
1360     return OK;
1361 #endif
1362 }
1363
1364 /* 
1365  * shire_child_init()
1366  *  Things to do when the child process is initialized.
1367  *  (or after the configs are read in apache-2)
1368  */
1369 #ifdef SHIB_APACHE_13
1370 extern "C" void shib_child_init(server_rec* s, SH_AP_POOL* p)
1371 #else
1372 extern "C" void shib_child_init(apr_pool_t* p, server_rec* s)
1373 #endif
1374 {
1375     // Initialize runtime components.
1376
1377     ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init(%d) starting", (int)getpid());
1378
1379     if (g_Config) {
1380         ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() already initialized!");
1381         exit(1);
1382     }
1383
1384     try {
1385         g_Config=&ShibTargetConfig::getConfig();
1386         g_Config->setFeatures(
1387             ShibTargetConfig::Listener |
1388             ShibTargetConfig::Metadata |
1389             ShibTargetConfig::AAP |
1390             ShibTargetConfig::RequestMapper |
1391             ShibTargetConfig::SHIREExtensions |
1392             ShibTargetConfig::Logging
1393             );
1394         if (!g_Config->init(g_szSchemaDir,g_szSHIBConfig)) {
1395             ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize SHIB Target");
1396             exit(1);
1397         }
1398     }
1399     catch (...) {
1400         ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize SHIB Target");
1401         exit (1);
1402     }
1403
1404     // Set the cleanup handler
1405     apr_pool_cleanup_register(p, NULL, &shib_exit, &shib_child_exit);
1406
1407     ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() done");
1408 }
1409
1410 typedef const char* (*config_fn_t)(void);
1411
1412 #ifdef SHIB_APACHE_13
1413
1414 // SHIB Module commands
1415
1416 static command_rec shire_cmds[] = {
1417   {"SHIREConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1418    RSRC_CONF, TAKE1, "Path to shibboleth.xml config file."},
1419   {"ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1420    RSRC_CONF, TAKE1, "Path to shibboleth.xml config file."},
1421   {"ShibSchemaDir", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1422    RSRC_CONF, TAKE1, "Path to Shibboleth XML schema directory."},
1423
1424   {"ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
1425    (void *) XtOffsetOf (shib_server_config, szScheme),
1426    RSRC_CONF, TAKE1, "URL scheme to force into generated URLs for a vhost."},
1427    
1428   {"ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1429    (void *) XtOffsetOf (shib_dir_config, bBasicHijack),
1430    OR_AUTHCFG, FLAG, "Respond to AuthType Basic and convert to shib?"},
1431   {"ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1432    (void *) XtOffsetOf (shib_dir_config, bRequireSession),
1433    OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist."},
1434   {"ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1435    (void *) XtOffsetOf (shib_dir_config, bExportAssertion),
1436    OR_AUTHCFG, FLAG, "Export SAML assertion to Shibboleth-defined header?"},
1437   {"AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
1438    (void *) XtOffsetOf (shib_dir_config, szAuthGrpFile),
1439    OR_AUTHCFG, TAKE1, "text file containing group names and member user IDs"},
1440   {"ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1441    (void *) XtOffsetOf (shib_dir_config, bRequireAll),
1442    OR_AUTHCFG, FLAG, "All require directives must match!"},
1443
1444   {NULL}
1445 };
1446
1447 extern "C"{
1448 handler_rec shib_handlers[] = {
1449   { "shib-shire-post", shib_post_handler },
1450   { NULL }
1451 };
1452
1453 module MODULE_VAR_EXPORT mod_shib = {
1454     STANDARD_MODULE_STUFF,
1455     NULL,                        /* initializer */
1456     create_shib_dir_config,     /* dir config creater */
1457     merge_shib_dir_config,      /* dir merger --- default is to override */
1458     create_shib_server_config, /* server config */
1459     merge_shib_server_config,   /* merge server config */
1460     shire_cmds,                 /* command table */
1461     shib_handlers,              /* handlers */
1462     NULL,                       /* filename translation */
1463     shib_check_user,            /* check_user_id */
1464     shib_auth_checker,          /* check auth */
1465     NULL,                       /* check access */
1466     NULL,                       /* type_checker */
1467     NULL,                       /* fixups */
1468     NULL,                       /* logger */
1469     NULL,                       /* header parser */
1470     shib_child_init,            /* child_init */
1471     shib_child_exit,            /* child_exit */
1472     NULL                        /* post read-request */
1473 };
1474
1475 #elif defined(SHIB_APACHE_20)
1476
1477 extern "C" void shib_register_hooks (apr_pool_t *p)
1478 {
1479   ap_hook_child_init(shib_child_init, NULL, NULL, APR_HOOK_MIDDLE);
1480   ap_hook_check_user_id(shib_check_user, NULL, NULL, APR_HOOK_MIDDLE);
1481   ap_hook_auth_checker(shib_auth_checker, NULL, NULL, APR_HOOK_FIRST);
1482   ap_hook_handler(shib_post_handler, NULL, NULL, APR_HOOK_LAST);
1483 }
1484
1485 // SHIB Module commands
1486
1487 extern "C" {
1488 static command_rec shib_cmds[] = {
1489   AP_INIT_TAKE1("ShibConfig",
1490                 (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1491                 RSRC_CONF, "Path to shibboleth.xml config file."),
1492   AP_INIT_TAKE1("ShibSchemaDir",
1493      (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1494       RSRC_CONF, "Path to Shibboleth XML schema directory."),
1495
1496   AP_INIT_TAKE1("ShibURLScheme",
1497      (config_fn_t)shib_set_server_string_slot,
1498      (void *) offsetof (shib_server_config, szScheme),
1499       RSRC_CONF, "URL scheme to force into generated URLs for a vhost."),
1500
1501   AP_INIT_FLAG("ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1502                (void *) offsetof (shib_dir_config, bBasicHijack),
1503                OR_AUTHCFG, "Respond to AuthType Basic and convert to shib?"),
1504   AP_INIT_FLAG("ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1505          (void *) offsetof (shib_dir_config, bRequireSession),
1506         OR_AUTHCFG, "Initiates a new session if one does not exist."),
1507   AP_INIT_FLAG("ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1508          (void *) offsetof (shib_dir_config, bExportAssertion),
1509         OR_AUTHCFG, "Export SAML assertion to Shibboleth-defined header?"),
1510   AP_INIT_TAKE1("AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
1511                 (void *) offsetof (shib_dir_config, szAuthGrpFile),
1512                 OR_AUTHCFG, "text file containing group names and member user IDs"),
1513   AP_INIT_FLAG("ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1514                (void *) offsetof (shib_dir_config, bRequireAll),
1515                OR_AUTHCFG, "All require directives must match!"),
1516
1517   {NULL}
1518 };
1519
1520 module AP_MODULE_DECLARE_DATA mod_shib = {
1521     STANDARD20_MODULE_STUFF,
1522     create_shib_dir_config,     /* create dir config */
1523     merge_shib_dir_config,      /* merge dir config --- default is to override */
1524     create_shib_server_config,  /* create server config */
1525     merge_shib_server_config,   /* merge server config */
1526     shib_cmds,                  /* command table */
1527     shib_register_hooks         /* register hooks */
1528 };
1529
1530 #else
1531 #error "undefined APACHE version"
1532 #endif
1533
1534 }