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