/*
+ * Copyright 2001-2007 Internet2
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/*
* mod_apache.cpp -- the core Apache Module code
*
* Created by: Derek Atkins <derek@ihtfp.com>
* $Id$
*/
+#define SHIBSP_LITE
+
#ifdef SOLARIS2
#undef _XOPEN_SOURCE // causes gethostname conflict in unistd.h
#endif
-// SAML Runtime
-#include <saml/saml.h>
-#include <shib/shib.h>
-#include <shib/shib-threads.h>
-#include <shib-target/shib-target.h>
+#ifdef WIN32
+# define _CRT_NONSTDC_NO_DEPRECATE 1
+# define _CRT_SECURE_NO_DEPRECATE 1
+#endif
+
+#include <shibsp/AbstractSPRequest.h>
+#include <shibsp/AccessControl.h>
+#include <shibsp/exceptions.h>
+#include <shibsp/RequestMapper.h>
+#include <shibsp/SPConfig.h>
+#include <shibsp/ServiceProvider.h>
+#include <shibsp/SessionCache.h>
+#include <shibsp/attribute/Attribute.h>
+
#include <xercesc/util/regx/RegularExpression.hpp>
+#include <xmltooling/XMLToolingConfig.h>
+#include <xmltooling/util/NDC.h>
+#include <xmltooling/util/Threads.h>
+#include <xmltooling/util/XMLConstants.h>
+#include <xmltooling/util/XMLHelper.h>
+
+#ifdef WIN32
+# include <winsock.h>
+#endif
#undef _XPG4_2
#include <unistd.h> // for getpid()
#endif
+using namespace shibsp;
+using namespace xmltooling;
using namespace std;
-using namespace saml;
-using namespace shibboleth;
-using namespace shibtarget;
+using xercesc::RegularExpression;
+using xercesc::XMLException;
extern "C" module MODULE_VAR_EXPORT mod_shib;
-#if 0
-int shib_handler(request_rec* r, const IApplication* application, SHIRE& shire);
-#endif
namespace {
- char* g_szSHIBConfig = NULL;
- char* g_szSchemaDir = NULL;
- ShibTargetConfig* g_Config = NULL;
+ char* g_szSHIBConfig = SHIBSP_CONFIG;
+ char* g_szSchemaDir = SHIBSP_SCHEMAS;
+ SPConfig* g_Config = NULL;
+ string g_unsetHeaderValue;
static const char* g_UserDataKey = "_shib_check_user_";
+ static const XMLCh path[] = UNICODE_LITERAL_4(p,a,t,h);
+ static const XMLCh validate[] = UNICODE_LITERAL_8(v,a,l,i,d,a,t,e);
}
+/* Apache 2.2.x headers must be accumulated and set in the output filter.
+ Apache 2.0.49+ supports the filter method.
+ Apache 1.3.x and lesser 2.0.x must write the headers directly. */
+
+#if (defined(SHIB_APACHE_20) || defined(SHIB_APACHE_22)) && AP_MODULE_MAGIC_AT_LEAST(20020903,6)
+#define SHIB_DEFERRED_HEADERS
+#endif
+
/********************************************************************************/
// Basic Apache Configuration code.
//
char* szAuthGrpFile; // Auth GroupFile name
int bRequireAll; // all require directives must match, otherwise OR logic
- // SHIRE Configuration
+ // Content Configuration
+ char* szApplicationId; // Shib applicationId value
+ char* szRequireWith; // require a session using a specific initiator?
+ char* szRedirectToSSL; // redirect non-SSL requests to SSL port
+ int bOff; // flat-out disable all Shib processing
int bBasicHijack; // activate for AuthType Basic?
int bRequireSession; // require a session?
int bExportAssertion; // export SAML assertion to the environment?
+ int bUseEnvVars; // use environment instead of headers?
};
// creates per-directory config structure
extern "C" void* create_shib_dir_config (SH_AP_POOL* p, char* d)
{
shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
+ dc->bOff = -1;
dc->bBasicHijack = -1;
dc->bRequireSession = -1;
dc->bExportAssertion = -1;
dc->bRequireAll = -1;
+ dc->szRedirectToSSL = NULL;
dc->szAuthGrpFile = NULL;
+ dc->szApplicationId = NULL;
+ dc->szRequireWith = NULL;
+ dc->bUseEnvVars = -1;
return dc;
}
else
dc->szAuthGrpFile=NULL;
+ if (child->szApplicationId)
+ dc->szApplicationId=ap_pstrdup(p,child->szApplicationId);
+ else if (parent->szApplicationId)
+ dc->szApplicationId=ap_pstrdup(p,parent->szApplicationId);
+ else
+ dc->szApplicationId=NULL;
+
+ if (child->szRequireWith)
+ dc->szRequireWith=ap_pstrdup(p,child->szRequireWith);
+ else if (parent->szRequireWith)
+ dc->szRequireWith=ap_pstrdup(p,parent->szRequireWith);
+ else
+ dc->szRequireWith=NULL;
+
+ if (child->szRedirectToSSL)
+ dc->szRedirectToSSL=ap_pstrdup(p,child->szRedirectToSSL);
+ else if (parent->szRedirectToSSL)
+ dc->szRedirectToSSL=ap_pstrdup(p,parent->szRedirectToSSL);
+ else
+ dc->szRedirectToSSL=NULL;
+
+ dc->bOff=((child->bOff==-1) ? parent->bOff : child->bOff);
dc->bBasicHijack=((child->bBasicHijack==-1) ? parent->bBasicHijack : child->bBasicHijack);
dc->bRequireSession=((child->bRequireSession==-1) ? parent->bRequireSession : child->bRequireSession);
dc->bExportAssertion=((child->bExportAssertion==-1) ? parent->bExportAssertion : child->bExportAssertion);
dc->bRequireAll=((child->bRequireAll==-1) ? parent->bRequireAll : child->bRequireAll);
+ dc->bUseEnvVars=((child->bUseEnvVars==-1) ? parent->bUseEnvVars : child->bUseEnvVars);
return dc;
}
+// per-request module structure
+struct shib_request_config
+{
+ SH_AP_TABLE *env; // environment vars
+#ifdef SHIB_DEFERRED_HEADERS
+ SH_AP_TABLE *hdr_out; // headers to browser
+ SH_AP_TABLE *hdr_err; // err headers to browser
+#endif
+};
+
+// create a request record
+static shib_request_config *init_request_config(request_rec *r)
+{
+ shib_request_config* rc=(shib_request_config*)ap_pcalloc(r->pool,sizeof(shib_request_config));
+ ap_set_module_config (r->request_config, &mod_shib, rc);
+ memset(rc, 0, sizeof(shib_request_config));
+ ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_init_rc");
+ return rc;
+}
+
// generic global slot handlers
extern "C" const char* ap_set_global_string_slot(cmd_parms* parms, void*, const char* arg)
{
extern "C" const char* shib_set_server_string_slot(cmd_parms* parms, void*, const char* arg)
{
char* base=(char*)ap_get_module_config(parms->server->module_config,&mod_shib);
- int offset=(int)parms->info;
+ size_t offset=(size_t)parms->info;
*((char**)(base + offset))=ap_pstrdup(parms->pool,arg);
return NULL;
}
}
/********************************************************************************/
-// Some other useful helper function(s)
-
-static SH_AP_TABLE* groups_for_user(request_rec* r, const char* user, char* grpfile)
-{
- SH_AP_CONFIGFILE* f;
- SH_AP_TABLE* grps=ap_make_table(r->pool,15);
- char l[MAX_STRING_LEN];
- const char *group_name, *ll, *w;
-
-#ifdef SHIB_APACHE_13
- if (!(f=ap_pcfg_openfile(r->pool,grpfile))) {
-#else
- if (ap_pcfg_openfile(&f,r->pool,grpfile) != APR_SUCCESS) {
-#endif
- ap_log_rerror(APLOG_MARK,APLOG_DEBUG,SH_AP_R(r),"groups_for_user() could not open group file: %s\n",grpfile);
- return NULL;
- }
-
- SH_AP_POOL* sp;
-#ifdef SHIB_APACHE_13
- sp=ap_make_sub_pool(r->pool);
-#else
- if (apr_pool_create(&sp,r->pool) != APR_SUCCESS) {
- ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,
- "groups_for_user() could not create a subpool");
- return NULL;
- }
-#endif
-
- while (!(ap_cfg_getline(l,MAX_STRING_LEN,f))) {
- if ((*l=='#') || (!*l))
- continue;
- ll = l;
- ap_clear_pool(sp);
-
- group_name=ap_getword(sp,&ll,':');
-
- while (*ll) {
- w=ap_getword_conf(sp,&ll);
- if (!strcmp(w,user)) {
- ap_table_setn(grps,ap_pstrdup(r->pool,group_name),"in");
- break;
- }
- }
- }
- ap_cfg_closefile(f);
- ap_destroy_pool(sp);
- return grps;
-}
-
-/********************************************************************************/
// Apache ShibTarget subclass(es) here.
-class HTGroupTableApache : public HTGroupTable
+class ShibTargetApache : public AbstractSPRequest
{
-public:
- HTGroupTableApache(request_rec* r, const char *user, char *grpfile) {
- groups = groups_for_user(r, user, grpfile);
- if (!groups)
- throw ResourceAccessException("Unable to access group file ($1) for user ($2)",params(2,grpfile,user));
- }
- ~HTGroupTableApache() {}
- bool lookup(const char *entry) { return (ap_table_get(groups, entry)!=NULL); }
- SH_AP_TABLE* groups;
-};
+ mutable string m_body;
+ mutable bool m_gotBody;
+ vector<string> m_certs;
-class ShibTargetApache : public ShibTarget
-{
public:
- ShibTargetApache(request_rec* req) {
- m_sc = (shib_server_config*)
- ap_get_module_config(req->server->module_config, &mod_shib);
+ request_rec* m_req;
+ shib_dir_config* m_dc;
+ shib_server_config* m_sc;
+ shib_request_config* m_rc;
+ ShibTargetApache(request_rec* req) : m_gotBody(false) {
+ m_sc = (shib_server_config*)ap_get_module_config(req->server->module_config, &mod_shib);
m_dc = (shib_dir_config*)ap_get_module_config(req->per_dir_config, &mod_shib);
-
- const char* ct = ap_table_get(req->headers_in, "Content-type");
-
- init(g_Config, string(m_sc->szScheme ? m_sc->szScheme : ap_http_method(req)),
- string(ap_get_server_name(req)), (int)ap_get_server_port(req),
- string(req->unparsed_uri), string(ct ? ct : ""),
- string(req->connection->remote_ip), string(req->method));
-
+ m_rc = (shib_request_config*)ap_get_module_config(req->request_config, &mod_shib);
m_req = req;
}
- ~ShibTargetApache() { }
-
- virtual void log(ShibLogLevel level, const string &msg) {
- ap_log_rerror(APLOG_MARK,
- (level == LogLevelDebug ? APLOG_DEBUG :
- (level == LogLevelInfo ? APLOG_INFO :
- (level == LogLevelWarn ? APLOG_WARNING :
- APLOG_ERR)))|APLOG_NOERRNO, SH_AP_R(m_req),
- msg.c_str());
+ virtual ~ShibTargetApache() {}
+
+ const char* getScheme() const {
+ return m_sc->szScheme ? m_sc->szScheme : ap_http_method(m_req);
+ }
+ const char* getHostname() const {
+ return ap_get_server_name(m_req);
+ }
+ int getPort() const {
+ return ap_get_server_port(m_req);
+ }
+ const char* getRequestURI() const {
+ return m_req->unparsed_uri;
+ }
+ const char* getMethod() const {
+ return m_req->method;
}
- virtual string getCookies(void) {
- const char *c = ap_table_get(m_req->headers_in, "Cookie");
- return string(c ? c : "");
+ string getContentType() const {
+ const char* type = ap_table_get(m_req->headers_in, "Content-Type");
+ return type ? type : "";
}
- virtual void setCookie(const string &name, const string &value) {
- char* val = ap_psprintf(m_req->pool, "%s=%s", name.c_str(), value.c_str());
- ap_table_setn(m_req->err_headers_out, "Set-Cookie", val);
+ long getContentLength() const {
+ return m_gotBody ? m_body.length() : m_req->remaining;
}
- virtual string getArgs(void) { return string(m_req->args ? m_req->args : ""); }
- virtual string getPostData(void) {
+ string getRemoteAddr() const {
+ return m_req->connection->remote_ip;
+ }
+ void log(SPLogLevel level, const string& msg) const {
+ AbstractSPRequest::log(level,msg);
+ ap_log_rerror(
+ APLOG_MARK,
+ (level == SPDebug ? APLOG_DEBUG :
+ (level == SPInfo ? APLOG_INFO :
+ (level == SPWarn ? APLOG_WARNING :
+ (level == SPError ? APLOG_ERR : APLOG_CRIT))))|APLOG_NOERRNO,
+ SH_AP_R(m_req),
+ msg.c_str()
+ );
+ }
+ const char* getQueryString() const { return m_req->args; }
+ const char* getRequestBody() const {
+ if (m_gotBody || m_req->method_number==M_GET)
+ return m_body.c_str();
// Read the posted data
- if (ap_setup_client_block(m_req, REQUEST_CHUNKED_ERROR))
- throw FatalProfileException("Apache function (setup_client_block) failed while reading profile submission.");
- if (!ap_should_client_block(m_req))
- throw FatalProfileException("Apache function (should_client_block) failed while reading profile submission.");
+ if (ap_setup_client_block(m_req, REQUEST_CHUNKED_DECHUNK) != OK) {
+ m_gotBody=true;
+ log(SPError, "Apache function (setup_client_block) failed while reading request body.");
+ return m_body.c_str();
+ }
+ if (!ap_should_client_block(m_req)) {
+ m_gotBody=true;
+ log(SPError, "Apache function (should_client_block) failed while reading request body.");
+ return m_body.c_str();
+ }
if (m_req->remaining > 1024*1024)
- throw FatalProfileException("Blocked too-large a submission to profile endpoint.");
- string cgistr;
+ throw opensaml::SecurityPolicyException("Blocked request body larger than 1M size limit.");
+ m_gotBody=true;
char buff[HUGE_STRING_LEN];
- ap_hard_timeout("[mod_shib] getPostData", m_req);
+ ap_hard_timeout("[mod_shib] getRequestBody", m_req);
memset(buff, 0, sizeof(buff));
while (ap_get_client_block(m_req, buff, sizeof(buff)-1) > 0) {
ap_reset_timeout(m_req);
- cgistr += buff;
+ m_body += buff;
memset(buff, 0, sizeof(buff));
}
ap_kill_timeout(m_req);
-
- return cgistr;
+ return m_body.c_str();
}
- virtual void clearHeader(const string &name) {
- ap_table_unset(m_req->headers_in, name.c_str());
+ void clearHeader(const char* name) {
+ if (m_dc->bUseEnvVars!=0) {
+ // ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_clear_header: env\n");
+ if (m_rc && m_rc->env) ap_table_unset(m_rc->env, name);
+ } else {
+ // ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_clear_header: hdr\n");
+ ap_table_unset(m_req->headers_in, name);
+ ap_table_set(m_req->headers_in, name, g_unsetHeaderValue.c_str());
+ }
}
- virtual void setHeader(const string &name, const string &value) {
- ap_table_set(m_req->headers_in, name.c_str(), value.c_str());
+ void setHeader(const char* name, const char* value) {
+ if (m_dc->bUseEnvVars!=0) {
+ if (!m_rc) {
+ // this happens on subrequests
+ // ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_setheader: no_m_rc\n");
+ m_rc = init_request_config(m_req);
+ }
+ if (!m_rc->env) m_rc->env = ap_make_table(m_req->pool, 10);
+ // ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_set_env: %s=%s\n", name, value?value:"Null");
+ ap_table_set(m_rc->env, name, value?value:"");
+ }
+ else {
+ ap_table_set(m_req->headers_in, name, value);
+ }
}
- virtual string getHeader(const string &name) {
- const char *hdr = ap_table_get(m_req->headers_in, name.c_str());
+ string getHeader(const char* name) const {
+ const char* hdr = ap_table_get(m_req->headers_in, name);
return string(hdr ? hdr : "");
}
- virtual void setRemoteUser(const string &user) {
- SH_AP_USER(m_req) = ap_pstrdup(m_req->pool, user.c_str());
+ string getSecureHeader(const char* name) const {
+ if (m_dc->bUseEnvVars!=0) {
+ const char *hdr;
+ if (m_rc && m_rc->env)
+ hdr = ap_table_get(m_rc->env, name);
+ else
+ hdr = NULL;
+ return string(hdr ? hdr : "");
+ }
+ return getHeader(name);
}
- virtual string getRemoteUser(void) {
+ void setRemoteUser(const char* user) {
+ SH_AP_USER(m_req) = user ? ap_pstrdup(m_req->pool, user) : NULL;
+ }
+ string getRemoteUser() const {
return string(SH_AP_USER(m_req) ? SH_AP_USER(m_req) : "");
}
- // override so we can look at the actual auth type and maybe override it.
- virtual string getAuthType(void) {
- const char *auth_type=ap_auth_type(m_req);
- if (!auth_type)
- return string("");
- if (strcasecmp(auth_type, "shibboleth")) {
- if (!strcasecmp(auth_type, "basic") && m_dc->bBasicHijack == 1) {
- core_dir_config* conf= (core_dir_config*)
- ap_get_module_config(m_req->per_dir_config,
- ap_find_linked_module("http_core.c"));
- auth_type = conf->ap_auth_type = "shibboleth";
- }
- }
- return string(auth_type);
+ void setContentType(const char* type) {
+ m_req->content_type = ap_psprintf(m_req->pool, type);
}
- // Override this function because we want to add the Apache Directory override
- virtual pair<bool,bool> getRequireSession(IRequestMapper::Settings &settings) {
- pair<bool,bool> requireSession = settings.first->getBool("requireSession");
- if (!requireSession.first || !requireSession.second)
- if (m_dc->bRequireSession == 1)
- requireSession.second=true;
-
- return requireSession;
+ void setResponseHeader(const char* name, const char* value) {
+#ifdef SHIB_DEFERRED_HEADERS
+ if (!m_rc)
+ // this happens on subrequests
+ m_rc = init_request_config(m_req);
+ ap_table_add(m_rc->hdr_err, name, value);
+ ap_table_add(m_rc->hdr_out, name, value);
+#else
+ ap_table_add(m_req->err_headers_out, name, value);
+#endif
}
-
- virtual HTAccessInfo* getAccessInfo(void) {
- int m = m_req->method_number;
- const array_header* reqs_arr = ap_requires(m_req);
- if (!reqs_arr)
- return NULL;
-
- require_line* reqs = (require_line*) reqs_arr->elts;
-
- ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req),
- "REQUIRE nelts: %d", reqs_arr->nelts);
- ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req),
- "REQUIRE all: %d", m_dc->bRequireAll);
-
- HTAccessInfo* ht = new HTAccessInfo();
- ht->requireAll = (m_dc->bRequireAll >= 0);
- ht->elements.reserve(reqs_arr->nelts);
- for (int x = 0; x < reqs_arr->nelts; x++) {
- HTAccessInfo::RequireLine* rline = new HTAccessInfo::RequireLine();
- rline->use_line = (reqs[x].method_mask & (1 << m));
- rline->tokens.reserve(6); // No reason to reserve specifically 6 tokens
- const char* t = reqs[x].requirement;
- const char* w = ap_getword_white(m_req->pool, &t);
- rline->tokens.push_back(w);
- while (*t) {
- w = ap_getword_conf(m_req->pool, &t);
- rline->tokens.push_back(w);
- }
- ht->elements.push_back(rline);
+ long sendResponse(istream& in, long status) {
+ ap_send_http_header(m_req);
+ char buf[1024];
+ while (in) {
+ in.read(buf,1024);
+ ap_rwrite(buf,in.gcount(),m_req);
}
- return ht;
+ return ((status==XMLTOOLING_HTTP_STATUS_OK) ? DONE : status);
}
- virtual HTGroupTable* getGroupTable(string &user) {
- if (m_dc->szAuthGrpFile && !user.empty()) {
- ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req),
- "getGroupTable() using groups file: %s\n",
- m_dc->szAuthGrpFile);
- try {
- HTGroupTableApache *gt = new HTGroupTableApache(m_req, user.c_str(),
- m_dc->szAuthGrpFile);
- return gt;
- } catch (...) { }
- }
- return NULL;
+ long sendRedirect(const char* url) {
+ ap_table_set(m_req->headers_out, "Location", url);
+ return REDIRECT;
}
-
- virtual void* sendPage(
- const string &msg,
- const string content_type,
- const saml::Iterator<header_t>& headers=EMPTY(header_t),
- int code=200
- ) {
- m_req->content_type = ap_psprintf(m_req->pool, content_type.c_str());
- while (headers.hasNext()) {
- const header_t& h=headers.next();
- ap_table_setn(m_req->headers_out, h.first.c_str(), h.second.c_str());
- }
- ap_send_http_header(m_req);
- ap_rprintf(m_req, msg.c_str());
- return (void*)DONE;
+ const vector<string>& getClientCertificates() const {
+ return m_certs;
}
- virtual void* sendRedirect(const string url) {
- ap_table_set(m_req->headers_out, "Location", url.c_str());
- return (void*)REDIRECT;
- }
- virtual void* returnDecline(void) { return (void*)DECLINED; }
- virtual void* returnOK(void) { return (void*)OK; }
-
- request_rec* m_req;
- shib_dir_config* m_dc;
- shib_server_config* m_sc;
+ long returnDecline(void) { return DECLINED; }
+ long returnOK(void) { return OK; }
};
/********************************************************************************/
extern "C" int shib_check_user(request_rec* r)
{
- ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
- "shib_check_user(%d): ENTER\n", (int)getpid());
+ // Short-circuit entirely?
+ if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
+ return DECLINED;
+
+ ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_check_user(%d): ENTER\n", (int)getpid());
ostringstream threadid;
threadid << "[" << getpid() << "] shib_check_user" << '\0';
- saml::NDC ndc(threadid.str().c_str());
+ xmltooling::NDC ndc(threadid.str().c_str());
-#ifndef _DEBUG
try {
-#endif
ShibTargetApache sta(r);
- // Check user authentication, the set the post handler bypass
- pair<bool,void*> res = sta.doCheckAuthN((sta.m_dc->bRequireSession == 1), true);
+ // Check user authentication and export information, then set the handler bypass
+ pair<bool,long> res = sta.getServiceProvider().doAuthentication(sta,true);
apr_pool_userdata_setn((const void*)42,g_UserDataKey,NULL,r->pool);
- if (res.first) return (int)res.second;
+ if (res.first) return res.second;
// user auth was okay -- export the assertions now
- res = sta.doExportAssertions((sta.m_dc->bExportAssertion == 1));
- if (res.first) return (int)res.second;
+ res = sta.getServiceProvider().doExport(sta);
+ if (res.first) return res.second;
// export happened successfully.. this user is ok.
return OK;
-
+ }
+ catch (exception& e) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user threw an exception: %s", e.what());
+ return SERVER_ERROR;
+ }
#ifndef _DEBUG
- } catch (...) {
- ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r),
- "shib_check_user threw an uncaught exception!");
+ catch (...) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user threw an uncaught exception!");
return SERVER_ERROR;
}
#endif
}
-extern "C" int shib_post_handler(request_rec* r)
+extern "C" int shib_handler(request_rec* r)
{
+ // Short-circuit entirely?
+ if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
+ return DECLINED;
+
ostringstream threadid;
- threadid << "[" << getpid() << "] shib_post_handler" << '\0';
- saml::NDC ndc(threadid.str().c_str());
+ threadid << "[" << getpid() << "] shib_handler" << '\0';
+ xmltooling::NDC ndc(threadid.str().c_str());
#ifndef SHIB_APACHE_13
// With 2.x, this handler always runs, though last.
- // We check if shib_check_user ran, because it will detect a SHIRE request
+ // We check if shib_check_user ran, because it will detect a handler request
// and dispatch it directly.
void* data;
apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
if (data==(const void*)42) {
- ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_post_handler skipped since check_user ran");
+ ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler skipped since check_user ran");
return DECLINED;
}
#endif
- ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
- "shib_post_handler(%d): ENTER", (int)getpid());
+ ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler(%d): ENTER: %s", (int)getpid(), r->handler);
-#ifndef _DEBUG
try {
-#endif
ShibTargetApache sta(r);
- pair<bool,void*> res = sta.doHandleProfile();
- if (res.first) return (int)res.second;
+ pair<bool,long> res = sta.getServiceProvider().doHandler(sta);
+ if (res.first) return res.second;
- ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r),
- "doHandleProfile() did not do anything.");
+ ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "doHandler() did not do anything.");
return SERVER_ERROR;
-
+ }
+ catch (exception& e) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler threw an exception: %s", e.what());
+ return SERVER_ERROR;
+ }
#ifndef _DEBUG
- } catch (...) {
- ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r),
- "shib_post_handler threw an uncaught exception!");
+ catch (...) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler threw an uncaught exception!");
return SERVER_ERROR;
}
#endif
*/
extern "C" int shib_auth_checker(request_rec* r)
{
- ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
- "shib_auth_checker(%d): ENTER", (int)getpid());
+ // Short-circuit entirely?
+ if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
+ return DECLINED;
+
+ ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_auth_checker(%d): ENTER", (int)getpid());
ostringstream threadid;
threadid << "[" << getpid() << "] shib_auth_checker" << '\0';
- saml::NDC ndc(threadid.str().c_str());
+ xmltooling::NDC ndc(threadid.str().c_str());
-#ifndef _DEBUG
try {
-#endif
ShibTargetApache sta(r);
- pair<bool,void*> res = sta.doCheckAuthZ();
- if (res.first) return (int)res.second;
+ pair<bool,long> res = sta.getServiceProvider().doAuthorization(sta);
+ if (res.first) return res.second;
// We're all okay.
return OK;
-
+ }
+ catch (exception& e) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an exception: %s", e.what());
+ return SERVER_ERROR;
+ }
#ifndef _DEBUG
- } catch (...) {
- ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r),
- "shib_auth_checker threw an uncaught exception!");
+ catch (...) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an uncaught exception!");
return SERVER_ERROR;
}
#endif
}
-#if 0
-static char* shib_get_targeturl(request_rec* r, const char* scheme=NULL)
+// Access control plugin that enforces htaccess rules
+class htAccessControl : virtual public AccessControl
{
- // On 1.3, this is always canonical, but on 2.0, UseCanonicalName comes into play.
- // However, we also have a setting to forcibly replace the scheme for esoteric cases.
- if (scheme) {
- unsigned port = ap_get_server_port(r);
- if ((!strcmp(scheme,"http") && port==80) || (!strcmp(scheme,"https") && port==443)) {
- return ap_pstrcat(r->pool, scheme, "://", ap_get_server_name(r), r->unparsed_uri, NULL);
- }
- return ap_psprintf(r->pool, "%s://%s:%u%s", scheme, ap_get_server_name(r), port, r->unparsed_uri);
- }
- return ap_construct_url(r->pool,r->unparsed_uri,r);
-}
+public:
+ htAccessControl() {}
+ ~htAccessControl() {}
+ Lockable* lock() {return this;}
+ void unlock() {}
+ bool authorized(const SPRequest& request, const Session* session) const;
+private:
+ bool checkAttribute(const SPRequest& request, const Attribute* attr, const char* toMatch, RegularExpression* re) const;
+};
-extern "C" int shib_check_user(request_rec* r)
+AccessControl* htAccessFactory(const xercesc::DOMElement* const & e)
{
- ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: ENTER");
- shib_dir_config* dc=(shib_dir_config*)ap_get_module_config(r->per_dir_config,&mod_shib);
- shib_server_config* sc=(shib_server_config*)ap_get_module_config(r->server->module_config,&mod_shib);
-
- ostringstream threadid;
- threadid << "[" << getpid() << "] shib_check_user" << '\0';
- saml::NDC ndc(threadid.str().c_str());
-
- const char* targeturl=shib_get_targeturl(r,sc->szScheme);
+ return new htAccessControl();
+}
- // We lock the configuration system for the duration.
- IConfig* conf=g_Config->getINI();
- Locker locker(conf);
-
- // Map request to application and content settings.
- IRequestMapper* mapper=conf->getRequestMapper();
- Locker locker2(mapper);
- IRequestMapper::Settings settings=mapper->getSettingsFromParsedURL(
- (sc-> szScheme ? sc-> szScheme : ap_http_method(r)), ap_get_server_name(r), ap_get_server_port(r), r->unparsed_uri
- );
- pair<bool,const char*> application_id=settings.first->getString("applicationId");
- const IApplication* application=conf->getApplication(application_id.second);
- if (!application) {
- ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
- "shib_check_user: unable to map request to application settings, check configuration");
- return SERVER_ERROR;
- }
-
- // Declare SHIRE object for this request.
- SHIRE shire(application);
-
- const char* shireURL=shire.getShireURL(targeturl);
- if (!shireURL) {
- ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
- "shib_check_user: unable to map request to proper shireURL setting, check configuration");
- return SERVER_ERROR;
- }
+class ApacheRequestMapper : public virtual RequestMapper, public virtual PropertySet
+{
+public:
+ ApacheRequestMapper(const xercesc::DOMElement* e);
+ ~ApacheRequestMapper() { delete m_mapper; delete m_htaccess; delete m_staKey; delete m_propsKey; }
+ Lockable* lock() { return m_mapper->lock(); }
+ void unlock() { m_staKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
+ Settings getSettings(const SPRequest& request) const;
- // Get location of this application's assertion consumer service and see if this is it.
- if (strstr(targeturl,shireURL)) {
- return shib_handler(r,application,shire);
- }
-
- // We can short circuit the handler if we run this...
- apr_pool_userdata_setn((const void*)42,g_UserDataKey,NULL,r->pool);
-
- // Regular access to arbitrary resource...check AuthType
- const char *auth_type=ap_auth_type(r);
- if (!auth_type)
- return DECLINED;
-
- if (strcasecmp(auth_type,"shibboleth")) {
- if (!strcasecmp(auth_type,"basic") && dc->bBasicHijack==1) {
- core_dir_config* conf=
- (core_dir_config*)ap_get_module_config(r->per_dir_config,
- ap_find_linked_module("http_core.c"));
- conf->ap_auth_type="shibboleth";
- }
- else
- return DECLINED;
- }
-
- pair<bool,bool> requireSession = settings.first->getBool("requireSession");
- if (!requireSession.first || !requireSession.second)
- if (dc->bRequireSession==1)
- requireSession.second=true;
-
- ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: session check for %s",targeturl);
-
- pair<const char*,const char*> shib_cookie=shire.getCookieNameProps(); // always returns *something*
-
- // We're in charge, so check for cookie.
- const char* session_id=NULL;
- const char* cookies=ap_table_get(r->headers_in,"Cookie");
-
- if (cookies) {
- ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: cookies found: %s",cookies);
- if (session_id=strstr(cookies,shib_cookie.first)) {
- // Yep, we found a cookie -- pull it out (our session_id)
- session_id+=strlen(shib_cookie.first) + 1; /* Skip over the '=' */
- char* cookiebuf = ap_pstrdup(r->pool,session_id);
- char* cookieend = strchr(cookiebuf,';');
- if (cookieend)
- *cookieend = '\0'; /* Ignore anyting after a ; */
- session_id=cookiebuf;
- }
- }
-
- if (!session_id || !*session_id) {
- // If no session required, bail now.
- if (!requireSession.second)
- return OK;
-
- // No acceptable cookie, and we require a session. Generate an AuthnRequest.
- ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: no cookie found -- redirecting to WAYF");
- ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(targeturl)));
- return REDIRECT;
- }
-
- // Make sure this session is still valid.
- RPCError* status = NULL;
- ShibMLP markupProcessor;
- markupProcessor.insert("requestURL", targeturl);
-
- try {
- status = shire.sessionIsValid(session_id, r->connection->remote_ip);
- }
- catch (ShibTargetException &e) {
- ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): %s", e.what());
- markupProcessor.insert("errorType", "Session Processing Error");
- markupProcessor.insert("errorText", e.what());
- markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
- return shib_error_page(r, application, "shire", markupProcessor);
- }
-#ifndef _DEBUG
- catch (...) {
- ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): caught unexpected error");
- markupProcessor.insert("errorType", "Session Processing Error");
- markupProcessor.insert("errorText", "Unexpected Exception");
- markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
- return shib_error_page(r, application, "shire", markupProcessor);
- }
-#endif
-
- // Check the status
- if (status->isError()) {
- ap_log_rerror(APLOG_MARK,APLOG_INFO|APLOG_NOERRNO,SH_AP_R(r),
- "shib_check_user() session invalid: %s", status->getText());
-
- // If no session required, bail now.
- if (!requireSession.second)
- return OK; // XXX: Or should this be DECLINED?
- // Has to be OK because DECLINED will just cause Apache to fail when it can't locate
- // anything to process the AuthType. No session plus requireSession false means
- // do not authenticate the user.
- else if (status->isRetryable()) {
- // Oops, session is invalid. Generate AuthnRequest.
- ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(targeturl)));
- delete status;
- return REDIRECT;
- }
- else {
- // return the error page to the user
- markupProcessor.insert(*status);
- delete status;
- return shib_error_page(r, application, "shire", markupProcessor);
- }
- }
-
- delete status;
- // set the authtype
-#ifdef SHIB_APACHE_13
- if (r->connection)
- r->connection->ap_auth_type = "shibboleth";
-#else
- r->ap_auth_type = "shibboleth";
-#endif
- ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: session successfully verified");
-
- // This is code transferred in from the auth check to export the attributes.
- // We could even combine the isSessionValid/getAssertions API...?
-
- RM rm(application);
- vector<SAMLAssertion*> assertions;
- SAMLAuthenticationStatement* sso_statement=NULL;
+ void setParent(const PropertySet*) {}
+ pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
+ pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
+ pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
+ pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
+ pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
+ const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:2.0:native:sp:config") const;
+ const xercesc::DOMElement* getElement() const;
+
+private:
+ RequestMapper* m_mapper;
+ ThreadKey* m_staKey;
+ ThreadKey* m_propsKey;
+ AccessControl* m_htaccess;
+};
- try {
- status = rm.getAssertions(session_id, r->connection->remote_ip, assertions, &sso_statement);
- }
- catch (ShibTargetException &e) {
- ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): %s", e.what());
- markupProcessor.insert("errorType", "Attribute Processing Error");
- markupProcessor.insert("errorText", e.what());
- markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
- return shib_error_page(r, application, "rm", markupProcessor);
- }
-#ifndef _DEBUG
- catch (...) {
- ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): caught unexpected error");
- markupProcessor.insert("errorType", "Attribute Processing Error");
- markupProcessor.insert("errorText", "Unexpected Exception");
- markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
- return shib_error_page(r, application, "rm", markupProcessor);
- }
-#endif
+RequestMapper* ApacheRequestMapFactory(const xercesc::DOMElement* const & e)
+{
+ return new ApacheRequestMapper(e);
+}
- if (status->isError()) {
- ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
- "shib_check_user() getAssertions failed: %s", status->getText());
+ApacheRequestMapper::ApacheRequestMapper(const xercesc::DOMElement* e) : m_mapper(NULL), m_staKey(NULL), m_propsKey(NULL), m_htaccess(NULL)
+{
+ m_mapper=SPConfig::getConfig().RequestMapperManager.newPlugin(XML_REQUEST_MAPPER,e);
+ m_htaccess=new htAccessControl();
+ m_staKey=ThreadKey::create(NULL);
+ m_propsKey=ThreadKey::create(NULL);
+}
- markupProcessor.insert(*status);
- delete status;
- return shib_error_page(r, application, "rm", markupProcessor);
- }
- delete status;
-
- // Do we have an access control plugin?
- if (settings.second) {
- Locker acllock(settings.second);
- if (!settings.second->authorized(*sso_statement,assertions)) {
- for (int k = 0; k < assertions.size(); k++)
- delete assertions[k];
- delete sso_statement;
- ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): access control provider denied access");
- return shib_error_page(r, application, "access", markupProcessor);
- }
- }
+RequestMapper::Settings ApacheRequestMapper::getSettings(const SPRequest& request) const
+{
+ Settings s=m_mapper->getSettings(request);
+ m_staKey->setData((void*)dynamic_cast<const ShibTargetApache*>(&request));
+ m_propsKey->setData((void*)s.first);
+ return pair<const PropertySet*,AccessControl*>(this,s.second ? s.second : m_htaccess);
+}
- // Get the AAP providers, which contain the attribute policy info.
- Iterator<IAAP*> provs=application->getAAPProviders();
-
- // Clear out the list of mapped attributes
- while (provs.hasNext()) {
- IAAP* aap=provs.next();
- aap->lock();
- try {
- Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
- while (rules.hasNext()) {
- const char* header=rules.next()->getHeader();
- if (header)
- ap_table_unset(r->headers_in,header);
- }
- }
- catch(...) {
- aap->unlock();
- for (int k = 0; k < assertions.size(); k++)
- delete assertions[k];
- delete sso_statement;
- ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
- "shib_check_user(): caught unexpected error while clearing headers");
- markupProcessor.insert("errorType", "Attribute Processing Error");
- markupProcessor.insert("errorText", "Unexpected Exception");
- markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
- return shib_error_page(r, application, "rm", markupProcessor);
- }
- aap->unlock();
- }
- provs.reset();
-
- // Maybe export the first assertion.
- ap_table_unset(r->headers_in,"Shib-Attributes");
- pair<bool,bool> exp=settings.first->getBool("exportAssertion");
- if (!exp.first || !exp.second)
- if (dc->bExportAssertion==1)
- exp.second=true;
- if (exp.second && assertions.size()) {
- string assertion;
- RM::serialize(*(assertions[0]), assertion);
- ap_table_set(r->headers_in,"Shib-Attributes", assertion.c_str());
+pair<bool,bool> ApacheRequestMapper::getBool(const char* name, const char* ns) const
+{
+ const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
+ const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
+ if (sta && !ns) {
+ // Override Apache-settable boolean properties.
+ if (name && !strcmp(name,"requireSession") && sta->m_dc->bRequireSession==1)
+ return make_pair(true,true);
+ else if (name && !strcmp(name,"exportAssertion") && sta->m_dc->bExportAssertion==1)
+ return make_pair(true,true);
}
+ return s ? s->getBool(name,ns) : make_pair(false,false);
+}
- // Export the SAML AuthnMethod and the origin site name, and possibly the NameIdentifier.
- ap_table_unset(r->headers_in,"Shib-Origin-Site");
- ap_table_unset(r->headers_in,"Shib-Authentication-Method");
- ap_table_unset(r->headers_in,"Shib-NameIdentifier-Format");
- auto_ptr_char os(sso_statement->getSubject()->getNameIdentifier()->getNameQualifier());
- auto_ptr_char am(sso_statement->getAuthMethod());
- ap_table_set(r->headers_in,"Shib-Origin-Site", os.get());
- ap_table_set(r->headers_in,"Shib-Authentication-Method", am.get());
-
- // Export NameID?
- AAP wrapper(provs,sso_statement->getSubject()->getNameIdentifier()->getFormat(),Constants::SHIB_ATTRIBUTE_NAMESPACE_URI);
- if (!wrapper.fail() && wrapper->getHeader()) {
- auto_ptr_char form(sso_statement->getSubject()->getNameIdentifier()->getFormat());
- auto_ptr_char nameid(sso_statement->getSubject()->getNameIdentifier()->getName());
- ap_table_set(r->headers_in,"Shib-NameIdentifier-Format",form.get());
- if (!strcmp(wrapper->getHeader(),"REMOTE_USER"))
- SH_AP_USER(r)=ap_pstrdup(r->pool,nameid.get());
- else
- ap_table_set(r->headers_in,wrapper->getHeader(),nameid.get());
- }
-
- ap_table_unset(r->headers_in,"Shib-Application-ID");
- ap_table_set(r->headers_in,"Shib-Application-ID",application_id.second);
-
- // Export the attributes.
- Iterator<SAMLAssertion*> a_iter(assertions);
- while (a_iter.hasNext()) {
- SAMLAssertion* assert=a_iter.next();
- Iterator<SAMLStatement*> statements=assert->getStatements();
- while (statements.hasNext()) {
- SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());
- if (!astate)
- continue;
- Iterator<SAMLAttribute*> attrs=astate->getAttributes();
- while (attrs.hasNext()) {
- SAMLAttribute* attr=attrs.next();
-
- // Are we supposed to export it?
- AAP wrapper(provs,attr->getName(),attr->getNamespace());
- if (wrapper.fail() || !wrapper->getHeader())
- continue;
-
- Iterator<string> vals=attr->getSingleByteValues();
- if (!strcmp(wrapper->getHeader(),"REMOTE_USER") && vals.hasNext())
- SH_AP_USER(r)=ap_pstrdup(r->pool,vals.next().c_str());
- else {
- int it=0;
- char* header = (char*)ap_table_get(r->headers_in, wrapper->getHeader());
- if (header) {
- header=ap_pstrdup(r->pool, header);
- it++;
- }
- else
- header = ap_pstrdup(r->pool, "");
- for (; vals.hasNext(); it++) {
- string value = vals.next();
- for (string::size_type pos = value.find_first_of(";", string::size_type(0));
- pos != string::npos;
- pos = value.find_first_of(";", pos)) {
- value.insert(pos, "\\");
- pos += 2;
- }
- header=ap_pstrcat(r->pool, header, (it ? ";" : ""), value.c_str(), NULL);
- }
- ap_table_setn(r->headers_in, wrapper->getHeader(), header);
- }
+pair<bool,const char*> ApacheRequestMapper::getString(const char* name, const char* ns) const
+{
+ const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
+ const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
+ if (sta && !ns) {
+ // Override Apache-settable string properties.
+ if (name && !strcmp(name,"authType")) {
+ const char *auth_type=ap_auth_type(sta->m_req);
+ if (auth_type) {
+ // Check for Basic Hijack
+ if (!strcasecmp(auth_type, "basic") && sta->m_dc->bBasicHijack == 1)
+ auth_type = "shibboleth";
+ return make_pair(true,auth_type);
}
}
+ else if (name && !strcmp(name,"applicationId") && sta->m_dc->szApplicationId)
+ return pair<bool,const char*>(true,sta->m_dc->szApplicationId);
+ else if (name && !strcmp(name,"requireSessionWith") && sta->m_dc->szRequireWith)
+ return pair<bool,const char*>(true,sta->m_dc->szRequireWith);
+ else if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
+ return pair<bool,const char*>(true,sta->m_dc->szRedirectToSSL);
}
-
- // clean up memory
- for (int k = 0; k < assertions.size(); k++)
- delete assertions[k];
- delete sso_statement;
-
- return OK;
+ return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
}
-extern "C" int shib_post_handler(request_rec* r)
+pair<bool,const XMLCh*> ApacheRequestMapper::getXMLString(const char* name, const char* ns) const
{
- ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
- "shib_post_handler(%d): ENTER", (int)getpid());
- shib_server_config* sc=(shib_server_config*)ap_get_module_config(r->server->module_config,&mod_shib);
+ const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
+ return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
+}
-#ifndef SHIB_APACHE_13
- // With 2.x, this handler always runs, though last.
- // We check if shib_check_user ran, because it will detect a SHIRE request
- // and dispatch it directly.
- void* data;
- apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
- if (data==(const void*)42) {
- ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_post_handler skipped since check_user ran");
- return DECLINED;
+pair<bool,unsigned int> ApacheRequestMapper::getUnsignedInt(const char* name, const char* ns) const
+{
+ const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
+ const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
+ if (sta && !ns) {
+ // Override Apache-settable int properties.
+ if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
+ return pair<bool,unsigned int>(true,strtol(sta->m_dc->szRedirectToSSL,NULL,10));
}
-#endif
-
- ostringstream threadid;
- threadid << "[" << getpid() << "] shib_post_handler" << '\0';
- saml::NDC ndc(threadid.str().c_str());
+ return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
+}
- // We lock the configuration system for the duration.
- IConfig* conf=g_Config->getINI();
- Locker locker(conf);
-
- // Map request to application and content settings.
- IRequestMapper* mapper=conf->getRequestMapper();
- Locker locker2(mapper);
- IRequestMapper::Settings settings=mapper->getSettingsFromParsedURL(
- (sc->szScheme ? sc->szScheme : ap_http_method(r)), ap_get_server_name(r), ap_get_server_port(r), r->unparsed_uri
- );
- pair<bool,const char*> application_id=settings.first->getString("applicationId");
- const IApplication* application=conf->getApplication(application_id.second);
- if (!application) {
- ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
- "shib_post_handler: unable to map request to application settings, check configuration");
- return SERVER_ERROR;
+pair<bool,int> ApacheRequestMapper::getInt(const char* name, const char* ns) const
+{
+ const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
+ const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
+ if (sta && !ns) {
+ // Override Apache-settable int properties.
+ if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
+ return pair<bool,int>(true,atoi(sta->m_dc->szRedirectToSSL));
}
-
- // Declare SHIRE object for this request.
- SHIRE shire(application);
-
- return shib_handler(r, application, shire);
+ return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
}
-int shib_handler(request_rec* r, const IApplication* application, SHIRE& shire)
+const PropertySet* ApacheRequestMapper::getPropertySet(const char* name, const char* ns) const
{
- shib_server_config* sc=(shib_server_config*)ap_get_module_config(r->server->module_config,&mod_shib);
-
- const char* targeturl=shib_get_targeturl(r,sc->szScheme);
-
- const char* shireURL=shire.getShireURL(targeturl);
- if (!shireURL) {
- ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
- "shib_post_handler: unable to map request to proper shireURL setting, check configuration");
- return SERVER_ERROR;
- }
+ const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
+ return s ? s->getPropertySet(name,ns) : NULL;
+}
- // Make sure we only process the SHIRE requests.
- if (!strstr(targeturl,shireURL))
- return DECLINED;
+const xercesc::DOMElement* ApacheRequestMapper::getElement() const
+{
+ const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
+ return s ? s->getElement() : NULL;
+}
- ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler() running");
+static SH_AP_TABLE* groups_for_user(request_rec* r, const char* user, char* grpfile)
+{
+ SH_AP_CONFIGFILE* f;
+ SH_AP_TABLE* grps=ap_make_table(r->pool,15);
+ char l[MAX_STRING_LEN];
+ const char *group_name, *ll, *w;
- const IPropertySet* sessionProps=application->getPropertySet("Sessions");
- if (!sessionProps) {
- ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
- "shib_post_handler: unable to map request to application session settings, check configuration");
- return SERVER_ERROR;
+#ifdef SHIB_APACHE_13
+ if (!(f=ap_pcfg_openfile(r->pool,grpfile))) {
+#else
+ if (ap_pcfg_openfile(&f,r->pool,grpfile) != APR_SUCCESS) {
+#endif
+ ap_log_rerror(APLOG_MARK,APLOG_DEBUG,SH_AP_R(r),"groups_for_user() could not open group file: %s\n",grpfile);
+ return NULL;
}
- pair<const char*,const char*> shib_cookie=shire.getCookieNameProps(); // always returns something
-
- ShibMLP markupProcessor;
- markupProcessor.insert("requestURL", targeturl);
+ SH_AP_POOL* sp;
+#ifdef SHIB_APACHE_13
+ sp=ap_make_sub_pool(r->pool);
+#else
+ if (apr_pool_create(&sp,r->pool) != APR_SUCCESS) {
+ ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,
+ "groups_for_user() could not create a subpool");
+ return NULL;
+ }
+#endif
- // Process SHIRE request
- ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() Beginning SHIRE processing");
-
- try {
- pair<bool,bool> shireSSL=sessionProps->getBool("shireSSL");
-
- // Make sure this is SSL, if it should be
- if ((!shireSSL.first || shireSSL.second) && strcmp(ap_http_method(r),"https"))
- throw ShibTargetException(SHIBRPC_OK, "blocked non-SSL access to session creation service");
-
- // If this is a GET, we manufacture an AuthnRequest.
- if (!strcasecmp(r->method,"GET")) {
- const char* areq=r->args ? shire.getLazyAuthnRequest(r->args) : NULL;
- if (!areq)
- throw ShibTargetException(SHIBRPC_OK, "malformed arguments to request a new session");
- ap_table_setn(r->headers_out, "Location", ap_pstrdup(r->pool,areq));
- return REDIRECT;
- }
- else if (strcasecmp(r->method,"POST")) {
- throw ShibTargetException(SHIBRPC_OK, "blocked non-POST to SHIRE POST processor");
- }
+ while (!(ap_cfg_getline(l,MAX_STRING_LEN,f))) {
+ if ((*l=='#') || (!*l))
+ continue;
+ ll = l;
+ ap_clear_pool(sp);
- // Sure sure this POST is an appropriate content type
- const char *ct = ap_table_get(r->headers_in, "Content-type");
- if (!ct || strcasecmp(ct, "application/x-www-form-urlencoded"))
- throw ShibTargetException(SHIBRPC_OK,
- ap_psprintf(r->pool, "blocked bad content-type to SHIRE POST processor: %s", (ct ? ct : "")));
-
- // Read the posted data
- if (ap_setup_client_block(r, REQUEST_CHUNKED_ERROR))
- throw ShibTargetException(SHIBRPC_OK, "CGI setup_client_block failed");
- if (!ap_should_client_block(r))
- throw ShibTargetException(SHIBRPC_OK, "CGI should_client_block failed");
- if (r->remaining > 1024*1024)
- throw ShibTargetException (SHIBRPC_OK, "CGI length too long...");
-
- string cgistr;
- char buff[HUGE_STRING_LEN];
- ap_hard_timeout("[mod_shib] CGI Parser", r);
- memset(buff, 0, sizeof(buff));
- while (ap_get_client_block(r, buff, sizeof(buff)-1) > 0) {
- ap_reset_timeout(r);
- cgistr += buff;
- memset(buff, 0, sizeof(buff));
- }
- ap_kill_timeout(r);
+ group_name=ap_getword(sp,&ll,':');
- // Parse the submission.
- pair<const char*,const char*> elements=shire.getFormSubmission(cgistr.c_str(),cgistr.length());
-
- // Make sure the SAML Response parameter exists
- if (!elements.first || !*elements.first)
- throw ShibTargetException(SHIBRPC_OK, "SHIRE POST failed to find SAMLResponse form element");
-
- // Make sure the target parameter exists
- if (!elements.second || !*elements.second)
- throw ShibTargetException(SHIBRPC_OK, "SHIRE POST failed to find TARGET form element");
-
- ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
- "shib_handler() Processing POST for target: %s", elements.second);
-
- // process the post
- string cookie;
- RPCError* status = shire.sessionCreate(elements.first, r->connection->remote_ip, cookie);
-
- if (status->isError()) {
- ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
- "shib_handler() POST process failed (%d): %s", status->getCode(), status->getText());
-
- if (status->isRetryable()) {
- delete status;
- ap_log_rerror(APLOG_MARK,APLOG_INFO|APLOG_NOERRNO,SH_AP_R(r),
- "shib_handler() retryable error, generating new AuthnRequest");
- ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(elements.second)));
- return REDIRECT;
+ while (*ll) {
+ w=ap_getword_conf(sp,&ll);
+ if (!strcmp(w,user)) {
+ ap_table_setn(grps,ap_pstrdup(r->pool,group_name),"in");
+ break;
}
-
- // return this error to the user.
- markupProcessor.insert(*status);
- delete status;
- return shib_error_page(r, application, "shire", markupProcessor);
}
- delete status;
-
- ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
- "shib_handler() POST process succeeded. New session: %s", cookie.c_str());
-
- // We've got a good session, set the cookie...
- char* val = ap_psprintf(r->pool,"%s=%s%s",shib_cookie.first,cookie.c_str(),shib_cookie.second);
- ap_table_setn(r->err_headers_out, "Set-Cookie", val);
- ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() setting cookie: %s", val);
-
- // ... and redirect to the target
- ap_table_setn(r->headers_out, "Location", ap_pstrdup(r->pool,elements.second));
- return REDIRECT;
- }
- catch (ShibTargetException &e) {
- ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() caught exception: %s", e.what());
- markupProcessor.insert("errorType", "Session Creation Service Error");
- markupProcessor.insert("errorText", e.what());
- markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
- return shib_error_page(r, application, "shire", markupProcessor);
- }
-#ifndef _DEBUG
- catch (...) {
- ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler(): unexpected exception");
- markupProcessor.insert("errorType", "Session Creation Service Error");
- markupProcessor.insert("errorText", "Unknown Exception");
- markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
- return shib_error_page(r, application, "shire", markupProcessor);
}
-#endif
-
- ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_handler() server error");
- return SERVER_ERROR;
+ ap_cfg_closefile(f);
+ ap_destroy_pool(sp);
+ return grps;
}
-static int shib_error_page(request_rec* r, const IApplication* app, const char* page, ShibMLP& mlp)
+bool htAccessControl::checkAttribute(const SPRequest& request, const Attribute* attr, const char* toMatch, RegularExpression* re) const
{
- const IPropertySet* props=app->getPropertySet("Errors");
- if (props) {
- pair<bool,const char*> p=props->getString(page);
- if (p.first) {
- ifstream infile(p.second);
- if (!infile.fail()) {
- const char* res = mlp.run(infile,props);
- if (res) {
- r->content_type = ap_psprintf(r->pool, "text/html");
- ap_send_http_header(r);
- ap_rprintf(r, res);
- return DONE;
- }
+ bool caseSensitive = attr->isCaseSensitive();
+ const vector<string>& vals = attr->getSerializedValues();
+ for (vector<string>::const_iterator v=vals.begin(); v!=vals.end(); ++v) {
+ if (re) {
+ auto_ptr<XMLCh> trans(fromUTF8(v->c_str()));
+ if (re->matches(trans.get())) {
+ request.log(SPRequest::SPDebug,
+ string("htAccessControl plugin expecting regexp ") + toMatch + ", got " + *v + ": authorization granted"
+ );
+ return true;
}
}
+ else if ((caseSensitive && *v == toMatch) || (!caseSensitive && !strcasecmp(v->c_str(), toMatch))) {
+ request.log(SPRequest::SPDebug,
+ string("htAccessControl plugin expecting ") + toMatch + ", got " + *v + ": authorization granted."
+ );
+ return true;
+ }
+ else {
+ request.log(SPRequest::SPDebug,
+ string("htAccessControl plugin expecting ") + toMatch + ", got " + *v + ": authorization not granted."
+ );
+ }
}
-
- ap_log_rerror(APLOG_MARK,APLOG_ERR,SH_AP_R(r),
- "shib_error_page() could not process shire error template for application %s",app->getId());
- return SERVER_ERROR;
+ return false;
}
-/*
- * shib_auth_checker() -- a simple resource manager to
- * process the .htaccess settings and copy attributes
- * into the HTTP headers.
- */
-extern "C" int shib_auth_checker(request_rec* r)
+bool htAccessControl::authorized(const SPRequest& request, const Session* session) const
{
- shib_dir_config* dc=
- (shib_dir_config*)ap_get_module_config(r->per_dir_config,&mod_shib);
-
- ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() executing");
-
- // Regular access to arbitrary resource...check AuthType
- const char* auth_type=ap_auth_type(r);
- if (!auth_type || strcasecmp(auth_type,"shibboleth"))
- return DECLINED;
-
- ostringstream threadid;
- threadid << "[" << getpid() << "] shibrm" << '\0';
- saml::NDC ndc(threadid.str().c_str());
-
- // We lock the configuration system for the duration.
- IConfig* conf=g_Config->getINI();
- Locker locker(conf);
-
- const char* application_id=ap_table_get(r->headers_in,"Shib-Application-ID");
- const IApplication* application=NULL;
- if (application_id)
- application = conf->getApplication(application_id);
+ // Make sure the object is our type.
+ const ShibTargetApache* sta=dynamic_cast<const ShibTargetApache*>(&request);
+ if (!sta)
+ throw ConfigurationException("Request wrapper object was not of correct type.");
// mod_auth clone
- int m=r->method_number;
+ int m=sta->m_req->method_number;
bool method_restricted=false;
const char *t, *w;
- const array_header* reqs_arr=ap_requires(r);
+ const array_header* reqs_arr=ap_requires(sta->m_req);
if (!reqs_arr)
- return OK;
+ return true;
require_line* reqs=(require_line*)reqs_arr->elts;
-
- ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"REQUIRE nelts: %d", reqs_arr->nelts);
- ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"REQUIRE all: %d", dc->bRequireAll);
+
+ ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(sta->m_req),"REQUIRE nelts: %d", reqs_arr->nelts);
+ ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(sta->m_req),"REQUIRE all: %d", sta->m_dc->bRequireAll);
vector<bool> auth_OK(reqs_arr->nelts,false);
-#define SHIB_AP_CHECK_IS_OK { \
- if (dc->bRequireAll < 1) \
- return OK; \
- auth_OK[x] = true; \
- continue; \
+#define SHIB_AP_CHECK_IS_OK { \
+ if (sta->m_dc->bRequireAll < 1) \
+ return true; \
+ auth_OK[x] = true; \
+ continue; \
}
for (int x=0; x<reqs_arr->nelts; x++) {
if (!(reqs[x].method_mask & (1 << m)))
continue;
method_restricted=true;
+ string remote_user = request.getRemoteUser();
t = reqs[x].requirement;
- w = ap_getword_white(r->pool, &t);
+ w = ap_getword_white(sta->m_req->pool, &t);
- if (!strcasecmp(w,"Shibboleth")) {
+ if (!strcasecmp(w,"shibboleth")) {
// This is a dummy rule needed because Apache conflates authn and authz.
// Without some require rule, AuthType is ignored and no check_user hooks run.
SHIB_AP_CHECK_IS_OK;
}
- else if (!strcmp(w,"valid-user") && application_id) {
- ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting valid-user");
- SHIB_AP_CHECK_IS_OK;
+ else if (!strcmp(w,"valid-user")) {
+ if (session) {
+ request.log(SPRequest::SPDebug,"htAccessControl plugin accepting valid-user based on active session");
+ SHIB_AP_CHECK_IS_OK;
+ }
+ else
+ request.log(SPRequest::SPError,"htAccessControl plugin rejecting access for valid-user rule, no session is active");
}
- else if (!strcmp(w,"user") && SH_AP_USER(r)) {
+ else if (!strcmp(w,"user") && !remote_user.empty()) {
bool regexp=false;
while (*t) {
- w=ap_getword_conf(r->pool,&t);
+ w=ap_getword_conf(sta->m_req->pool,&t);
if (*w=='~') {
regexp=true;
continue;
// To do regex matching, we have to convert from UTF-8.
auto_ptr<XMLCh> trans(fromUTF8(w));
RegularExpression re(trans.get());
- auto_ptr<XMLCh> trans2(fromUTF8(SH_AP_USER(r)));
+ auto_ptr<XMLCh> trans2(fromUTF8(remote_user.c_str()));
if (re.matches(trans2.get())) {
- ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting user: %s",w);
+ request.log(SPRequest::SPDebug, string("htAccessControl plugin accepting user (") + w + ")");
SHIB_AP_CHECK_IS_OK;
}
}
catch (XMLException& ex) {
auto_ptr_char tmp(ex.getMessage());
- ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
- "shib_auth_checker caught exception while parsing regular expression (%s): %s",w,tmp.get());
+ request.log(SPRequest::SPError,
+ string("htAccessControl plugin caught exception while parsing regular expression (") + w + "): " + tmp.get());
}
}
- else if (!strcmp(SH_AP_USER(r),w)) {
- ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting user: %s",w);
+ else if (remote_user==w) {
+ request.log(SPRequest::SPDebug, string("htAccessControl plugin accepting user (") + w + ")");
SHIB_AP_CHECK_IS_OK;
}
}
}
else if (!strcmp(w,"group")) {
SH_AP_TABLE* grpstatus=NULL;
- if (dc->szAuthGrpFile && SH_AP_USER(r)) {
- ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() using groups file: %s\n",dc->szAuthGrpFile);
- grpstatus=groups_for_user(r,SH_AP_USER(r),dc->szAuthGrpFile);
+ if (sta->m_dc->szAuthGrpFile && !remote_user.empty()) {
+ request.log(SPRequest::SPDebug,string("htAccessControl plugin using groups file: ") + sta->m_dc->szAuthGrpFile);
+ grpstatus=groups_for_user(sta->m_req,remote_user.c_str(),sta->m_dc->szAuthGrpFile);
}
if (!grpstatus)
- return DECLINED;
+ continue;
while (*t) {
- w=ap_getword_conf(r->pool,&t);
+ w=ap_getword_conf(sta->m_req->pool,&t);
if (ap_table_get(grpstatus,w)) {
- ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting group: %s",w);
+ request.log(SPRequest::SPDebug, string("htAccessControl plugin accepting group (") + w + ")");
SHIB_AP_CHECK_IS_OK;
}
}
}
else {
- Iterator<IAAP*> provs=application ? application->getAAPProviders() : EMPTY(IAAP*);
- AAP wrapper(provs,w);
- if (wrapper.fail()) {
- ap_log_rerror(APLOG_MARK,APLOG_WARNING|APLOG_NOERRNO,SH_AP_R(r),
- "shib_auth_checker() didn't recognize require rule: %s\n",w);
+ // Map alias in rule to the attribute.
+ if (!session) {
+ request.log(SPRequest::SPError, "htAccessControl plugin not given a valid session to evaluate, are you using lazy sessions?");
+ continue;
+ }
+
+ // Find the attribute(s) matching the require rule.
+ pair<multimap<string,Attribute*>::const_iterator,multimap<string,Attribute*>::const_iterator> attrs =
+ session->getAttributes().equal_range(w);
+ if (attrs.first == attrs.second) {
+ request.log(SPRequest::SPWarn, string("htAccessControl rule requires attribute (") + w + "), not found in session");
continue;
}
bool regexp=false;
- const char* vals=ap_table_get(r->headers_in,wrapper->getHeader());
- while (*t && vals) {
- w=ap_getword_conf(r->pool,&t);
+
+ while (!auth_OK[x] && *t) {
+ w=ap_getword_conf(sta->m_req->pool,&t);
if (*w=='~') {
regexp=true;
continue;
if (regexp) {
delete re.release();
auto_ptr<XMLCh> trans(fromUTF8(w));
- auto_ptr<RegularExpression> temp(new RegularExpression(trans.get()));
+ auto_ptr<xercesc::RegularExpression> temp(new xercesc::RegularExpression(trans.get()));
re=temp;
}
- string vals_str(vals);
- int j = 0;
- for (int i = 0; i < vals_str.length(); i++) {
- if (vals_str.at(i) == ';') {
- if (i == 0) {
- ap_log_rerror(APLOG_MARK,APLOG_WARNING|APLOG_NOERRNO,SH_AP_R(r),
- "shib_auth_checker() invalid header encoding %s: starts with semicolon", vals);
- return SERVER_ERROR;
- }
-
- if (vals_str.at(i-1) == '\\') {
- vals_str.erase(i-1, 1);
- i--;
- continue;
- }
-
- string val = vals_str.substr(j, i-j);
- j = i+1;
- if (regexp) {
- auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
- if (re->matches(trans.get())) {
- ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
- "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
- SHIB_AP_CHECK_IS_OK;
- }
- }
- else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
- ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
- "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
- SHIB_AP_CHECK_IS_OK;
- }
- else {
- ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
- "shib_auth_checker() expecting %s, got %s: authorization not granted", w, val.c_str());
- }
- }
- }
-
- string val = vals_str.substr(j, vals_str.length()-j);
- if (regexp) {
- auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
- if (re->matches(trans.get())) {
- ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
- "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
+ for (; !auth_OK[x] && attrs.first!=attrs.second; ++attrs.first) {
+ if (checkAttribute(request, attrs.first->second, w, regexp ? re.get() : NULL)) {
SHIB_AP_CHECK_IS_OK;
}
}
- else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
- ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
- "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
- SHIB_AP_CHECK_IS_OK;
- }
- else {
- ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
- "shib_auth_checker() expecting %s, got %s: authorization not granted", w, val.c_str());
- }
}
catch (XMLException& ex) {
auto_ptr_char tmp(ex.getMessage());
- ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
- "shib_auth_checker caught exception while parsing regular expression (%s): %s",w,tmp.get());
+ request.log(SPRequest::SPError,
+ string("htAccessControl plugin caught exception while parsing regular expression (") + w + "): " + tmp.get()
+ );
}
}
}
for (int i= 0; i<reqs_arr->nelts; i++) {
auth_all_OK &= auth_OK[i];
}
- if (auth_all_OK)
- return OK;
-
- if (!method_restricted)
- return OK;
-
- if (!application_id) {
- ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
- "shib_auth_checker: Shib-Application-ID header not found in request");
- return HTTP_FORBIDDEN;
- }
- else if (!application) {
- ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
- "shib_auth_checker: unable to map request to application settings, check configuration");
- return HTTP_FORBIDDEN;
- }
+ if (auth_all_OK || !method_restricted)
+ return true;
- ShibMLP markupProcessor;
- markupProcessor.insert("requestURL", ap_construct_url(r->pool,r->unparsed_uri,r));
- return shib_error_page(r, application, "access", markupProcessor);
+ return false;
}
-#endif /* 0 */
#ifndef SHIB_APACHE_13
/*
*/
extern "C" apr_status_t shib_exit(void* data)
{
- ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,0,NULL,"shib_exit() done\n");
+ if (g_Config) {
+ g_Config->term();
+ g_Config = NULL;
+ }
+ ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,0,NULL,"shib_exit() done");
return OK;
}
#endif
+// Initial look at a request - create the per-request structure
+static int shib_post_read(request_rec *r)
+{
+ shib_request_config* rc = init_request_config(r);
+
+ ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_post_read: E=%s", rc->env?"env":"hdr");
+
+#ifdef SHIB_DEFERRED_HEADERS
+ rc->hdr_out = ap_make_table(r->pool, 5);
+ rc->hdr_err = ap_make_table(r->pool, 5);
+#endif
+ return DECLINED;
+}
+
+// fixups: set environment vars
+
+extern "C" int shib_fixups(request_rec* r)
+{
+ shib_request_config *rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
+ shib_dir_config *dc = (shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib);
+ if (dc->bOff==1 || dc->bUseEnvVars==0)
+ return DECLINED;
+
+ ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_fixup(%d): ENTER", (int)getpid());
+
+ if (rc==NULL || rc->env==NULL || ap_is_empty_table(rc->env))
+ return DECLINED;
+
+ ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_fixup adding %d vars", ap_table_elts(rc->env)->nelts);
+ r->subprocess_env = ap_overlay_tables(r->pool, r->subprocess_env, rc->env);
+
+ return OK;
+}
+
/*
* shib_child_exit()
* Cleanup the (per-process) pool info.
#endif
ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit(%d) dealing with g_Config..", (int)getpid());
- g_Config->shutdown();
+ g_Config->term();
g_Config = NULL;
- ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit() done\n");
+ ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit() done");
#ifndef SHIB_APACHE_13
return OK;
exit(1);
}
+ g_Config=&SPConfig::getConfig();
+ g_Config->setFeatures(
+ SPConfig::Listener |
+ SPConfig::Caching |
+ SPConfig::RequestMapping |
+ SPConfig::InProcess |
+ SPConfig::Logging
+ );
+ if (!g_Config->init(g_szSchemaDir)) {
+ ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize libraries");
+ exit(1);
+ }
+ g_Config->AccessControlManager.registerFactory(HT_ACCESS_CONTROL,&htAccessFactory);
+ g_Config->RequestMapperManager.registerFactory(NATIVE_REQUEST_MAPPER,&ApacheRequestMapFactory);
+
try {
- g_Config=&ShibTargetConfig::getConfig();
- g_Config->setFeatures(
- ShibTargetConfig::Listener |
- ShibTargetConfig::Metadata |
- ShibTargetConfig::AAP |
- ShibTargetConfig::RequestMapper |
- ShibTargetConfig::LocalExtensions |
- ShibTargetConfig::Logging
- );
- if (!g_Config->init(g_szSchemaDir,g_szSHIBConfig)) {
- ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize SHIB Target");
- exit(1);
- }
+ xercesc::DOMDocument* dummydoc=XMLToolingConfig::getConfig().getParser().newDocument();
+ XercesJanitor<xercesc::DOMDocument> docjanitor(dummydoc);
+ xercesc::DOMElement* dummy = dummydoc->createElementNS(NULL,path);
+ auto_ptr_XMLCh src(g_szSHIBConfig);
+ dummy->setAttributeNS(NULL,path,src.get());
+ dummy->setAttributeNS(NULL,validate,xmlconstants::XML_ONE);
+
+ g_Config->setServiceProvider(g_Config->ServiceProviderManager.newPlugin(XML_SERVICE_PROVIDER,dummy));
+ g_Config->getServiceProvider()->init();
+ }
+ catch (exception& ex) {
+ ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),ex.what());
+ ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to load configuration");
+ exit(1);
}
- catch (...) {
- ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize SHIB Target");
- exit (1);
+
+ ServiceProvider* sp=g_Config->getServiceProvider();
+ xmltooling::Locker locker(sp);
+ const PropertySet* props=sp->getPropertySet("Local");
+ if (props) {
+ pair<bool,const char*> unsetValue=props->getString("unsetHeaderValue");
+ if (unsetValue.first)
+ g_unsetHeaderValue = unsetValue.second;
}
// Set the cleanup handler
ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() done");
}
+// Output filters
+#ifdef SHIB_DEFERRED_HEADERS
+static void set_output_filter(request_rec *r)
+{
+ ap_add_output_filter("SHIB_HEADERS_OUT", NULL, r, r->connection);
+}
+
+static void set_error_filter(request_rec *r)
+{
+ ap_add_output_filter("SHIB_HEADERS_ERR", NULL, r, r->connection);
+}
+
+static int _table_add(void *v, const char *key, const char *value)
+{
+ apr_table_addn((apr_table_t*)v, key, value);
+ return 1;
+}
+
+static apr_status_t do_output_filter(ap_filter_t *f, apr_bucket_brigade *in)
+{
+ request_rec *r = f->r;
+ shib_request_config *rc = (shib_request_config*) ap_get_module_config(r->request_config, &mod_shib);
+
+ if (rc) {
+ ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_out_filter: merging %d headers", apr_table_elts(rc->hdr_out)->nelts);
+ apr_table_do(_table_add,r->headers_out, rc->hdr_out,NULL);
+ // can't use overlap call because it will collapse Set-Cookie headers
+ //apr_table_overlap(r->headers_out, rc->hdr_out, APR_OVERLAP_TABLES_MERGE);
+ }
+
+ /* remove ourselves from the filter chain */
+ ap_remove_output_filter(f);
+
+ /* send the data up the stack */
+ return ap_pass_brigade(f->next,in);
+}
+
+static apr_status_t do_error_filter(ap_filter_t *f, apr_bucket_brigade *in)
+{
+ request_rec *r = f->r;
+ shib_request_config *rc = (shib_request_config*) ap_get_module_config(r->request_config, &mod_shib);
+
+ if (rc) {
+ ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_err_filter: merging %d headers", apr_table_elts(rc->hdr_err)->nelts);
+ apr_table_do(_table_add,r->err_headers_out, rc->hdr_err,NULL);
+ // can't use overlap call because it will collapse Set-Cookie headers
+ //apr_table_overlap(r->err_headers_out, rc->hdr_err, APR_OVERLAP_TABLES_MERGE);
+ }
+
+ /* remove ourselves from the filter chain */
+ ap_remove_output_filter(f);
+
+ /* send the data up the stack */
+ return ap_pass_brigade(f->next,in);
+}
+#endif // SHIB_DEFERRED_HEADERS
+
typedef const char* (*config_fn_t)(void);
#ifdef SHIB_APACHE_13
// SHIB Module commands
static command_rec shire_cmds[] = {
- {"SHIREConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
- RSRC_CONF, TAKE1, "Path to shibboleth.xml config file."},
{"ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
- RSRC_CONF, TAKE1, "Path to shibboleth.xml config file."},
+ RSRC_CONF, TAKE1, "Path to shibboleth.xml config file"},
+ {"ShibCatalogs", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
+ RSRC_CONF, TAKE1, "Paths of XML schema catalogs"},
{"ShibSchemaDir", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
- RSRC_CONF, TAKE1, "Path to Shibboleth XML schema directory."},
+ RSRC_CONF, TAKE1, "Paths of XML schema catalogs (deprecated in favor of ShibCatalogs)"},
{"ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
(void *) XtOffsetOf (shib_server_config, szScheme),
- RSRC_CONF, TAKE1, "URL scheme to force into generated URLs for a vhost."},
+ RSRC_CONF, TAKE1, "URL scheme to force into generated URLs for a vhost"},
+ {"ShibDisable", (config_fn_t)ap_set_flag_slot,
+ (void *) XtOffsetOf (shib_dir_config, bOff),
+ OR_AUTHCFG, FLAG, "Disable all Shib module activity here to save processing effort"},
+ {"ShibApplicationId", (config_fn_t)ap_set_string_slot,
+ (void *) XtOffsetOf (shib_dir_config, szApplicationId),
+ OR_AUTHCFG, TAKE1, "Set Shibboleth applicationId property for content"},
{"ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
(void *) XtOffsetOf (shib_dir_config, bBasicHijack),
- OR_AUTHCFG, FLAG, "Respond to AuthType Basic and convert to shib?"},
+ OR_AUTHCFG, FLAG, "Respond to AuthType Basic and convert to shibboleth"},
{"ShibRequireSession", (config_fn_t)ap_set_flag_slot,
(void *) XtOffsetOf (shib_dir_config, bRequireSession),
- OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist."},
+ OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist"},
+ {"ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
+ (void *) XtOffsetOf (shib_dir_config, szRequireWith),
+ OR_AUTHCFG, TAKE1, "Initiates a new session if one does not exist using a specific SessionInitiator"},
{"ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
(void *) XtOffsetOf (shib_dir_config, bExportAssertion),
- OR_AUTHCFG, FLAG, "Export SAML assertion to Shibboleth-defined header?"},
+ OR_AUTHCFG, FLAG, "Export SAML attribute assertion(s) to Shib-Attributes header"},
+ {"ShibRedirectToSSL", (config_fn_t)ap_set_string_slot,
+ (void *) XtOffsetOf (shib_dir_config, szRedirectToSSL),
+ OR_AUTHCFG, TAKE1, "Redirect non-SSL requests to designated port" },
{"AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
(void *) XtOffsetOf (shib_dir_config, szAuthGrpFile),
OR_AUTHCFG, TAKE1, "text file containing group names and member user IDs"},
{"ShibRequireAll", (config_fn_t)ap_set_flag_slot,
(void *) XtOffsetOf (shib_dir_config, bRequireAll),
- OR_AUTHCFG, FLAG, "All require directives must match!"},
+ OR_AUTHCFG, FLAG, "All require directives must match"},
+ {"ShibUseEnvironment", (config_fn_t)ap_set_flag_slot,
+ (void *) XtOffsetOf (shib_dir_config, bUseEnvVars),
+ OR_AUTHCFG, FLAG, "Export data in environment instead of headers (default)"},
{NULL}
};
extern "C"{
handler_rec shib_handlers[] = {
- { "shib-shire-post", shib_post_handler },
+ { "shib-handler", shib_handler },
{ NULL }
};
shib_auth_checker, /* check auth */
NULL, /* check access */
NULL, /* type_checker */
- NULL, /* fixups */
+ shib_fixups, /* fixups */
NULL, /* logger */
NULL, /* header parser */
shib_child_init, /* child_init */
shib_child_exit, /* child_exit */
- NULL /* post read-request */
+ shib_post_read /* post read-request */
};
-#elif defined(SHIB_APACHE_20)
+#elif defined(SHIB_APACHE_20) || defined(SHIB_APACHE_22)
extern "C" void shib_register_hooks (apr_pool_t *p)
{
+#ifdef SHIB_DEFERRED_HEADERS
+ ap_register_output_filter("SHIB_HEADERS_OUT", do_output_filter, NULL, AP_FTYPE_CONTENT_SET);
+ ap_hook_insert_filter(set_output_filter, NULL, NULL, APR_HOOK_LAST);
+ ap_register_output_filter("SHIB_HEADERS_ERR", do_error_filter, NULL, AP_FTYPE_CONTENT_SET);
+ ap_hook_insert_error_filter(set_error_filter, NULL, NULL, APR_HOOK_LAST);
+ ap_hook_post_read_request(shib_post_read, NULL, NULL, APR_HOOK_MIDDLE);
+#endif
ap_hook_child_init(shib_child_init, NULL, NULL, APR_HOOK_MIDDLE);
ap_hook_check_user_id(shib_check_user, NULL, NULL, APR_HOOK_MIDDLE);
ap_hook_auth_checker(shib_auth_checker, NULL, NULL, APR_HOOK_FIRST);
- ap_hook_handler(shib_post_handler, NULL, NULL, APR_HOOK_LAST);
+ ap_hook_handler(shib_handler, NULL, NULL, APR_HOOK_LAST);
+ ap_hook_fixups(shib_fixups, NULL, NULL, APR_HOOK_MIDDLE);
}
// SHIB Module commands
static command_rec shib_cmds[] = {
AP_INIT_TAKE1("ShibConfig",
(config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
- RSRC_CONF, "Path to shibboleth.xml config file."),
+ RSRC_CONF, "Path to shibboleth.xml config file"),
+ AP_INIT_TAKE1("ShibCatalogs",
+ (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
+ RSRC_CONF, "Paths of XML schema catalogs"),
AP_INIT_TAKE1("ShibSchemaDir",
(config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
- RSRC_CONF, "Path to Shibboleth XML schema directory."),
+ RSRC_CONF, "Paths of XML schema catalogs (deprecated in favor of ShibCatalogs)"),
AP_INIT_TAKE1("ShibURLScheme",
(config_fn_t)shib_set_server_string_slot,
(void *) offsetof (shib_server_config, szScheme),
- RSRC_CONF, "URL scheme to force into generated URLs for a vhost."),
-
+ RSRC_CONF, "URL scheme to force into generated URLs for a vhost"),
+
+ AP_INIT_FLAG("ShibDisable", (config_fn_t)ap_set_flag_slot,
+ (void *) offsetof (shib_dir_config, bOff),
+ OR_AUTHCFG, "Disable all Shib module activity here to save processing effort"),
+ AP_INIT_TAKE1("ShibApplicationId", (config_fn_t)ap_set_string_slot,
+ (void *) offsetof (shib_dir_config, szApplicationId),
+ OR_AUTHCFG, "Set Shibboleth applicationId property for content"),
AP_INIT_FLAG("ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
- (void *) offsetof (shib_dir_config, bBasicHijack),
- OR_AUTHCFG, "Respond to AuthType Basic and convert to shib?"),
+ (void *) offsetof (shib_dir_config, bBasicHijack),
+ OR_AUTHCFG, "Respond to AuthType Basic and convert to shibboleth"),
AP_INIT_FLAG("ShibRequireSession", (config_fn_t)ap_set_flag_slot,
- (void *) offsetof (shib_dir_config, bRequireSession),
- OR_AUTHCFG, "Initiates a new session if one does not exist."),
+ (void *) offsetof (shib_dir_config, bRequireSession),
+ OR_AUTHCFG, "Initiates a new session if one does not exist"),
+ AP_INIT_TAKE1("ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
+ (void *) offsetof (shib_dir_config, szRequireWith),
+ OR_AUTHCFG, "Initiates a new session if one does not exist using a specific SessionInitiator"),
AP_INIT_FLAG("ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
- (void *) offsetof (shib_dir_config, bExportAssertion),
- OR_AUTHCFG, "Export SAML assertion to Shibboleth-defined header?"),
+ (void *) offsetof (shib_dir_config, bExportAssertion),
+ OR_AUTHCFG, "Export SAML attribute assertion(s) to Shib-Attributes header"),
+ AP_INIT_TAKE1("ShibRedirectToSSL", (config_fn_t)ap_set_string_slot,
+ (void *) offsetof (shib_dir_config, szRedirectToSSL),
+ OR_AUTHCFG, "Redirect non-SSL requests to designated port"),
AP_INIT_TAKE1("AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
(void *) offsetof (shib_dir_config, szAuthGrpFile),
- OR_AUTHCFG, "text file containing group names and member user IDs"),
+ OR_AUTHCFG, "Text file containing group names and member user IDs"),
AP_INIT_FLAG("ShibRequireAll", (config_fn_t)ap_set_flag_slot,
- (void *) offsetof (shib_dir_config, bRequireAll),
- OR_AUTHCFG, "All require directives must match!"),
+ (void *) offsetof (shib_dir_config, bRequireAll),
+ OR_AUTHCFG, "All require directives must match"),
+ AP_INIT_FLAG("ShibUseEnvironment", (config_fn_t)ap_set_flag_slot,
+ (void *) offsetof (shib_dir_config, bUseEnvVars),
+ OR_AUTHCFG, "Export data in environment instead of headers (default)"),
{NULL}
};