A regular expression takes exponential time on some inputs, confirmed with an input that shows it

tx0/python:regex-exponential-backtrackingdefaultwarningperformance/regexdepth fastbug, security, cwe-1333

What it finds

re.match(r"^(\w+\s?)*$", name): on an input that almost matches, such as a long run of letters followed by !, the backtracking engine of re tries exponentially many ways to split the letters between the inner and the outer repetition. A string of a few dozen characters keeps a worker busy for minutes (CWE-1333).

The pattern is turned into an automaton and searched for ambiguity: a state that reaches itself on one input along two paths makes the time exponential. Every candidate is then confirmed by running the input it suggests on a backtracking matcher that follows the pattern exactly, lookarounds, atomic groups and possessive quantifiers included, with the semantics of the function (fullmatch needs the whole input, match a prefix, search, findall, sub and split search). The finding names that input. Patterns matched against request input are reported by regex-backtracking-on-input instead.

From the rule's source, regex_backtracking.rs.

Example from the rule's tests
import re a = re.compile(r"^(\w+\s?)*$")tx0 reports: exponential timeb = re.fullmatch(r"(a|a)*", text)tx0 reports: exponential timec = re.search(r"(a+)+", text)d = re.match(r"^(\S+\s+)*x$", text)
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs in every tier. To turn it off for a project, set its level in tx0.toml:

tx0.toml
[rules]
"tx0/python:regex-exponential-backtracking" = "off"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

# tx0: ignore[tx0/python:regex-exponential-backtracking] reason="..."

tx0 explain tx0/python:regex-exponential-backtracking shows the same in the terminal. Found a false positive? Report it.