diff --git a/changes-entries/proxy-html-doctype-libxml2.txt b/changes-entries/proxy-html-doctype-libxml2.txt new file mode 100644 index 00000000000..ca5552f6df9 --- /dev/null +++ b/changes-entries/proxy-html-doctype-libxml2.txt @@ -0,0 +1,3 @@ + *) mod_proxy_html: Reject "ProxyHTMLDocType HTML|XHTML" if built with + libxml2 2.14 or later, with which HTML 4 documents can no longer + be cleaned up. [Joe Orton] 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/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/docs/manual/mod/mod_proxy_html.xml b/docs/manual/mod/mod_proxy_html.xml index 70d731b0a81..d9ac598020f 100644 --- a/docs/manual/mod/mod_proxy_html.xml +++ b/docs/manual/mod/mod_proxy_html.xml @@ -322,6 +322,11 @@ will also clean up the HTML to the specified standard. It cannot fix every error, but it will strip out bogus elements and attributes. It will also optionally log other errors at LogLevel Debug.

+The first form relies on the description of HTML 4 which +libxml2 provided up to version 2.13. If mod_proxy_html +is built with libxml2 2.14 or later, the first form is not available and +is rejected as a configuration error. To declare such a document type +without the clean-up, give it in the second form. @@ -424,6 +429,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 3dffa5c8771..4ab45417487 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,10 +132,39 @@ 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) +/* Cleaning up documents to HTML 4.01 or XHTML 1.0 relies on the element + * and attribute tables which libxml2 2.14 no longer has. + */ +#if LIBXML_VERSION < 21400 +#define PROXY_HTML_ENFORCE 1 +#endif + +#ifndef PROXY_HTML_ENFORCE +/* Elements which have no content and no end tag. */ +static const char *const empty_elts[] = { + "area", "base", "basefont", "bgsound", "br", "col", "embed", "frame", + "hr", "img", "input", "isindex", "keygen", "link", "meta", "param", + "source", "track", "wbr", NULL +}; + +static int is_empty_elt(const char *name) +{ + const char *const *e; + + for (e = empty_elts; *e; e++) { + if (!ap_cstr_casecmp(name, *e)) + return 1; + } + return 0; +} +#endif +#define DEFAULT_MAXBUFSZ (1024 * 1024) + #define NORM_LC 0x1 #define NORM_MSSLASH 0x2 #define NORM_RESET 0x4 @@ -141,6 +172,7 @@ static htmlSAXHandler sax; typedef enum { ATTR_IGNORE, ATTR_URI, ATTR_EVENT } rewrite_t; +#ifdef PROXY_HTML_ENFORCE static const char *const fpi_html = "\n"; static const char *const fpi_html_legacy = @@ -149,6 +181,7 @@ static const char *const fpi_xhtml = "\n"; static const char *const fpi_xhtml_legacy = "\n"; +#endif static const char *const fpi_html5 = "\n"; static const char *const html_etag = ">"; static const char *const xhtml_etag = " />"; @@ -356,12 +389,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 +439,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'', +} + +NO_DIRECTIVE = not_backported("gh-1104", "ProxyHTMLMaxBufSize") + +TOO_LARGE = r'.*larger than ProxyHTMLMaxBufSize.*' + + +class TestProxyHTMLMaxBufSize: + + @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) + for name, text in DOCS.items(): + with open(os.path.join(doc_dir, name), "w") as f: + f.write(text) + cls.doc_dir = doc_dir + + def configure(self, env, maxbuf): + conf = HttpdConf(env, extras={ + f"test1.{env.http_tld}": f""" + + SetEnv PROXY_HTML_FORCE 1 + ProxyHTMLEnable On + ProxyHTMLExtended On + ProxyHTMLLinks a href + ProxyHTMLURLMap http://backend.example/ /proxy/ + {maxbuf} + + """, + }) + conf.add_vhost_test1() + conf.install() + assert env.apache_restart() == 0 + + def get(self, env, name): + r = env.curl_get(env.mkurl("http", "test1", f"/phtml/{name}")) + assert r.response["status"] == 200 + return r.response["body"].decode() + + @NO_DIRECTIVE + def test_filters_012_01_limit(self, env): + self.configure(env, f"ProxyHTMLMaxBufSize {MAXBUF}") + body = self.get(env, "small.html") + assert SMALL.replace("http://backend.example/", "/proxy/") in body + assert "backend.example" not in body + + # Over the limit: all of the script comes through untouched, the + # stylesheet after it is rewritten. + body = self.get(env, "large.html") + assert f"" in body + assert ("") in body + env.httpd_error_log.ignore_recent(matches=[TOO_LARGE]) + + body = self.get(env, "comment.html") + assert f"" in body + assert ("") in body + env.httpd_error_log.ignore_recent(matches=[TOO_LARGE]) + + @pytest.mark.parametrize("maxbuf", [ + pytest.param("ProxyHTMLMaxBufSize 0", marks=NO_DIRECTIVE), + pytest.param("ProxyHTMLMaxBufSize 1M", marks=NO_DIRECTIVE), + "", + ]) + def test_filters_012_02_under_limit(self, env, maxbuf): + self.configure(env, maxbuf) + for name in ["large.html", "comment.html"]: + assert "backend.example" not in self.get(env, name) + + @pytest.mark.parametrize("value, ok", [ + pytest.param("64K", True, marks=NO_DIRECTIVE), + pytest.param("0", True, marks=NO_DIRECTIVE), + ("-1", False), ("lots", False), + ]) + def test_filters_012_03_config(self, env, value, ok): + r = env.configtest([f"ProxyHTMLMaxBufSize {value}"]) + assert (r.exit_code == 0) == ok, r.stderr diff --git a/test/modules/filters/test_013_proxy_html_doctype.py b/test/modules/filters/test_013_proxy_html_doctype.py new file mode 100644 index 00000000000..80389c74b4a --- /dev/null +++ b/test/modules/filters/test_013_proxy_html_doctype.py @@ -0,0 +1,80 @@ +import os + +import pytest + +from pyhttpd.backport import not_backported +from pyhttpd.conf import HttpdConf + +# "ProxyHTMLDocType HTML|XHTML [Legacy]" cleans up the document, dropping +# elements and attributes which HTML 4 does not have. It relies on tables +# which libxml2 2.14 removed, so a module built with a newer libxml2 +# refuses those forms rather than accept them and clean up nothing. +DOC = ('t' + '

