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