Skip to content

Commit 40a501a

Browse files
authored
Merge pull request #269 from CoreTrace/fix/template-start-tags
fix(templates): read start tags as the HTML tokenizer does
2 parents ea73758 + 22a747f commit 40a501a

3 files changed

Lines changed: 212 additions & 2 deletions

File tree

‎docs/usage.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,11 @@ It establishes escaping only when all of the following hold:
197197
or an attribute name.
198198
- No Python file of the project sets `autoescape` to `False`.
199199

200+
Start tags and their attributes are read as a browser's HTML tokenizer reads them, in time
201+
linear in the size of the template. A tag, or a quoted attribute value, a template leaves
202+
open at its end is checked too: once the template is included, it runs into the markup
203+
that follows, the value staying quoted until its quote closes.
204+
200205
The analyzer never assumes escaping where it cannot read the template. That covers a
201206
template file it cannot read, a template named by an expression, a template found
202207
through a `DIRS` entry not named `templates`, one shipped by an installed package, one

‎src/coretrace_python/taint/templates.py‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -140,8 +140,20 @@
140140
# fixed: no scheme such as ``javascript:`` can follow.
141141
_SAFE_URL_PREFIX = re.compile(r"(?:/(?!/)|\.{1,2}/|[#?]|https?://[^/?#\x00\x01]+[/?#])")
142142
_QUOTED = r"\"[^\"]*\"|'[^']*'"
143-
_ATTRIBUTE = re.compile(rf"([^\s\"'>/=]+)(?:\s*=\s*({_QUOTED}|[^\s\"'=<>`]+))?")
144-
_START_TAG = re.compile(rf"<([A-Za-z][^\s/>]*)((?:\s*[^\s\"'>/=]+(?:\s*=\s*(?:{_QUOTED}|[^\s\"'=<>`]+))?)*)\s*/?>")
143+
# A start tag read as the HTML tokenizer reads one: the tag name runs to whitespace, ``/``
144+
# or ``>``; between attributes, whitespace and a stray ``/`` are skipped; an attribute
145+
# name, which may begin with ``=``, runs to whitespace, ``/``, ``>`` or ``=``; a value
146+
# follows ``=``, quoted, or running to whitespace or ``>``. Each token is told apart by
147+
# its first character, so matching is linear, where splitting runs between attributes
148+
# took exponential time (#263). A tag the text ends in before its ``>`` still matches,
149+
# to the end: a template may be included before more markup, which the tag then runs
150+
# into, so its attributes are checked like any other's. A value that opens a quote
151+
# stays quoted to the matching quote or, for the same reason, to the end of the text: it
152+
# is never read again as an unquoted value.
153+
_ATTRIBUTE_NAME = r"(?:=[^\s/>=]*+|[^\s/>=]++)"
154+
_ATTRIBUTE_VALUE = r"(?:\"[^\"]*+(?:\"|\Z)|'[^']*+(?:'|\Z)|[^\s>]*+)"
155+
_ATTRIBUTE = re.compile(rf"({_ATTRIBUTE_NAME})(?:\s*+=\s*+({_ATTRIBUTE_VALUE}))?")
156+
_START_TAG = re.compile(rf"<([A-Za-z][^\s/>]*+)((?:[\s/]++|{_ATTRIBUTE_NAME}(?:\s*+=\s*+{_ATTRIBUTE_VALUE})?)*+)>?")
145157
_RAW_TEXT = re.compile(r"<(script|style)\b[^>]*>(.*?)</\1\s*>", re.DOTALL | re.IGNORECASE)
146158
_COMMENT = re.compile(r"<!--.*?-->", re.DOTALL)
147159
_END_TAG = re.compile(r"</[A-Za-z][^>]*>")
Lines changed: 193 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,193 @@
1+
"""Acceptance tests for issue #263: the escaping inspection of a template ends, whatever
2+
the file under a ``templates`` directory holds.
3+
4+
``_START_TAG`` could split a run of attribute-name characters, or of an unquoted value,
5+
between consecutive attributes in exponentially many ways, and tried them all when no
6+
``>`` followed: a few dozen characters, in a text template or a binary file decoded with
7+
replacement characters, stopped the analysis. Each inspection runs here in a subprocess
8+
with a timeout, so that one that does not end fails instead of hanging the suite. The
9+
inspection still refuses to establish escaping where a variable stands in a dangerous
10+
attribute, however long what comes before it.
11+
12+
Start tags are read as the HTML tokenizer reads them. A tag a template leaves open at its
13+
end runs, once the template is included, into the markup that follows: its attributes
14+
are checked like any other's.
15+
"""
16+
17+
from __future__ import annotations
18+
19+
import json
20+
import subprocess
21+
import sys
22+
from pathlib import Path
23+
24+
import pytest
25+
26+
# A run long enough that no exponential inspection would ever end; a linear one takes
27+
# milliseconds.
28+
RUN = 5000
29+
TIMEOUT = 60
30+
31+
ESCAPED_TEMPLATES = (
32+
"import json, sys\n"
33+
"from pathlib import Path\n"
34+
"from coretrace_python.taint.templates import escaped_templates\n"
35+
"print(json.dumps(sorted(escaped_templates(Path(sys.argv[1])))))\n"
36+
)
37+
38+
39+
def escaped(tmp_path: Path, files: dict[str, str | bytes]) -> list[str]:
40+
"""The names of the templates ``escaped_templates`` establishes for a project of
41+
``files``, computed in a subprocess with a timeout."""
42+
43+
root = tmp_path / "project"
44+
for relative, content in files.items():
45+
path = root / relative
46+
path.parent.mkdir(parents=True, exist_ok=True)
47+
if isinstance(content, bytes):
48+
path.write_bytes(content)
49+
else:
50+
path.write_text(content, encoding="utf-8")
51+
try:
52+
completed = subprocess.run(
53+
[sys.executable, "-c", ESCAPED_TEMPLATES, str(root)],
54+
capture_output=True,
55+
text=True,
56+
check=True,
57+
timeout=TIMEOUT,
58+
)
59+
except subprocess.TimeoutExpired:
60+
pytest.fail(f"the inspection did not end within {TIMEOUT} s")
61+
names: list[str] = json.loads(completed.stdout)
62+
return names
63+
64+
65+
@pytest.mark.parametrize(
66+
"template",
67+
[
68+
"<p><a " + "b" * RUN + "</p>",
69+
"<a " + "b" * RUN + '"',
70+
"<a " + "b" * RUN,
71+
"<a b=" + "c" * RUN + '"',
72+
],
73+
ids=["name-run-in-text", "name-run-then-quote", "name-run-at-the-end", "unquoted-value-run-then-quote"],
74+
)
75+
def test_a_tag_that_never_closes_is_inspected_to_the_end(tmp_path: Path, template: str) -> None:
76+
# No variable is printed, so the template escapes.
77+
assert escaped(tmp_path, {"app/templates/page.html": template}) == ["page.html"]
78+
79+
80+
def test_a_binary_file_under_templates_does_not_stop_the_inspection(tmp_path: Path) -> None:
81+
# Invalid UTF-8 decodes to replacement characters, which may form attribute names.
82+
image = b"\x89PNG\r\n\x1a\n" + b"<a " + b"\xb5" * RUN + b'"'
83+
files: dict[str, str | bytes] = {
84+
"app/templates/images/thumbnail.png": image,
85+
"app/templates/page.html": "<p>{{ name }}</p>",
86+
}
87+
88+
assert "page.html" in escaped(tmp_path, files)
89+
90+
91+
@pytest.mark.parametrize(
92+
"template",
93+
[
94+
"<a " + "b" * RUN + " onclick=\"go('{{ name }}')\">x</a>",
95+
"<div " + "b" * RUN + " title={{ name }}>x</div>",
96+
"<a b=" + "c" * RUN + ' href="{{ url }}">x</a>',
97+
"<a title=\"x\"onclick=\"go('{{ name }}')\">x</a>",
98+
"<div " + "b" * RUN + " {{ attributes }}>x</div>",
99+
],
100+
ids=["event-handler", "unquoted-value", "url-attribute", "handler-right-after-a-quoted-value", "attribute-name"],
101+
)
102+
def test_a_variable_in_a_dangerous_attribute_after_a_long_run_is_still_refused(tmp_path: Path, template: str) -> None:
103+
assert escaped(tmp_path, {"app/templates/page.html": template}) == []
104+
105+
106+
def test_a_variable_in_a_quoted_attribute_after_a_long_run_is_still_escaped(tmp_path: Path) -> None:
107+
template = "<a " + "b" * RUN + ' title="{{ name }}">x</a>'
108+
109+
assert escaped(tmp_path, {"app/templates/page.html": template}) == ["page.html"]
110+
111+
112+
@pytest.mark.parametrize(
113+
("template", "names"),
114+
[
115+
("<p>Hello</p><a onclick=\"go('{{ name }}')\"", []),
116+
("<p>Hello</p><a title={{ name }}", []),
117+
("<p>Hello</p><a {{ name }}", []),
118+
('<p>Hello</p><a title="{{ name }}"', ["page.html"]),
119+
],
120+
ids=["event-handler", "unquoted-value", "attribute-name", "quoted-title"],
121+
)
122+
def test_a_tag_left_open_at_the_end_has_its_attributes_checked(tmp_path: Path, template: str, names: list[str]) -> None:
123+
assert escaped(tmp_path, {"app/templates/page.html": template}) == names
124+
125+
126+
@pytest.mark.parametrize(
127+
("template", "names"),
128+
[
129+
# After a stray ``/``, the variable starts an attribute name.
130+
("<a/{{ name }}>x</a>", []),
131+
# An attribute name may begin with ``=``: here ``="`` and the variable.
132+
('<div ="{{ name }}">x</div>', []),
133+
# ``=`` is an attribute of its own, and ``title`` a quoted one after it.
134+
('<div = title="{{ name }}">x</div>', ["page.html"]),
135+
],
136+
ids=["after-a-slash", "name-beginning-with-equals", "equals-then-quoted-title"],
137+
)
138+
def test_attributes_are_read_as_a_browser_reads_them(tmp_path: Path, template: str, names: list[str]) -> None:
139+
assert escaped(tmp_path, {"app/templates/page.html": template}) == names
140+
141+
142+
# A value that opens a quote stays quoted to the matching quote or, left open, to the end
143+
# of the template: once included, the markup that follows continues it. Read again as an
144+
# unquoted value, ``"/*`` ended at the first space and ``title='…'`` read as a separate,
145+
# safe attribute, while the variable sits in the handler.
146+
@pytest.mark.parametrize(
147+
("template", "names"),
148+
[
149+
("<a onclick=\"/* title='<{{ name }}'>", []),
150+
("<a onclick='/* title=\"<{{ name }}\">", []),
151+
('<a title="x {{ name }} y>', ["page.html"]),
152+
],
153+
ids=["double-quoted-handler", "single-quoted-handler", "double-quoted-title"],
154+
)
155+
def test_a_quoted_value_left_open_runs_to_the_end_of_the_template(
156+
tmp_path: Path, template: str, names: list[str]
157+
) -> None:
158+
assert escaped(tmp_path, {"app/templates/page.html": template}) == names
159+
160+
161+
INCLUDING_VIEW = (
162+
"from django.http import HttpRequest, HttpResponse\n"
163+
"from django.template.loader import render_to_string\n\n"
164+
"def page(request: HttpRequest):\n"
165+
" return HttpResponse(render_to_string('page.html', {'name': request.GET['name']}))\n"
166+
)
167+
168+
169+
def test_a_handler_whose_quote_closes_in_the_including_template_is_cross_site_scripting(tmp_path: Path) -> None:
170+
# Rendered, the handler is ``/* title='<…'>{…}">``: a name such as ``*/alert(1);//``
171+
# runs in it.
172+
files: dict[str, str | bytes] = {
173+
"app/views.py": INCLUDING_VIEW,
174+
"app/templates/fragment.html": "<a onclick=\"/* title='<{{ name }}'>\n",
175+
"app/templates/page.html": "{% include 'fragment.html' %}\">click</a>\n",
176+
}
177+
178+
assert escaped(tmp_path, files) == []
179+
root = tmp_path / "project"
180+
try:
181+
completed = subprocess.run(
182+
[sys.executable, "-m", "coretrace_python", "--check", str(root), "--format", "json"],
183+
capture_output=True,
184+
text=True,
185+
check=False,
186+
timeout=TIMEOUT,
187+
)
188+
except subprocess.TimeoutExpired:
189+
pytest.fail(f"the analysis did not end within {TIMEOUT} s")
190+
findings = json.loads(completed.stdout)["findings"]
191+
assert [(f["location"]["path"], f["location"]["line"]) for f in findings if f["rule_id"] == "xss"] == [
192+
("app/views.py", 5)
193+
]

0 commit comments

Comments
 (0)