Skip to main content
Menu
Advisories

Quadratic-time (O(n^2)) ReDoS in CSS length unit parsing (RE_UNIT) via a style attribute

GHSA-R39G-X868-W7R7Published Updated GitHub

Description

CssParse._get_em parses a CSS length with RE_UNIT = re.compile(r"(-?[0-9.]+)(\w+)") via .search(). On a style value that is a long run of '.' characters, this search is quadratic: [0-9.]+ matches the whole run at every start position and then the required \w+ fails, backtracking each time. get_text() runs on untrusted HTML by default, so a single small document hangs the process. This is a CPU/ReDoS issue in the regex itself, distinct from the memory issue already reported for CSS lengths.

Details

src/inscriptis/model/css.py:33 and its use in _get_em:

RE_UNIT = re_compile(r"(-?[0-9.]+)(\w+)")
...
_m = CssParse.RE_UNIT.search(length)   # line 70

length is the value of a length-based CSS property in an untrusted style attribute. attr_style() dispatches margin-top / margin-bottom / padding-left (and aliases) to _get_em(value). RE_UNIT.search over a value of only . characters never matches ([0-9.]+ consumes the dots, \w+ then fails because . is not a word char), and re.search retries from every start position and backtracks the greedy [0-9.]+, giving O(n^2) in the value length. Style attribute values have no length limit, and this is reachable in 2.7.6.

This is separate from the previously reported "CSS length drives unbounded string allocation" (a memory issue from the numeric value used as a repeat count). Here the cost is CPU inside the regex, before any number is used.

Suggested fix: cap the CSS value length before RE_UNIT.search, or anchor the match.

Proof of concept

import time
from inscriptis import get_text
for n in (10_000, 20_000, 40_000):
    html = '<p style="margin-top:' + '.' * n + '">x</p>'
    t0 = time.perf_counter()
    get_text(html)
    print(n, round(time.perf_counter() - t0, 1), "s")

Scales as O(n^2) (doubling n ~= 4x time): 5,000 -> 0.22 s | 10,000 -> 0.89 s | 20,000 -> 3.52 s | 40,000 -> 14.1 s.

Impact

Anything that runs get_text()/get_annotated_text() on untrusted HTML (the documented use) can be made to consume quadratic CPU and hang on a single small document, a denial of service. No configuration or auth is required.

Affected versions

References

GitHub · weblyzard/inscriptis