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