text
more

' + 'old' + '') + +ENFORCING = ["HTML", "XHTML", "HTML Legacy", "XHTML Legacy"] + + +class TestProxyHTMLDocType: + + @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, "doctype.html"), "w") as f: + f.write(DOC) + + def get(self, env, doctype): + conf = HttpdConf(env, extras={ + f"test1.{env.http_tld}": f""" + + SetEnv PROXY_HTML_FORCE 1 + ProxyHTMLEnable On + ProxyHTMLLinks a href + ProxyHTMLDocType {doctype} + + """, + }) + conf.add_vhost_test1() + conf.install() + assert env.apache_restart() == 0 + r = env.curl_get(env.mkurl("http", "test1", "/phtml/doctype.html")) + assert r.response["status"] == 200 + return r.response["body"].decode() + + # Either the form is refused, or it does what is documented. (An + # unpatched server fails this only if built with libxml2 >= 2.14.) + @not_backported("gh-1104", "ProxyHTMLDocType with libxml2 2.14") + @pytest.mark.parametrize("doctype", ENFORCING) + def test_filters_013_01_enforcing(self, env, doctype): + r = env.configtest([f"ProxyHTMLDocType {doctype}"]) + if r.exit_code != 0: + assert "libxml2" in r.stderr + return + body = self.get(env, doctype) + assert 'class="ok"' in body + assert "data-bogus" not in body + if "Legacy" not in doctype: + assert "" not in body + assert "old" in body + + # The other forms never cleaned anything up. + @pytest.mark.parametrize("doctype, declared", [ + ("HTML5", ""), + ("auto", None), + ('"-//W3C//DTD HTML 4.01//EN"', "-//W3C//DTD HTML 4.01//EN"), + ]) + def test_filters_013_02_other_forms(self, env, doctype, declared): + body = self.get(env, doctype) + if declared: + assert body.startswith(declared) + assert 'data-bogus="x"' in body + assert 'old' in body + # an empty element gets no end tag + assert "text
more" in body diff --git a/test/pytest_suite/t/conf/proxy.conf.in b/test/pytest_suite/t/conf/proxy.conf.in index 3025038a494..dab47b48620 100644 --- a/test/pytest_suite/t/conf/proxy.conf.in +++ b/test/pytest_suite/t/conf/proxy.conf.in @@ -325,7 +325,7 @@ Alias /modules/proxy/fcgi-uds-sethandler @SERVERROOT@/htdocs/modules/proxy/fcgi ProxyHTMLEnable on ProxyHTMLLinks a href - ProxyHTMLDocType HTML + ProxyHTMLDocType HTML5 ProxyHTMLURLMap http://a.example.com/ http://b.example.com/ ProxyPass http://@SERVERNAME@:@PORT@/modules/proxy_html