From c91187aa85b8600816512828a9dad9d83b1b5761 Mon Sep 17 00:00:00 2001 From: Josh Knapp Date: Thu, 19 Nov 2026 16:34:52 -0800 Subject: [PATCH] fix(wp-admin gate): exempt the WordPress install screens (setup-config.php, install.php) A fresh WordPress with no wp-config.php redirects every request to /wp-admin/setup-config.php. The edge wp-admin gate bounced that cookieless request to wp-login.php?redirect_to=/wp-admin/setup-config.php, which then tripped CRS 930120 ("config.php" in ARGS:redirect_to) and showed the WAF block page: manual installers never saw WordPress's setup screen. New ACL wp_admin_install (path_end, exact /wp-admin/setup-config.php and /wp-admin/install.php on the normalised path, case-sensitive) added as a negated exclusion on the redirect rule. upgrade.php stays gated (only logged-in users are sent there). Variants (.php.php, .phpx, case, path info, inserted directory, dotdot/encoded escapes) stay gated; encoded separators still deny. Tests: the structural suite now pins the new ACL; new test-wpadmin-gate-behaviour.py runs the real gate rules in the real haproxy and sends raw requests (run by the image build). VERSION 2026.11.7. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_0185ukXi4YX5FxJGqhi6qab6 --- Dockerfile | 1 + VERSION | 2 +- scripts/test-wpadmin-gate-behaviour.py | 226 +++++++++++++++++++++++++ scripts/test-wpadmin-gate.py | 19 ++- templates/hap_listener.tpl | 31 +++- 5 files changed, 269 insertions(+), 10 deletions(-) create mode 100644 scripts/test-wpadmin-gate-behaviour.py diff --git a/Dockerfile b/Dockerfile index c0d8611..85732c2 100644 --- a/Dockerfile +++ b/Dockerfile @@ -147,6 +147,7 @@ RUN pip install -r requirements.txt # The unit suites run here too. They had never run anywhere automated either, # and they cost a few seconds. RUN python3 /haproxy/scripts/test-wpadmin-gate.py \ + && python3 /haproxy/scripts/test-wpadmin-gate-behaviour.py \ && python3 /haproxy/scripts/test-trusted-proxy-gate.py \ && python3 /haproxy/scripts/test-xmlrpc-rate-limit.py \ && python3 /haproxy/scripts/test-default-splash.py \ diff --git a/VERSION b/VERSION index 5b0a96a..04a6e38 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -2026.11.6 +2026.11.7 diff --git a/scripts/test-wpadmin-gate-behaviour.py b/scripts/test-wpadmin-gate-behaviour.py new file mode 100644 index 0000000..2ddd7a4 --- /dev/null +++ b/scripts/test-wpadmin-gate-behaviour.py @@ -0,0 +1,226 @@ +#!/usr/bin/env python3 +"""BEHAVIOURAL test of the wp-admin edge gate against the REAL haproxy binary. + +test-wpadmin-gate.py asserts on the TEXT of the rendered config. This file runs +the actual gate rules (extracted from the rendered hap_listener.tpl, not +re-typed) in a real haproxy and sends real requests, so the install-screen +exemption and its path-normalisation edge cases are measured, not inferred. + +Only the exclusion ACLs that depend on the client address (is_local, +is_trusted_ip, is_whitelisted) are stubbed to never match: the test client is +127.0.0.1, which the real is_local would exempt wholesale. Everything else +(normalize-uri chain, wp_admin_* ACLs, deny rules, set-var, redirect) is the +production text. + +A request that PASSES the gate gets 200 "ok" from a stub `http-request return`; +a gated one gets the edge 302 (Location: .../wp-login.php?redirect_to=...) or +the 403 deny. + +Skips (exit 0, loud message) when no `haproxy` binary is on PATH. The Dockerfile +build has one, so the image build always runs it. + + python3 scripts/test-wpadmin-gate-behaviour.py +""" + +import os +import re +import shutil +import socket +import subprocess +import sys +import tempfile +import time +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +os.environ.setdefault('HAPROXY_MANAGER_DIR', os.path.abspath(os.path.join(HERE, '..'))) + +import importlib.util # noqa: E402 + +_spec = importlib.util.spec_from_file_location( + 'wpadmin_gate_tests', os.path.join(HERE, 'test-wpadmin-gate.py')) +gate = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(gate) + +HAPROXY = shutil.which('haproxy') + +# Code lines (comment-stripped) that make up the gate, in template order. +_KEEP = re.compile( + r'^(?:' + r'http-request normalize-uri ' + r'|acl (?:has_wp_logged_in|wp_gate_exempt|wp_admin_\w+|path_has_encoded_sep) ' + r'|http-request deny deny_status 403 if wp_admin' + r'|http-request set-var\(txn\.wp_login_url\) ' + r'|http-request redirect code 302 location %\[var\(txn\.wp_login_url\)\]' + r')') + +# (description, raw request path, extra header, expected status, location-prefix) +PASS, REDIR, DENY = 200, 302, 403 +LOGIN = '/wp-login.php?redirect_to=' + +CASES = [ + # --- the install/setup screens: exempt ------------------------------ + ('setup-config.php', '/wp-admin/setup-config.php', None, PASS, None), + ('setup-config.php language step', '/wp-admin/setup-config.php?step=-1', None, PASS, None), + ('install.php', '/wp-admin/install.php', None, PASS, None), + ('install.php step 2', '/wp-admin/install.php?step=2', None, PASS, None), + ('subdirectory install', '/blog/wp-admin/install.php', None, PASS, None), + ('subdirectory setup-config', '/blog/wp-admin/setup-config.php', None, PASS, None), + # spellings that NORMALISE to the exempt path are the same request to the backend + ('dotdot normalises to the exempt page', '/wp-admin/css/../setup-config.php', None, PASS, None), + ('encoded dot normalises to the exempt page', '/wp-admin/setup-config%2Ephp', None, PASS, None), + ('double slash merges to the exempt page', '//wp-admin/install.php', None, PASS, None), + # --- everything near them stays gated ------------------------------- + ('dashboard', '/wp-admin/', None, REDIR, LOGIN + '%2Fwp-admin%2F'), + ('index.php', '/wp-admin/index.php', None, REDIR, LOGIN), + ('upgrade.php is NOT exempt', '/wp-admin/upgrade.php', None, REDIR, LOGIN), + ('plugins.php', '/wp-admin/plugins.php', None, REDIR, LOGIN), + ('setup-config.php.php', '/wp-admin/setup-config.php.php', None, REDIR, LOGIN), + ('setup-config.phpx', '/wp-admin/setup-config.phpx', None, REDIR, LOGIN), + ('install.php.bak', '/wp-admin/install.php.bak', None, REDIR, LOGIN), + ('case variant Setup-Config.php', '/wp-admin/Setup-Config.php', None, REDIR, LOGIN), + ('case variant Install.php', '/wp-admin/Install.php', None, REDIR, LOGIN), + ('upper-case dir WP-ADMIN', '/WP-ADMIN/install.php', None, REDIR, LOGIN), + ('path info after the script', '/wp-admin/install.php/x', None, REDIR, LOGIN), + ('trailing slash', '/wp-admin/install.php/', None, REDIR, LOGIN), + ('inserted directory', '/wp-admin/evil/install.php', None, REDIR, LOGIN), + ('inserted directory (setup-config)', '/wp-admin/x/setup-config.php', None, REDIR, LOGIN), + ('dotdot climbs off the exempt page', '/wp-admin/install.php/../plugins.php', None, REDIR, LOGIN), + ('asset dir dotdot to plugins.php', '/wp-admin/css/../plugins.php', None, REDIR, LOGIN), + ('encoded slash separator', '/wp-admin%2Fsetup-config.php', None, DENY, None), + ('encoded slash before wp-admin', '/blog%2Fwp-admin/install.php', None, DENY, None), + ('backslash prefix (open redirect guard)', '/%5Cevil.example/wp-admin/plugins.php', None, DENY, None), + # --- identity still passes ------------------------------------------ + ('logged-in cookie on plugins.php', '/wp-admin/plugins.php', + 'Cookie: wordpress_logged_in_abc=1', PASS, None), +] + + +def _free_port(): + s = socket.socket() + s.bind(('127.0.0.1', 0)) + port = s.getsockname()[1] + s.close() + return port + + +def _raw_get(port, path, header=None): + req = 'GET %s HTTP/1.1\r\nHost: site.example.com\r\nConnection: close\r\n' % path + if header: + req += header + '\r\n' + req += '\r\n' + with socket.create_connection(('127.0.0.1', port), timeout=5) as s: + s.sendall(req.encode('latin-1')) + buf = b'' + while True: + chunk = s.recv(4096) + if not chunk: + break + buf += chunk + head = buf.split(b'\r\n\r\n', 1)[0].decode('latin-1') + lines = head.split('\r\n') + status = int(lines[0].split()[1]) + loc = None + for ln in lines[1:]: + if ln.lower().startswith('location:'): + loc = ln.split(':', 1)[1].strip() + return status, loc + + +@unittest.skipUnless(HAPROXY, 'SKIP: no haproxy binary on PATH (the image build has one)') +class WpAdminGateBehaviour(unittest.TestCase): + + @classmethod + def setUpClass(cls): + cfg = gate.render_listener() + lines = [] + for raw in cfg.split('\n'): + stripped = raw.strip() + if not stripped or stripped.startswith('#'): + continue + code = stripped.split(' #', 1)[0].rstrip() + if _KEEP.match(code): + lines.append(code) + joined = '\n'.join(lines) + # Guard against a silently empty extraction: every moving part must be there. + for needle in ('normalize-uri path-strip-dotdot full', 'acl wp_admin_install', + 'acl wp_admin_allowed', 'acl wp_admin_asset', 'acl wp_gate_exempt', + 'acl has_wp_logged_in', 'acl path_has_encoded_sep', + 'set-var(txn.wp_login_url)', 'http-request redirect code 302'): + assert needle in joined, 'extraction lost %r' % needle + + cls.tmp = tempfile.mkdtemp(prefix='wpgate-behaviour-') + exempt = os.path.join(cls.tmp, 'exempt.list') + open(exempt, 'w').close() + joined = joined.replace('/etc/haproxy/wpadmin_gate_exempt.list', exempt) + cls.port = _free_port() + conf = '\n'.join([ + 'global', + ' expose-experimental-directives', + ' maxconn 100', + 'defaults', + ' mode http', + ' timeout connect 2s', + ' timeout client 5s', + ' timeout server 5s', + 'frontend gate', + ' bind 127.0.0.1:%d' % cls.port, + # client-address exclusions stubbed: the real is_local would match 127.0.0.1 + ' acl is_local src 203.0.113.1', + ' acl is_trusted_ip src 203.0.113.2', + ' acl is_whitelisted src 203.0.113.3', + ' ' + joined.replace('\n', '\n '), + ' http-request return status 200 content-type text/plain string ok', + '', + ]) + cls.conf_path = os.path.join(cls.tmp, 'gate.cfg') + with open(cls.conf_path, 'w') as f: + f.write(conf) + chk = subprocess.run([HAPROXY, '-c', '-f', cls.conf_path], + capture_output=True, text=True) + assert chk.returncode == 0, 'haproxy -c rejected the gate:\n' + chk.stdout + chk.stderr + cls.proc = subprocess.Popen([HAPROXY, '-db', '-f', cls.conf_path], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + for _ in range(50): + try: + socket.create_connection(('127.0.0.1', cls.port), timeout=0.2).close() + break + except OSError: + time.sleep(0.1) + else: + raise AssertionError('haproxy did not start listening') + + @classmethod + def tearDownClass(cls): + proc = getattr(cls, 'proc', None) + if proc: + proc.terminate() + try: + proc.wait(timeout=5) + except subprocess.TimeoutExpired: + proc.kill() + shutil.rmtree(getattr(cls, 'tmp', ''), ignore_errors=True) + + def test_cases(self): + for desc, path, header, want, loc_prefix in CASES: + with self.subTest(desc=desc, path=path): + status, loc = _raw_get(self.port, path, header) + self.assertEqual(status, want, '%s: %s -> %s %s' % (desc, path, status, loc)) + if loc_prefix is not None: + self.assertIsNotNone(loc, 'no Location header for ' + path) + self.assertTrue(loc.endswith(loc_prefix) or loc_prefix in loc, + '%s: Location %r' % (path, loc)) + # redirect must stay same-origin (open-redirect guard) + self.assertTrue(loc.startswith('/') and not loc.startswith('//'), loc) + + def test_nul_byte_after_exempt_name_is_not_exempt(self): + """%00 is not an unreserved escape, so it is not decoded and the path no + longer ends in the exempt name. Anything but a pass-through is fine + (gated 302, or haproxy refusing the request).""" + status, _ = _raw_get(self.port, '/wp-admin/setup-config.php%00') + self.assertNotEqual(status, PASS) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/scripts/test-wpadmin-gate.py b/scripts/test-wpadmin-gate.py index 8900c7c..227b1c2 100644 --- a/scripts/test-wpadmin-gate.py +++ b/scripts/test-wpadmin-gate.py @@ -59,7 +59,7 @@ import haproxy_manager # noqa: E402 ALLOWLIST = ('/admin-ajax.php', '/admin-post.php', '/load-styles.php', '/load-scripts.php') -EXCLUSIONS = ('!wp_admin_allowed', '!wp_admin_asset', '!has_wp_logged_in', +EXCLUSIONS = ('!wp_admin_allowed', '!wp_admin_install', '!wp_admin_asset', '!has_wp_logged_in', '!wp_gate_exempt', '!is_local', '!is_trusted_ip', '!is_whitelisted') # The normalizer set, in the order it MUST render. Decoding has to precede the @@ -220,10 +220,23 @@ class WpAdminGate(unittest.TestCase): line = require_rule(self.cfg, 'acl wp_admin_asset', 'wp_admin_asset ACL') self.assertRegex(line, r'path_reg.*\(css\|js\|images\)') - def test_install_php_is_NOT_allowlisted(self): - """install.php is deliberately gated -- a takeover vector on abandoned installs.""" + def test_install_php_is_not_in_the_ajax_allowlist(self): + """install.php / setup-config.php live in their OWN ACL (wp_admin_install), + not in wp_admin_allowed, so the admin-ajax/asset allowlist stays minimal.""" line = require_rule(self.cfg, 'acl wp_admin_allowed', 'wp_admin_allowed ACL') self.assertNotIn('install.php', line) + self.assertNotIn('setup-config.php', line) + + def test_install_screens_exempt_exactly_two_anchored_paths(self): + """A fresh WordPress redirects every request to /wp-admin/setup-config.php + and a manual installer has no cookie. Exactly these two pages are exempt, + each anchored to /wp-admin/ (path_end, no regex, no wildcard). + upgrade.php is deliberately NOT exempt (logged-in only).""" + line = require_rule(self.cfg, 'acl wp_admin_install', 'wp_admin_install ACL') + self.assertEqual(line.split(None, 3)[2], 'path_end') + entries = line.split()[3:] + self.assertEqual(sorted(entries), + ['/wp-admin/install.php', '/wp-admin/setup-config.php']) def test_redirect_rule_has_all_exclusions(self): rule = require_rule_by_predicate( diff --git a/templates/hap_listener.tpl b/templates/hap_listener.tpl index ccd850a..2560363 100644 --- a/templates/hap_listener.tpl +++ b/templates/hap_listener.tpl @@ -431,11 +431,29 @@ frontend web # suffix matching (/blog/wp-admin/admin-ajax.php ends with # /wp-admin/admin-ajax.php) while rejecting an inserted directory. # - # install.php is DELIBERATELY NOT allowlisted. It is legitimately - # reachable without a cookie during a fresh install, but it is also a - # standing scanner target and a real takeover vector on a site that was - # half-installed and then abandoned. Anyone genuinely installing uses the - # per-site exempt-list opt-out below instead. + # The WordPress install/setup screens ARE exempt (wp_admin_install below): + # exactly /wp-admin/setup-config.php and /wp-admin/install.php. A fresh + # WordPress with no wp-config.php redirects EVERY request to + # /wp-admin/setup-config.php, and a person doing a manual install has no + # cookie by definition -- gating those two pages bounced the installer to + # wp-login.php?redirect_to=/wp-admin/setup-config.php (a login form that + # can never succeed on a site with no database) and, worse, that URL then + # tripped CRS 930120 ("config.php" in ARGS:redirect_to) so the visitor saw + # the WAF block page instead of WordPress's own setup screen. WordPress + # itself refuses both once the site is installed (setup-config.php exits + # "wp-config.php already exists"; install.php shows "Already Installed" + # when the options table has siteurl), so the exemption exposes nothing on + # a finished site. RESIDUAL RISK (known tradeoff of exempting these two pages, requested 2026-11-19): a site that + # was half-installed and abandoned (wp-config.php present, tables not + # created) lets any visitor finish the install via install.php?step=2 and + # so choose the admin account. The old blanket gate happened to block that + # on edge-fronted sites; WordPress itself never did. Matching is exact (path_end on the normalised path, + # case-sensitive): /wp-admin/setup-config.php.php, /wp-admin/Install.php, + # /wp-admin/install.php/x, /wp-admin/evil/install.php are all still gated. + # upgrade.php is NOT exempt: WordPress only sends logged-in users there + # (admin_init), and a logged-in user carries the cookie, so it needs no + # exemption. The install screens' CSS/JS come from the css|js|images dirs + # and load-styles.php / load-scripts.php, already allowed above. # # Honors the same whitelist as every other rule in this frontend # (RFC1918 / trusted_ips.list / trusted_ips.map), and a per-site opt-out @@ -515,6 +533,7 @@ frontend web # the intended "reject a literal backslash" semantics. acl wp_admin_safe_path path_reg ^/[^/\\\\] acl wp_admin_allowed path_end /wp-admin/admin-ajax.php /wp-admin/admin-post.php /wp-admin/load-styles.php /wp-admin/load-scripts.php + acl wp_admin_install path_end /wp-admin/setup-config.php /wp-admin/install.php # The (?!.*\.php) lookahead is DEFENCE IN DEPTH, not the primary fix. This # ACL grants an un-gated bypass to everything under wp-admin/css|js|images, # and it used to anchor its prefix but not its suffix, so @@ -589,7 +608,7 @@ frontend web http-request deny deny_status 403 if wp_admin_word path_has_encoded_sep !has_wp_logged_in !wp_gate_exempt !is_local !is_trusted_ip !is_whitelisted http-request deny deny_status 403 if wp_admin_path !wp_admin_safe_path !has_wp_logged_in !wp_gate_exempt !is_local !is_trusted_ip !is_whitelisted http-request set-var(txn.wp_login_url) path,regsub(/wp-admin/.*,/wp-login.php,i) if wp_admin_path - http-request redirect code 302 location %[var(txn.wp_login_url)]?redirect_to=%[path,url_enc] if wp_admin_path wp_admin_safe_path !wp_admin_allowed !wp_admin_asset !has_wp_logged_in !wp_gate_exempt !is_local !is_trusted_ip !is_whitelisted + http-request redirect code 302 location %[var(txn.wp_login_url)]?redirect_to=%[path,url_enc] if wp_admin_path wp_admin_safe_path !wp_admin_allowed !wp_admin_install !wp_admin_asset !has_wp_logged_in !wp_gate_exempt !is_local !is_trusted_ip !is_whitelisted # IP blocking using map file (manual blocks only) # Map file format: /etc/haproxy/blocked_ips.map contains " 1" per line