From 694cb81cac5c72147a78ed4fd1ab88a9d3ded1a1 Mon Sep 17 00:00:00 2001
From: Joe Orton
Date: Fri, 27 Nov 2026 15:23:32 +0000
Subject: [PATCH 1/3] mod_proxy_html: Fix handling of ProxyHTMLURLMap regex
compile failures:
* modules/filters/mod_proxy_html.c (comp_urlmap): Set regflags for
interpolated rules too, and fail if the regex does not compile.
(fixup_rules): Skip a rule whose interpolated regex does not
compile; only evaluate conditions and interpolate with
ProxyHTMLInterp on.
(has_request_regex): New function.
(check_filter_init): Use fixup_rules() for an interpolated regex
without ProxyHTMLInterp.
* test/modules/filters/test_011_proxy_html_urlmap.py: New test.
* test/modules/filters/env.py (FiltersTestSetup.__init__): Load
mod_xml2enc and mod_proxy_html if available.
(FiltersTestEnv.__init__): Log mod_proxy_html at debug level.
(FiltersTestEnv.configtest): New method.
* changes-entries/proxy-html-urlmap-regex.txt: Add.
Co-Authored-By: Claude Fable 5.2
---
changes-entries/proxy-html-urlmap-regex.txt | 3 +
modules/filters/mod_proxy_html.c | 53 +++++++---
test/modules/filters/env.py | 20 +++-
.../filters/test_011_proxy_html_urlmap.py | 96 +++++++++++++++++++
4 files changed, 158 insertions(+), 14 deletions(-)
create mode 100644 changes-entries/proxy-html-urlmap-regex.txt
create mode 100644 test/modules/filters/test_011_proxy_html_urlmap.py
diff --git a/changes-entries/proxy-html-urlmap-regex.txt b/changes-entries/proxy-html-urlmap-regex.txt
new file mode 100644
index 00000000000..ac8b8e88b7d
--- /dev/null
+++ b/changes-entries/proxy-html-urlmap-regex.txt
@@ -0,0 +1,3 @@
+ *) mod_proxy_html: Fix a crash if a ProxyHTMLURLMap regex using
+ interpolated variables was invalid, and fail at startup for any
+ other invalid regex. [Joe Orton]
diff --git a/modules/filters/mod_proxy_html.c b/modules/filters/mod_proxy_html.c
index 3dffa5c8771..3c3cc7ce622 100644
--- a/modules/filters/mod_proxy_html.c
+++ b/modules/filters/mod_proxy_html.c
@@ -877,15 +877,30 @@ static const char *interpolate_vars(request_rec *r, const char *str)
}
return str;
}
+/* Whether any rule has a regex which is compiled per request. */
+static int has_request_regex(const urlmap *map)
+{
+ for (; map; map = map->next) {
+ if ((map->flags & M_REGEX) && (map->flags & M_INTERPOLATE_FROM))
+ return 1;
+ }
+ return 0;
+}
+
+/* Build the map for this request. Conditions and interpolation only
+ * apply with ProxyHTMLInterp on; without it the pattern of a regex rule
+ * flagged for interpolation is compiled as written.
+ */
static void fixup_rules(saxctxt *ctx)
{
urlmap *newp;
urlmap *p;
urlmap *prev = NULL;
request_rec *r = ctx->f->r;
+ int interp = ctx->cfg->interp;
for (p = ctx->cfg->map; p; p = p->next) {
- if (p->cond != NULL) {
+ if (interp && p->cond != NULL) {
const char *err;
int ok = ap_expr_exec(r, p->cond, &err);
if (err) {
@@ -900,15 +915,23 @@ static void fixup_rules(saxctxt *ctx)
newp = apr_pmemdup(r->pool, p, sizeof(urlmap));
if (newp->flags & M_INTERPOLATE_FROM) {
- newp->from.c = interpolate_vars(r, newp->from.c);
+ if (interp)
+ newp->from.c = interpolate_vars(r, newp->from.c);
if (!newp->from.c || !*newp->from.c)
continue; /* don't use empty from-pattern */
if (newp->flags & M_REGEX) {
- newp->from.r = ap_pregcomp(r->pool, newp->from.c,
- newp->regflags);
+ const char *pattern = newp->from.c;
+
+ newp->from.r = ap_pregcomp(r->pool, pattern, newp->regflags);
+ if (!newp->from.r) {
+ ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(10705)
+ "ProxyHTMLURLMap: could not compile "
+ "regex '%s', rule ignored", pattern);
+ continue;
+ }
}
}
- if (newp->flags & M_INTERPOLATE_TO) {
+ if (interp && (newp->flags & M_INTERPOLATE_TO)) {
newp->to = interpolate_vars(r, newp->to);
}
/* evaluate p->cond; continue if unsatisfied */
@@ -973,7 +996,7 @@ static saxctxt *check_filter_init (ap_filter_t *f)
ap_varbuf_init(f->r->pool, &fctx->vb, bufsz);
apr_table_unset(f->r->headers_out, "Content-Length");
- if (cfg->interp)
+ if (cfg->interp || has_request_regex(cfg->map))
fixup_rules(fctx);
else
fctx->map = cfg->map;
@@ -1220,18 +1243,22 @@ static const char *comp_urlmap(cmd_parms *cmd, urlmap *newmap,
| REGFLAG(M_INTERPOLATE_TO,flags,'V')
| REGFLAG(M_INTERPOLATE_FROM,flags,'v');
+ newmap->regflags
+ = REGFLAG(AP_REG_EXTENDED,flags,'x')
+ | REGFLAG(AP_REG_ICASE,flags,'i')
+ | REGFLAG(AP_REG_NOSUB,flags,'n')
+ | REGFLAG(AP_REG_NEWLINE,flags,'s');
+ newmap->to = to;
+
if ((newmap->flags & M_INTERPOLATE_FROM) || !(newmap->flags & M_REGEX)) {
newmap->from.c = from;
- newmap->to = to;
}
else {
- newmap->regflags
- = REGFLAG(AP_REG_EXTENDED,flags,'x')
- | REGFLAG(AP_REG_ICASE,flags,'i')
- | REGFLAG(AP_REG_NOSUB,flags,'n')
- | REGFLAG(AP_REG_NEWLINE,flags,'s');
newmap->from.r = ap_pregcomp(cmd->pool, from, newmap->regflags);
- newmap->to = to;
+ if (!newmap->from.r) {
+ return apr_pstrcat(cmd->pool, "ProxyHTMLURLMap: could not "
+ "compile regex '", from, "'", NULL);
+ }
}
if (cond != NULL) {
/* back-compatibility: support old-style ENV expressions
diff --git a/test/modules/filters/env.py b/test/modules/filters/env.py
index 149cdcdd4c7..f980371fc69 100644
--- a/test/modules/filters/env.py
+++ b/test/modules/filters/env.py
@@ -1,8 +1,10 @@
import inspect
import logging
import os
+from typing import List
from pyhttpd.env import HttpdTestEnv, HttpdTestSetup
+from pyhttpd.result import ExecResult
log = logging.getLogger(__name__)
@@ -14,13 +16,29 @@ def __init__(self, env: 'HttpdTestEnv'):
self.add_source_dir(os.path.dirname(inspect.getfile(FiltersTestSetup)))
self.add_modules(["substitute", "sed", "buffer", "brotli", "ext_filter", "include", "deflate"])
self.add_cgi_module()
+ self.add_optional_modules(["xml2enc", "proxy_html"])
class FiltersTestEnv(HttpdTestEnv):
def __init__(self, pytestconfig=None):
super().__init__(pytestconfig=pytestconfig)
- self.add_httpd_log_modules(["substitute", "sed", "buffer", "brotli", "ext_filter", "core"])
+ self.add_httpd_log_modules(["substitute", "sed", "buffer", "brotli", "ext_filter", "core", "proxy_html"])
def setup_httpd(self, setup: HttpdTestSetup = None):
super().setup_httpd(setup=FiltersTestSetup(env=self))
+
+ def configtest(self, lines: List[str]) -> ExecResult:
+ """Run `httpd -t` on a standalone config of the generated
+ modules.conf plus `lines`, leaving the running server alone."""
+ conf_path = os.path.join(self.gen_dir, "filters-configtest.conf")
+ modules_conf = os.path.join(self.server_conf_dir, "modules.conf")
+ with open(conf_path, 'w') as fd:
+ fd.write('\n'.join([
+ f'ServerRoot "{self.server_dir}"',
+ f'Include "{modules_conf}"',
+ f'DocumentRoot "{self.server_docs_dir}"',
+ f'Listen {self.http_port2}',
+ ] + lines) + '\n')
+ return self.run([os.path.join(self.bin_dir, 'httpd'), '-t',
+ '-f', conf_path])
diff --git a/test/modules/filters/test_011_proxy_html_urlmap.py b/test/modules/filters/test_011_proxy_html_urlmap.py
new file mode 100644
index 00000000000..5bc1f56bc7b
--- /dev/null
+++ b/test/modules/filters/test_011_proxy_html_urlmap.py
@@ -0,0 +1,96 @@
+import os
+
+import pytest
+
+from pyhttpd.backport import not_backported, skip_not_backported
+from pyhttpd.conf import HttpdConf
+
+# ProxyHTMLURLMap rules with a regex ('R') which is interpolated per
+# request ('v'): the pattern is only compiled once the request's
+# environment is known, and may then turn out not to be a regex at all.
+DOC = 'link'
+
+# Logged when the pattern for a request does not compile.
+NO_COMPILE = r'.*ProxyHTMLURLMap: could not compile regex.*'
+
+
+class TestProxyHTMLURLMap:
+
+ @pytest.fixture(autouse=True, scope='class')
+ @classmethod
+ def _class_scope(cls, env):
+ env.require(env.has_shared_module("proxy_html"),
+ "mod_proxy_html not available", dep="mod_proxy_html",
+ detected=f"no mod_proxy_html.so in {env.libexec_dir}")
+ doc_dir = os.path.join(env.server_dir, "htdocs", "test1", "phtml")
+ os.makedirs(doc_dir, exist_ok=True)
+ with open(os.path.join(doc_dir, "doc.html"), "w") as f:
+ f.write(DOC)
+ conf = HttpdConf(env, extras={
+ f"test1.{env.http_tld}": """
+ SetEnvIf X-Foo "(.+)" FOO=$1
+
+ SetEnv PROXY_HTML_FORCE 1
+ ProxyHTMLEnable On
+ ProxyHTMLLinks a href
+
+
+ ProxyHTMLInterp On
+ ProxyHTMLURLMap "${FOO}" "X" Rv
+
+
+ ProxyHTMLInterp On
+ ProxyHTMLURLMap "${FOO}" "X" Rvi
+
+
+ ProxyHTMLURLMap "Z.d" "X" Rv
+
+ Alias /phtml/interp %s
+ Alias /phtml/icase %s
+ Alias /phtml/nointerp %s
+ """ % ((doc_dir,) * 3),
+ })
+ conf.add_vhost_test1()
+ conf.install()
+ # The core warns that ${FOO} is not a variable it can expand.
+ env.httpd_error_log.add_ignored_lognos(["AH00111"])
+ assert env.apache_restart() == 0
+
+ def get(self, env, path, foo=None):
+ options = ["-H", f"X-Foo: {foo}"] if foo else None
+ r = env.curl_get(env.mkurl("http", "test1", path), options=options)
+ assert r.response["status"] == 200
+ return r.response["body"].decode()
+
+ def test_filters_011_01_interpolated_regex(self, env):
+ assert 'href="/X/x"' in self.get(env, "/phtml/interp/doc.html", "Z.d")
+
+ # The interpolated pattern is not a regex: the rule is ignored.
+ @skip_not_backported("gh-1104", "invalid interpolated regex")
+ def test_filters_011_02_interpolated_regex_invalid(self, env):
+ assert 'href="/Zed/x"' in self.get(env, "/phtml/interp/doc.html", "[")
+ env.httpd_error_log.ignore_recent(matches=[NO_COMPILE])
+ # ... and the next request is not affected by it.
+ assert 'href="/X/x"' in self.get(env, "/phtml/interp/doc.html", "Zed")
+
+ # The regex flags apply to an interpolated pattern too.
+ @not_backported("gh-1104", "regex flags with interpolation")
+ def test_filters_011_03_interpolated_regex_flags(self, env):
+ assert 'href="/X/x"' in self.get(env, "/phtml/icase/doc.html", "zED")
+ assert 'href="/Zed/x"' in self.get(env, "/phtml/interp/doc.html", "zED")
+
+ # Without ProxyHTMLInterp nothing is interpolated, and the pattern is
+ # used as it was written.
+ @skip_not_backported("gh-1104", "interpolated regex without ProxyHTMLInterp")
+ def test_filters_011_04_regex_without_interp(self, env):
+ assert 'href="/X/x"' in self.get(env, "/phtml/nointerp/doc.html")
+
+ @not_backported("gh-1104", "invalid regex is a configuration error")
+ def test_filters_011_05_invalid_regex_config(self, env):
+ r = env.configtest(['ProxyHTMLURLMap "[" "X" R'])
+ assert r.exit_code != 0
+ assert "ProxyHTMLURLMap" in r.stderr
+
+ def test_filters_011_06_valid_regex_config(self, env):
+ r = env.configtest(['ProxyHTMLURLMap "[a-z]" "X" R'])
+ assert r.exit_code == 0, r.stderr
From 49e6651edbd339adbb1b6b446d32c41a87d6db1b Mon Sep 17 00:00:00 2001
From: Joe Orton
Date: Fri, 27 Nov 2026 15:28:32 +0000
Subject: [PATCH 2/3] mod_proxy_html: Add ProxyHTMLMaxBufSize directive:
* modules/filters/mod_proxy_html.c (buffer_text): New function.
(pcdata, pcomment): Use it.
(pendElement, pstartElement): Reset overflow state.
(set_maxbufsz): New function.
(proxy_html_config, proxy_html_merge, proxy_html_cmds): Add
ProxyHTMLMaxBufSize, defaulting to 1M.
* docs/manual/mod/mod_proxy_html.xml: Document ProxyHTMLMaxBufSize.
* test/modules/filters/test_012_proxy_html_maxbuf.py: New test.
* changes-entries/proxy-html-maxbufsize.txt: Add.
Co-Authored-By: Claude Fable 5.2
---
changes-entries/proxy-html-maxbufsize.txt | 3 +
docs/manual/mod/mod_proxy_html.xml | 25 ++++
modules/filters/mod_proxy_html.c | 68 ++++++++++-
.../filters/test_012_proxy_html_maxbuf.py | 108 ++++++++++++++++++
4 files changed, 200 insertions(+), 4 deletions(-)
create mode 100644 changes-entries/proxy-html-maxbufsize.txt
create mode 100644 test/modules/filters/test_012_proxy_html_maxbuf.py
diff --git a/changes-entries/proxy-html-maxbufsize.txt b/changes-entries/proxy-html-maxbufsize.txt
new file mode 100644
index 00000000000..7f58f2a7de1
--- /dev/null
+++ b/changes-entries/proxy-html-maxbufsize.txt
@@ -0,0 +1,3 @@
+ *) mod_proxy_html: Add ProxyHTMLMaxBufSize, 1M by default; a larger
+ inline script, stylesheet or comment is passed through without
+ being rewritten by ProxyHTMLExtended. [Joe Orton]
diff --git a/docs/manual/mod/mod_proxy_html.xml b/docs/manual/mod/mod_proxy_html.xml
index 70d731b0a81..e0c078e054c 100644
--- a/docs/manual/mod/mod_proxy_html.xml
+++ b/docs/manual/mod/mod_proxy_html.xml
@@ -424,6 +424,31 @@ size and avoid the need to resize the buffer dynamically during a request.
+
+ProxyHTMLMaxBufSize
+Sets the maximum size of an inline script, stylesheet or
+comment which is rewritten.
+ProxyHTMLMaxBufSize bytes
+ProxyHTMLMaxBufSize 1M
+server config
+virtual hostdirectory
+
+Available in version 2.5.1 and later.
+
+With ProxyHTMLExtended
+enabled, mod_proxy_html reads each inline script,
+stylesheet or comment into memory in full before rewriting it. This
+directive limits the size of that buffer. A script, stylesheet or comment
+larger than bytes is passed through as received from the
+backend, without any ProxyHTMLURLMap rule applied to it, and a warning is
+logged.
+The value may be followed by K, M or
+G for kilobytes, megabytes or gigabytes. A value of
+0 removes the limit.
+
+
+
ProxyHTMLEvents
Specify attributes to treat as scripting events.
diff --git a/modules/filters/mod_proxy_html.c b/modules/filters/mod_proxy_html.c
index 3c3cc7ce622..6b1a93d836a 100644
--- a/modules/filters/mod_proxy_html.c
+++ b/modules/filters/mod_proxy_html.c
@@ -109,6 +109,8 @@ typedef struct {
const char *etag;
unsigned int flags;
int bufsz;
+ apr_size_t maxbufsz;
+ int maxbufsz_set;
apr_hash_t *links;
apr_array_header_t *events;
const char *charset_out;
@@ -130,9 +132,11 @@ typedef struct {
char rbuf[4];
apr_size_t rlen;
apr_size_t rmin;
+ int overflow; /* buffered text went over the limit */
} saxctxt;
#define DEFAULT_BUFSZ (8192)
+#define DEFAULT_MAXBUFSZ (1024 * 1024)
#define NORM_LC 0x1
#define NORM_MSSLASH 0x2
@@ -356,12 +360,40 @@ static void pinternalSubset(void* ctxt, const xmlChar *name,
}
ap_fputs(ctx->f->next, ctx->bb, ">\n");
}
+
+/* Buffer text which is rewritten when the element ends. If the buffer
+ * would grow beyond ProxyHTMLMaxBufSize, write out what it holds and
+ * pass through the rest of the text up to the end of the element,
+ * none of it rewritten.
+ */
+static void buffer_text(saxctxt *ctx, const char *chars, apr_size_t length)
+{
+ apr_size_t max = ctx->cfg->maxbufsz;
+
+ if (!ctx->overflow && max
+ && (ctx->vb.strlen > max || length > max - ctx->vb.strlen)) {
+ ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, ctx->f->r, APLOGNO(10706)
+ "Inline script, stylesheet or comment larger than "
+ "ProxyHTMLMaxBufSize (%" APR_SIZE_T_FMT
+ " bytes), not rewritten", max);
+ AP_fwrite(ctx, ctx->vb.buf, ctx->vb.strlen, 0);
+ ctx->vb.strlen = 0;
+ ctx->overflow = 1;
+ }
+ if (ctx->overflow) {
+ AP_fwrite(ctx, chars, length, 0);
+ }
+ else {
+ ap_varbuf_strmemcat(&ctx->vb, chars, length);
+ }
+}
+
static void pcdata(void *ctxt, const xmlChar *uchars, int length)
{
const char *chars = (const char*) uchars;
saxctxt *ctx = (saxctxt*) ctxt;
if (ctx->cfg->extfix) {
- ap_varbuf_strmemcat(&ctx->vb, chars, length);
+ buffer_text(ctx, chars, length);
}
else {
/* not sure if this should force-flush
@@ -378,9 +410,9 @@ static void pcomment(void *ctxt, const xmlChar *uchars)
return;
if (ctx->cfg->extfix) {
- ap_varbuf_strcat(&ctx->vb, "");
+ buffer_text(ctx, "", 3);
}
else {
ap_fputs(ctx->f->next, ctx->bb, "
'
+ f'