diff --git a/Dockerfile.shared-httpd b/Dockerfile.shared-httpd index 6ef6e99..c63c1f7 100644 --- a/Dockerfile.shared-httpd +++ b/Dockerfile.shared-httpd @@ -3,6 +3,22 @@ # so the pkg-cache registry mirror can only serve content-addressed blobs. # Local builds use the tag. docs/pkg-cache.md "Base-image digest pinning". ARG BASE_IMAGE=almalinux/10-base + +# Build stage for mod_whp_proxy_guard (src/mod_whp_proxy_guard/): compiled +# against the distribution httpd-devel, so the runtime keeps the stock +# AlmaLinux httpd RPMs and their security updates. Only the .so (and the httpd +# version it was built against) reaches the image. +FROM ${BASE_IMAGE} AS modbuild-proxyguard +ARG PKG_CACHE= +COPY ./scripts/pkg-cache-repos.sh /usr/local/sbin/pkg-cache-repos.sh +COPY ./keys/pkg-cache/ /usr/local/share/pkg-cache/ +COPY ./src/mod_whp_proxy_guard/mod_whp_proxy_guard.c /src/mod_whp_proxy_guard.c +RUN /usr/local/sbin/pkg-cache-repos.sh rpm && \ + dnf update -y && \ + dnf install -y httpd-devel gcc redhat-rpm-config && \ + /usr/local/sbin/pkg-cache-repos.sh restore && \ + cd /src && apxs -Wc,-Wall -Wc,-Werror -c mod_whp_proxy_guard.c && \ + rpm -q --qf '%{VERSION}-%{RELEASE}' httpd-devel > /src/built-against FROM ${BASE_IMAGE} # OPTIONAL internal package cache, e.g. --build-arg PKG_CACHE=https://192.168.1.40 @@ -44,6 +60,18 @@ RUN openssl req -newkey rsa:2048 -nodes \ COPY ./configs/remote_ip.conf /etc/httpd/conf.d/ COPY ./configs/default-index.conf /etc/httpd/conf.d/ +# mod_whp_proxy_guard: request-time proxy allow list, .htaccess +# ProxyFCGISetEnvIf refusal, FastCGI env scrub and handler deny list +# (configs/whp-proxy-guard.conf). Loaded after mod_proxy (99-), which its +# scheme_handler hook needs. The build fails if the runtime httpd differs from +# the httpd-devel it was compiled against, or if the module does not load. +COPY --from=modbuild-proxyguard /src/.libs/mod_whp_proxy_guard.so /usr/lib64/httpd/modules/mod_whp_proxy_guard.so +COPY --from=modbuild-proxyguard /src/built-against /usr/lib64/httpd/modules/mod_whp_proxy_guard.built-against +COPY ./configs/whp-proxy-guard.conf /etc/httpd/conf.d/whp-proxy-guard.conf +RUN echo 'LoadModule whp_proxy_guard_module modules/mod_whp_proxy_guard.so' > /etc/httpd/conf.modules.d/99-whp-proxy-guard.conf && \ + test "$(rpm -q --qf '%{VERSION}-%{RELEASE}' httpd)" = "$(cat /usr/lib64/httpd/modules/mod_whp_proxy_guard.built-against)" && \ + httpd -t && httpd -M 2>/dev/null | grep -q ' whp_proxy_guard_module ' + # Create vhosts directory (will be volume-mounted from host) RUN mkdir -p /etc/httpd/conf.d/vhosts diff --git a/configs/whp-proxy-guard.conf b/configs/whp-proxy-guard.conf new file mode 100644 index 0000000..bc46ec5 --- /dev/null +++ b/configs/whp-proxy-guard.conf @@ -0,0 +1,29 @@ +# mod_whp_proxy_guard (src/mod_whp_proxy_guard/) - request-time proxy +# confinement for the shared tier. Loaded from +# conf.modules.d/99-whp-proxy-guard.conf. These are the image defaults for the +# main server; every vhost inherits them. WHP renders a per-vhost +# `WHPProxyAllow fcgi://-NN:9000 ...` (inside ), which replaces +# the default list for that vhost, and repeats the server-scope lines in its +# drop-in (conf.d/vhosts/000-whp-security.conf). + + # ProxyFCGISetEnvIf / ProxyFCGIBackendType in a tenant .htaccess (any + # nesting, included) is a configuration error for that directory. + # A nested tenant is merged after every server-scope section, so a + # tenant rule there overrode the vhost's SCRIPT_FILENAME pin. + WHPHtaccessProxyFCGI Deny + + # Removed from the request environment before any proxy scheme handler + # builds the backend's parameters (tenant SetEnv / SetEnvIf / [E=]). + WHPProxyScrubEnv PHP_VALUE PHP_ADMIN_VALUE PATH_TRANSLATED + + # Default allow list: FastCGI to port 9000 only (every WHP-rendered PHP + # handler). Blocks [P] / SetHandler "proxy:" to http, https, ws, ajp, + # scgi, uwsgi, unix sockets and other ports from any vhost that does not + # render its own, stricter list. + WHPProxyAllow fcgi://*:9000 + WHPProxyGuard On + + # Handlers no tenant may reach, whatever selects them (nested + # SetHandler, RewriteRule [H=...]). + WHPDenyHandler balancer-manager server-status application/x-httpd-status server-info lua-script cgi-script application/x-httpd-cgi + diff --git a/scripts/tests/whp-proxy-guard-module.test.sh b/scripts/tests/whp-proxy-guard-module.test.sh new file mode 100755 index 0000000..2349c71 --- /dev/null +++ b/scripts/tests/whp-proxy-guard-module.test.sh @@ -0,0 +1,187 @@ +#!/usr/bin/env bash +# whp-proxy-guard-module.test.sh - live probe of mod_whp_proxy_guard in a built +# shared-httpd image (src/mod_whp_proxy_guard, configs/whp-proxy-guard.conf). +# +# Usage: whp-proxy-guard-module.test.sh [image] (default shared-httpd:latest) +# Env: WHP_FPM_IMAGE a cac-fpm image for the FastCGI environment section +# (default repo.anhonesthost.net/cloud-hosting-platform/cac-fpm:php83; +# that section is SKIPPED, not failed, when it is absent) +# SKIPs (exit 0) without docker or without the image. +# +# Tenant vhosts a.test / b.test / l.test on a private docker network, an HTTP +# "target" (this image's httpd, counted in its access log) and, with +# WHP_FPM_IMAGE, a php-fpm container answering as a.test-01 and b.test-01. +set -u +IMAGE="${1:-shared-httpd:latest}" +FPM_IMAGE="${WHP_FPM_IMAGE:-repo.anhonesthost.net/cloud-hosting-platform/cac-fpm:php83}" +ID="whp-pg-$$"; NET="$ID-net"; H="$ID-httpd"; TG="$ID-tgt"; FP="$ID-fpm" +pass=0; fail=0 +ok() { pass=$((pass + 1)); printf ' ok %s\n' "$*"; } +bad() { fail=$((fail + 1)); printf ' FAIL %s\n' "$*"; } +skip() { printf 'SKIP whp-proxy-guard-module: %s\n' "$*"; exit 0; } +command -v docker >/dev/null 2>&1 || skip "no docker" +docker image inspect "$IMAGE" >/dev/null 2>&1 || skip "image $IMAGE not available" +T="$(mktemp -d)" +trap 'docker rm -f "$H" "$TG" "$FP" >/dev/null 2>&1; docker network rm "$NET" >/dev/null 2>&1; rm -rf "$T"' EXIT + +vhost() { # name user allow-line + cat < + Options SymLinksIfOwnerMatch + AllowOverride AuthConfig FileInfo Indexes Limit Options=Indexes,MultiViews,SymLinksIfOwnerMatch + Require all granted + + + ServerName $1 + DocumentRoot "/srv/$2" + SSLEngine on + SSLCertificateFile /etc/pki/tls/certs/localhost.crt + SSLCertificateKeyFile /etc/pki/tls/private/localhost.key + + SetHandler "proxy:fcgi://$2.test-01:9000" + + $3 + + ProxyFCGISetEnvIf "true" SCRIPT_FILENAME "/home/$2%{reqenv:SCRIPT_NAME}" + + +EOF +} +mkdir -p "$T/v" +vhost a.test a ' + WHPProxyAllow "fcgi://A.TEST-01:9000" + ' > "$T/v/a.conf" +vhost b.test b '' > "$T/v/b.conf" # inherits the image default list +vhost l.test l ' + WHPProxyGuard Log + WHPProxyAllow fcgi://l.test-01:9000 + ' > "$T/v/l.conf" +vhost n.test n ' + WHPProxyAllow None + ' > "$T/v/n.conf" + +cat > "$T/fx.sh" <<'EOF' +set -e +A=/srv/a; mkdir -p $A /srv/b /srv/l /srv/n; : > /srv/n/index.php +echo A-OWN > $A/own.txt; : > $A/index.php +mk() { mkdir -p "$A/$1"; printf "$2" > "$A/$1/.htaccess"; echo F > "$A/$1/f.txt"; } +SF='ProxyFCGISetEnvIf "true" SCRIPT_FILENAME "/home/b/admin.php"\n' +mk e0 "$SF" +mk e1 "\n$SF\n" +mk e2 "\n\n$SF\n\n" +mk e3 "\n\n\n$SF\n" +mk e4 "\n\n\n$SF\n\n\n" +mk e5 'ProxyFCGIBackendType GENERIC\n' +p() { mk "$1" "RewriteEngine on\nRewriteRule ^go\$ $2 [P]\n"; } +p t1 'fcgi://b.test-01:9000/home/b/admin.php' # another tenant's backend +p t2 'fcgi://a.test-01:9000/home/a/index.php' # own backend (case differs from the list) +p t3 'fcgi://a.test-01:9001/home/a/index.php' # own host, other port +p t4 'http://target.test/' # SSRF: http +p t5 'ws://target.test/' +p t6 'ajp://target.test:80/' +p t7 'fcgi://TGTIP:9000/home/b/admin.php' # another backend by IP +mk t8 '\n\nSetHandler "proxy:http://target.test/"\n\n\n' +mk t9 '\nSetHandler "proxy:unix:/run/httpd/cgisock|http://localhost/"\n\n' +mk h1 '\n\nSetHandler balancer-manager\n\n\n' +mk h2 'RewriteEngine on\nRewriteRule ^ - [H=server-status]\n' +mk h3 'SetHandler lua-script\n' +mk h4 '\n\nSetHandler application/x-httpd-cgi\n\n\n' +mk h5 'RewriteEngine on\nRewriteRule ^ - [H=application/x-httpd-status]\n' +mk c1 '\nSetHandler none\nSetHandler default-handler\n\n' +mk c2 'RewriteEngine on\nRewriteRule ^pretty$ f.txt [L]\nHeader set X-T 1\nSetEnvIf User-Agent . X=1\n' +mkdir -p /srv/l/lg; printf 'RewriteEngine on\nRewriteRule ^go$ http://target.test/ [P]\n' > /srv/l/lg/.htaccess +chmod -R a+rX /srv +EOF + +docker network create "$NET" >/dev/null || skip "could not create a docker network" +docker run -d --name "$TG" --network "$NET" --network-alias target.test --entrypoint sh "$IMAGE" \ + -c 'echo TARGET > /var/www/html/index.html; exec httpd -DFOREGROUND' >/dev/null || skip "could not start the target" +fpm=0; BK="$TG" +if docker image inspect "$FPM_IMAGE" >/dev/null 2>&1 && + docker run -d --name "$FP" --network "$NET" --network-alias a.test-01 --network-alias b.test-01 \ + --entrypoint sleep "$FPM_IMAGE" infinity >/dev/null 2>&1; then + fpm=1; BK="$FP" + docker exec "$FP" sh -c ' + mkdir -p /home/a /home/b /run/php-fpm + echo A-INDEX > /home/a/index.php; echo A-OTHER > /home/a/other.php; echo PREPENDED > /home/a/pre.txt + echo B-ADMIN > /home/b/admin.php; chmod -R a+rX /home + printf "[w]\nuser=nobody\ngroup=nobody\nlisten=0.0.0.0:9000\npm=static\npm.max_children=1\n" > /etc/php-fpm.d/www.conf + php-fpm -D' >/dev/null 2>&1 +fi +TGTIP="$(docker inspect -f "{{(index .NetworkSettings.Networks \"$NET\").IPAddress}}" "$BK")" +sed -i "s/TGTIP/$TGTIP/" "$T/fx.sh" + +docker run -d --name "$H" --network "$NET" "$IMAGE" >/dev/null || skip "could not start $IMAGE" +sleep 3 +docker cp "$T/v/." "$H:/etc/httpd/conf.d/vhosts/" >/dev/null +docker exec "$H" sh -c 'grep -q "conf.d/vhosts" /etc/httpd/conf/httpd.conf /etc/httpd/conf.d/*.conf 2>/dev/null || echo "IncludeOptional conf.d/vhosts/*.conf" > /etc/httpd/conf.d/zz-vhosts.conf' +docker cp "$T/fx.sh" "$H:/fx.sh" >/dev/null +docker exec "$H" bash /fx.sh || { bad "fixtures"; exit 1; } +docker exec "$H" sh -c 'httpd -M 2>/dev/null' | grep -q ' whp_proxy_guard_module ' && ok "module loaded" || bad "module not loaded" +docker exec "$H" httpd -t >/dev/null 2>&1 && ok "httpd -t" || { bad "httpd -t"; docker exec "$H" httpd -t 2>&1 | tail -3; exit 1; } +docker exec "$H" httpd -k graceful >/dev/null 2>&1; sleep 3 + +get() { # host path -> " " + docker exec "$H" sh -c "curl -sk --http1.1 --max-time 15 --resolve $1:443:127.0.0.1 -o /tmp/o -w '%{http_code} ' 'https://$1$2'; head -c 60 /tmp/o | tr '\n' '~'" 2>/dev/null +} +code() { local r; r="$(get "$2" "$3")"; [ "${r%% *}" = "$4" ] && ok "$1 -> $4" || bad "$1 -> got '${r:0:50}', want $4"; } +notcode() { local r; r="$(get "$2" "$3")"; [ "${r%% *}" != "$4" ] && ok "$1 -> ${r%% *} (not $4)" || bad "$1 -> $4"; } +hits() { docker exec "$TG" sh -c 'cat /var/log/httpd/access_log 2>/dev/null | wc -l' 2>/dev/null || echo 0; } + +echo "== .htaccess ProxyFCGISetEnvIf / ProxyFCGIBackendType refused in every nesting (WHPHtaccessProxyFCGI Deny)" +for c in "e0|plain" "e1|" "e2|" "e3|" "e4|" "e5|ProxyFCGIBackendType"; do + code "${c#*|}" a.test "/${c%%|*}/f.txt" 500 +done +docker exec "$H" sh -c 'grep -q "ProxyFCGISetEnvIf is not allowed in .htaccess on this server (whp_proxy_guard)" /var/log/httpd/*error*log' \ + && ok "refusal is logged with the module name" || bad "refusal not logged" + +echo "== proxy allow list (scheme_handler hook)" +code "[P] another tenant's backend (not on a.test's list)" a.test /t1/go 403 +notcode "[P] own backend (host case differs from the list)" a.test /t2/go 403 +code "[P] own host, other port" a.test /t3/go 403 +h0=$(hits) +code "[P] http:// SSRF" a.test /t4/go 403 +code "[P] ws:// SSRF" a.test /t5/go 403 +code "[P] ajp:// SSRF" a.test /t6/go 403 +code "[P] backend by IP address" a.test /t7/go 403 +code " SetHandler proxy:http://" a.test /t8/f.txt 403 +[ "$(hits)" = "$h0" ] && ok "the SSRF target saw no request" || bad "the SSRF target was reached" +r="$(get a.test /t9/f.txt)"; case "$r" in 403*|"200 F"*) ok "SetHandler proxy:unix: -> ${r:0:3} (refused or not proxied)" ;; *) bad "proxy:unix: -> ${r:0:40}" ;; esac +code "vhost without a list inherits the image default: [P] http://" b.test /t4/go 404 # no /t4 under /srv/b +docker exec "$H" sh -c 'mkdir -p /srv/b/t; printf "RewriteEngine on\nRewriteRule ^go\$ http://target.test/ [P]\nRewriteRule ^gf\$ fcgi://b.test-01:9000/home/b/admin.php [P]\n" > /srv/b/t/.htaccess; chmod -R a+rX /srv/b' +code " ... b.test [P] http:// (default list is fcgi on :9000 only)" b.test /t/go 403 +notcode " ... b.test [P] fcgi://b.test-01:9000 (default list)" b.test /t/gf 403 +r="$(get l.test /lg/go)"; [ "${r%% *}" != 403 ] && ok "WHPProxyGuard Log does not refuse (${r%% *})" || bad "Log mode refused" +docker exec "$H" sh -c 'grep -q "whp_proxy_guard: proxy target http://target.test:80 is not in the allow list of virtual host l.test .*(log only)" /var/log/httpd/*error*log' \ + && ok "Log mode logs the target" || bad "Log mode did not log" + +code "WHPProxyAllow None: even the vhost's own .php handler is refused" n.test /index.php 403 + +echo "== denied handlers (WHPDenyHandler)" +code " SetHandler balancer-manager" a.test /h1/f.txt 403 +code "RewriteRule [H=server-status]" a.test /h2/f.txt 403 +code "SetHandler lua-script" a.test /h3/f.txt 403 +code " SetHandler application/x-httpd-cgi (mod_cgid alias)" a.test /h4/f.txt 403 +code "[H=application/x-httpd-status] (mod_status alias)" a.test /h5/f.txt 403 + +echo "== compat" +code "static file" a.test /own.txt 200 +code "uploads idiom SetHandler none/default-handler" a.test /c1/f.txt 200 +code "RewriteRule / Header / SetEnvIf" a.test /c2/pretty 200 + +if [ "$fpm" = 1 ]; then + echo "== FastCGI environment (WHPProxyScrubEnv), own backend" + docker exec "$H" sh -c 'mkdir -p /srv/a/s1 /srv/a/s2; : > /srv/a/s1/index.php; : > /srv/a/s2/index.php + printf "SetEnv PHP_VALUE \"auto_prepend_file=/home/a/pre.txt\"\nRewriteEngine on\nRewriteRule ^go\$ index.php [E=PHP_ADMIN_VALUE:auto_prepend_file=/home/a/pre.txt]\n" > /srv/a/s1/.htaccess + printf "SetEnv PATH_TRANSLATED /home/a/other.php\nRewriteEngine on\nRewriteRule ^go\$ index.php\n" > /srv/a/s2/.htaccess + chmod -R a+rX /srv/a' + docker exec "$FP" sh -c 'mkdir -p /home/a/s1 /home/a/s2; echo S1-INDEX > /home/a/s1/index.php; echo S2-INDEX > /home/a/s2/index.php; chmod -R a+rX /home/a' + code "own .php reaches its backend" a.test /index.php 200 + r="$(get a.test /s1/go)"; case "$r" in *PREPENDED*) bad "PHP_VALUE / PHP_ADMIN_VALUE reached php-fpm -> ${r:0:40}" ;; "200 S1-INDEX"*) ok "SetEnv PHP_VALUE / [E=PHP_ADMIN_VALUE] scrubbed" ;; *) bad "s1 -> ${r:0:40}" ;; esac + r="$(get a.test /s2/go)"; case "$r" in *A-OTHER*) bad "tenant PATH_TRANSLATED chose the script -> ${r:0:40}" ;; "200 S2-INDEX"*) ok "SetEnv PATH_TRANSLATED + REDIRECT_URL scrubbed" ;; *) bad "s2 -> ${r:0:40}" ;; esac +else + echo " skip FastCGI environment section: $FPM_IMAGE not available" +fi + +if [ "$fail" -eq 0 ]; then echo "PASS whp-proxy-guard-module ($pass assertions)"; exit 0; fi +echo "FAIL whp-proxy-guard-module: $fail failed, $pass passed"; exit 1 diff --git a/src/mod_whp_proxy_guard/mod_whp_proxy_guard.c b/src/mod_whp_proxy_guard/mod_whp_proxy_guard.c new file mode 100644 index 0000000..b6bec95 --- /dev/null +++ b/src/mod_whp_proxy_guard/mod_whp_proxy_guard.c @@ -0,0 +1,410 @@ +/* + * mod_whp_proxy_guard - request-time proxy confinement for a shared Apache + * tier (stock distribution httpd, loadable module, no core patch). + * + * THE PROBLEM IT SOLVES + * On the shared tier every tenant's .htaccess may use FileInfo directives, + * which include `RewriteRule ... [P]`, `SetHandler "proxy:..."` and + * `ProxyFCGISetEnvIf`. httpd merges a tenant's nested `` sections AFTER + * every server-scope section (, inside , ...), so a + * config-only pin of SCRIPT_FILENAME / DOCUMENT_ROOT / PHP_VALUE can always + * be overridden by ` ProxyFCGISetEnvIf ...`. Combined + * with `[P]` to ANOTHER tenant's php-fpm backend that ran the other + * tenant's script under the other tenant's uid (measured, httpd 2.4.63). + * No section order can fix that; only a check that runs after all config + * is merged can. + * + * WHAT IT DOES (all three parts are independent of config merge order) + * + * 1. WHPProxyAllow / WHPProxyGuard Off|Log|On (server config only) + * A mod_proxy scheme_handler hook registered APR_HOOK_REALLY_FIRST. It + * runs once per backend attempt, after the per-dir config (every + * .htaccess and ) is merged, after mod_rewrite, after mod_proxy's + * balancer has picked a member and rewritten the URL to that member, and + * immediately before mod_proxy_fcgi / _http / _ajp / _wstunnel / ... open + * the connection. The connection target is taken from the same + * places mod_proxy takes it (the worker's or the request's UDS path, + * otherwise apr_uri_parse() of the URL the scheme handler receives) and + * compared with this virtual host's allow list. Not on the list: logged, + * and with `On` answered 403 before any byte reaches the backend. Every + * proxy scheme is covered (fcgi, http, https, ws, wss, ajp, scgi, uwsgi, + * fdpass, ftp, balancer members, unix: sockets), so the same check + * closes the "[P] to an arbitrary host:port" SSRF. + * WHPProxyAllow fcgi://site-01:9000 fcgi://site-02:9000 + * WHPProxyAllow unix:/run/php-fpm/site.sock + * WHPProxyAllow fcgi:// *:9000 (written without the space: any host, + * this scheme and port) + * A virtual host that sets its own list replaces the inherited one. + * WHPProxyGuard defaults to On where a list is in effect, Off otherwise. + * + * 2. WHPProxyScrubEnv VAR... (server config only) + * The same hook removes these variables from r->subprocess_env before + * the scheme handler builds the backend's environment. Anything a tenant + * set with SetEnv / SetEnvIf / RewriteRule [E=] is gone; the scheme + * handler then adds the standard CGI variables (SCRIPT_FILENAME, + * PATH_TRANSLATED for PATH_INFO, ...) itself, and applies the + * ProxyFCGISetEnvIf rules (server config only, see 3), so an + * administrator can still set a scrubbed variable on purpose. + * Intended list: PHP_VALUE PHP_ADMIN_VALUE (php-fpm applies them AND + * keeps them in the worker for later requests) and PATH_TRANSLATED + * (php-fpm's Apache-CGI fallback runs PATH_TRANSLATED instead of + * SCRIPT_FILENAME when REDIRECT_URL is set). + * + * 3. WHPHtaccessProxyFCGI Allow|Deny (server config only) + * With Deny, `ProxyFCGISetEnvIf` and `ProxyFCGIBackendType` in a + * .htaccess file (any nesting: plain, , , , + * , ...) are a configuration error for that directory (500, + * like any other directive the directory may not use). Mechanism, the + * same one mod_whp_symlink uses for `Options`: httpd 2.4 keeps, per + * directive name, a list of every module that declares it, most + * recently loaded first, and invokes each in turn + * (server/config.c ap_walk_config_sub); this module declares the two + * names too, is invoked before mod_proxy_fcgi, and returns an error in + * .htaccess context (no ACCESS_CONF/RSRC_CONF in cmd->override) or + * DECLINE_CMD everywhere else. mod_proxy_fcgi applies those rules inside + * its handler, after (2), so this is what keeps the administrator's + * SCRIPT_FILENAME / DOCUMENT_ROOT / PHP_VALUE rules the last word. + * + * 4. WHPDenyHandler name... (server config only) + * A handler hook registered APR_HOOK_REALLY_FIRST answers 403 when the + * request's final handler (after merging and RewriteRule [H=]) is + * one of these names, e.g. balancer-manager, server-status (and its + * application/x-httpd-status alias), server-info, lua-script, cgi-script + * (and application/x-httpd-cgi, which mod_cgid also runs). Same reason: + * the handler is chosen after every section a server-scope pin can live + * in. Compared case-insensitively. + * + * Nothing here changes a request whose virtual host has none of these + * directives in effect. + */ +#include "httpd.h" +#include "http_config.h" +#include "http_core.h" +#include "http_log.h" +#include "http_protocol.h" +#include "http_request.h" +#include "apr_strings.h" +#include "apr_uri.h" +#include "mod_proxy.h" + +module AP_MODULE_DECLARE_DATA whp_proxy_guard_module; + +#define MODE_UNSET -1 +#define MODE_OFF 0 +#define MODE_LOG 1 +#define MODE_ON 2 + +typedef struct { + const char *scheme; /* lower-case; "unix" for a socket path entry */ + const char *host; /* lower-case; "*" = any host */ + apr_port_t port; + const char *path; /* unix: entries only */ +} allow_entry; + +typedef struct { + int mode; + apr_array_header_t *allow; /* allow_entry, NULL = not set here */ + apr_array_header_t *scrub; /* const char *, NULL = not set here */ + apr_array_header_t *deny_handler;/* const char *, NULL = not set here */ + int htaccess_fcgi; /* MODE_UNSET / MODE_OFF (allow) / MODE_ON (deny) */ +} guard_srv; + +static void *create_srv(apr_pool_t *p, server_rec *s) +{ + guard_srv *c = apr_pcalloc(p, sizeof(*c)); + c->mode = MODE_UNSET; + c->htaccess_fcgi = MODE_UNSET; + return c; +} + +static void *merge_srv(apr_pool_t *p, void *b_, void *a_) +{ + guard_srv *b = b_, *a = a_, *c = apr_pcalloc(p, sizeof(*c)); + c->mode = a->mode != MODE_UNSET ? a->mode : b->mode; + c->allow = a->allow ? a->allow : b->allow; + c->scrub = a->scrub ? a->scrub : b->scrub; + c->deny_handler = a->deny_handler ? a->deny_handler : b->deny_handler; + c->htaccess_fcgi = a->htaccess_fcgi != MODE_UNSET ? a->htaccess_fcgi + : b->htaccess_fcgi; + return c; +} + +static int effective_mode(const guard_srv *c) +{ + if (c->mode != MODE_UNSET) + return c->mode; + /* A list that is set (even `WHPProxyAllow None`, i.e. empty) enforces. */ + return c->allow ? MODE_ON : MODE_OFF; +} + +/* ------------------------------------------------------------------ */ +/* configuration */ + +static const char *cmd_mode(cmd_parms *cmd, void *d, const char *arg) +{ + guard_srv *c = ap_get_module_config(cmd->server->module_config, + &whp_proxy_guard_module); + if (!strcasecmp(arg, "off")) + c->mode = MODE_OFF; + else if (!strcasecmp(arg, "log")) + c->mode = MODE_LOG; + else if (!strcasecmp(arg, "on")) + c->mode = MODE_ON; + else + return "WHPProxyGuard must be Off, Log or On"; + return NULL; +} + +static const char *cmd_allow(cmd_parms *cmd, void *d, const char *arg) +{ + guard_srv *c = ap_get_module_config(cmd->server->module_config, + &whp_proxy_guard_module); + allow_entry *e; + apr_uri_t u; + + if (!c->allow) + c->allow = apr_array_make(cmd->pool, 4, sizeof(allow_entry)); + if (!strcasecmp(arg, "none")) /* explicit empty list: deny every target */ + return NULL; + + e = apr_array_push(c->allow); + memset(e, 0, sizeof(*e)); + if (!strncasecmp(arg, "unix:", 5)) { + if (arg[5] != '/' || ap_strchr_c(arg, '|')) + return apr_psprintf(cmd->pool, "WHPProxyAllow: '%s' is not " + "unix:/absolute/socket/path", arg); + e->scheme = "unix"; + e->path = ap_runtime_dir_relative(cmd->pool, arg + 5); + return NULL; + } + /* A wildcard host ("*" between "://" and ":port") is not something + * apr_uri_parse() accepts for every scheme, so it is cut out by hand. */ + { + const char *sep = ap_strstr_c(arg, "://"); + const char *hp, *colon; + char *end; + long port; + if (!sep || sep == arg) + return apr_psprintf(cmd->pool, "WHPProxyAllow: '%s' is not " + "scheme://host[:port] or unix:/path", arg); + e->scheme = apr_pstrmemdup(cmd->pool, arg, sep - arg); + ap_str_tolower((char *)e->scheme); + hp = sep + 3; + if (hp[0] == '*' && (hp[1] == ':' || hp[1] == '\0')) { + e->host = "*"; + colon = hp + 1; + if (*colon == ':') { + port = strtol(colon + 1, &end, 10); + if (*end || port < 1 || port > 65535) + return apr_psprintf(cmd->pool, "WHPProxyAllow: bad port " + "in '%s'", arg); + e->port = (apr_port_t)port; + } + else { + e->port = ap_proxy_port_of_scheme(e->scheme); + } + } + else { + if (apr_uri_parse(cmd->pool, arg, &u) != APR_SUCCESS + || !u.hostname || !*u.hostname || u.user || u.password + || (u.path && strcmp(u.path, "/") && *u.path) + || u.query || u.fragment) + return apr_psprintf(cmd->pool, "WHPProxyAllow: '%s' is not " + "scheme://host[:port]", arg); + e->host = apr_pstrdup(cmd->pool, u.hostname); + ap_str_tolower((char *)e->host); + e->port = u.port_str ? u.port : ap_proxy_port_of_scheme(e->scheme); + } + if (!e->port) + return apr_psprintf(cmd->pool, "WHPProxyAllow: '%s' needs a port " + "(no default port for scheme %s)", arg, + e->scheme); + } + return NULL; +} + +static const char *cmd_scrub(cmd_parms *cmd, void *d, const char *arg) +{ + guard_srv *c = ap_get_module_config(cmd->server->module_config, + &whp_proxy_guard_module); + if (!c->scrub) + c->scrub = apr_array_make(cmd->pool, 4, sizeof(const char *)); + if (strcasecmp(arg, "none")) + *(const char **)apr_array_push(c->scrub) = arg; + return NULL; +} + +static const char *cmd_deny_handler(cmd_parms *cmd, void *d, const char *arg) +{ + guard_srv *c = ap_get_module_config(cmd->server->module_config, + &whp_proxy_guard_module); + if (!c->deny_handler) + c->deny_handler = apr_array_make(cmd->pool, 8, sizeof(const char *)); + if (strcasecmp(arg, "none")) + *(const char **)apr_array_push(c->deny_handler) = arg; + return NULL; +} + +static const char *cmd_htaccess_fcgi(cmd_parms *cmd, void *d, const char *arg) +{ + guard_srv *c = ap_get_module_config(cmd->server->module_config, + &whp_proxy_guard_module); + if (!strcasecmp(arg, "allow")) + c->htaccess_fcgi = MODE_OFF; + else if (!strcasecmp(arg, "deny")) + c->htaccess_fcgi = MODE_ON; + else + return "WHPHtaccessProxyFCGI must be Allow or Deny"; + return NULL; +} + +/* .htaccess context: cmd->override never carries ACCESS_CONF / RSRC_CONF + * there (core.c ifsection keeps the .htaccess overrides for a nested ). */ +static int is_htaccess(cmd_parms *cmd) +{ + return !(cmd->override & (ACCESS_CONF | RSRC_CONF)); +} + +static const char *htaccess_fcgi_gate(cmd_parms *cmd, void *d, const char *args) +{ + guard_srv *c; + if (!is_htaccess(cmd)) + return DECLINE_CMD; + c = ap_get_module_config(cmd->server->module_config, + &whp_proxy_guard_module); + if (c->htaccess_fcgi == MODE_ON) + return apr_pstrcat(cmd->pool, cmd->cmd->name, " is not allowed in " + ".htaccess on this server (whp_proxy_guard)", NULL); + return DECLINE_CMD; +} + +/* ------------------------------------------------------------------ */ +/* request time */ + +static int target_allowed(request_rec *r, const guard_srv *c, + proxy_worker *worker, const char *url, + const char **desc) +{ + const char *uds; + int i; + const allow_entry *e = c->allow ? (const allow_entry *)c->allow->elts : NULL; + int n = c->allow ? c->allow->nelts : 0; + + /* Same precedence as ap_proxy_determine_connection(). */ + uds = (worker && *worker->s->uds_path) ? worker->s->uds_path + : apr_table_get(r->notes, "uds_path"); + if (uds) { + *desc = apr_pstrcat(r->pool, "unix:", uds, NULL); + for (i = 0; i < n; i++) + if (e[i].path && !strcmp(e[i].path, uds)) + return 1; + return 0; + } + else { + apr_uri_t u; + const char *scheme; + apr_port_t port; + if (!url || apr_uri_parse(r->pool, url, &u) != APR_SUCCESS + || !u.scheme || !u.hostname || !*u.hostname) { + *desc = url ? url : "(none)"; + return 0; + } + scheme = apr_pstrdup(r->pool, u.scheme); + ap_str_tolower((char *)scheme); + port = u.port_str ? u.port : ap_proxy_port_of_scheme(scheme); + *desc = apr_psprintf(r->pool, "%s://%s:%u", scheme, u.hostname, + (unsigned)port); + for (i = 0; i < n; i++) { + if (e[i].path || strcmp(e[i].scheme, scheme) || e[i].port != port) + continue; + if (!strcmp(e[i].host, "*") || !strcasecmp(e[i].host, u.hostname)) + return 1; + } + return 0; + } +} + +static int guard_scheme_handler(request_rec *r, proxy_worker *worker, + proxy_server_conf *pconf, char *url, + const char *proxyhost, apr_port_t proxyport) +{ + guard_srv *c = ap_get_module_config(r->server->module_config, + &whp_proxy_guard_module); + const char *desc = NULL; + int mode; + + if (c->scrub) { + int i; + const char **v = (const char **)c->scrub->elts; + for (i = 0; i < c->scrub->nelts; i++) + apr_table_unset(r->subprocess_env, v[i]); + } + + mode = effective_mode(c); + if (mode == MODE_OFF) + return DECLINED; + if (target_allowed(r, c, worker, url, &desc)) + return DECLINED; + + ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, + "whp_proxy_guard: proxy target %s is not in the allow list " + "of virtual host %s (uri %s)%s", desc, + r->server->server_hostname ? r->server->server_hostname : "-", + r->uri, mode == MODE_ON ? " (refused)" : " (log only)"); + return mode == MODE_ON ? HTTP_FORBIDDEN : DECLINED; +} + +static int guard_handler(request_rec *r) +{ + guard_srv *c = ap_get_module_config(r->server->module_config, + &whp_proxy_guard_module); + int i; + const char **v; + + if (!c->deny_handler || !r->handler) + return DECLINED; + v = (const char **)c->deny_handler->elts; + for (i = 0; i < c->deny_handler->nelts; i++) { + if (!strcasecmp(r->handler, v[i])) { + ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, + "whp_proxy_guard: handler '%s' is denied in virtual " + "host %s (uri %s) (refused)", r->handler, + r->server->server_hostname ? r->server->server_hostname + : "-", r->uri); + return HTTP_FORBIDDEN; + } + } + return DECLINED; +} + +static const command_rec cmds[] = { + AP_INIT_TAKE1("WHPProxyGuard", cmd_mode, NULL, RSRC_CONF, + "Off | Log | On: enforce WHPProxyAllow for every proxied request"), + AP_INIT_ITERATE("WHPProxyAllow", cmd_allow, NULL, RSRC_CONF, + "proxy targets this virtual host may reach: scheme://host[:port], " + "scheme://*:port or unix:/path (None = nothing)"), + AP_INIT_ITERATE("WHPProxyScrubEnv", cmd_scrub, NULL, RSRC_CONF, + "environment variables removed before any proxy scheme handler runs"), + AP_INIT_ITERATE("WHPDenyHandler", cmd_deny_handler, NULL, RSRC_CONF, + "handler names answered 403 in this virtual host"), + AP_INIT_TAKE1("WHPHtaccessProxyFCGI", cmd_htaccess_fcgi, NULL, RSRC_CONF, + "Allow | Deny: ProxyFCGISetEnvIf / ProxyFCGIBackendType in .htaccess"), + /* Same names and override class as mod_proxy_fcgi; invoked first. */ + AP_INIT_RAW_ARGS("ProxyFCGISetEnvIf", htaccess_fcgi_gate, NULL, OR_FILEINFO, + "(whp_proxy_guard gate, see WHPHtaccessProxyFCGI)"), + AP_INIT_RAW_ARGS("ProxyFCGIBackendType", htaccess_fcgi_gate, NULL, OR_FILEINFO, + "(whp_proxy_guard gate, see WHPHtaccessProxyFCGI)"), + {NULL} +}; + +static void register_hooks(apr_pool_t *p) +{ + proxy_hook_scheme_handler(guard_scheme_handler, NULL, NULL, + APR_HOOK_REALLY_FIRST); + ap_hook_handler(guard_handler, NULL, NULL, APR_HOOK_REALLY_FIRST); +} + +AP_DECLARE_MODULE(whp_proxy_guard) = { + STANDARD20_MODULE_STUFF, + NULL, NULL, create_srv, merge_srv, cmds, register_hooks +};