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