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