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

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

What it finds

new Regex(@"^(\w+\s?)*$"): on an input that almost matches, such as a long run of letters followed by !, the backtracking engine of .NET tries exponentially many ways to split the letters between the inner and the outer repetition. Without a match timeout, a request of a few dozen characters keeps a thread 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, as IsMatch, Match, Replace and Split search for the pattern, on a backtracking matcher that follows the pattern exactly, lookarounds and atomic groups included. Patterns with a timeout or with RegexOptions.NonBacktracking are left alone. 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
using System;using System.Text.RegularExpressions; public class Names{    static readonly Regex Name = new Regex(@"^(\w+\s?)*$");tx0 reports: exponential time    static readonly Regex Bounded = new Regex(@"^(\w+\s?)*$", RegexOptions.None, TimeSpan.FromSeconds(1));    static readonly Regex Fast = new Regex(@"^(\S+\s+)*x$");     public bool Check(string s) => Regex.IsMatch(s, "(a|a)*b");tx0 reports: exponential time}
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/csharp: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/csharp:regex-exponential-backtracking] reason="..."

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