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