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