S6444 — Regular expressions should be executed with a timeout

Language
C#
Type
Vulnerability
Severity
Minor
Tags
cwe, regex, former-hotspot

Regular expressions without a timeout can be exploited to cause a Denial-of-Service attack.

Why is this an issue?

When a regular expression is executed against untrusted input without a timeout, a malicious user may craft an input that triggers catastrophic backtracking, where the regex engine takes exponential time to determine there is no match. This type of attack is known as a Regular Expression Denial of Service (ReDoS). This rule raises an issue when System.Text.RegularExpressions APIs are called without a matchTimeout parameter and no process-wide default timeout has been configured via AppDomain.CurrentDomain.SetData("REGEX_DEFAULT_MATCH_TIMEOUT", timeout).

What is the potential impact?

An attacker who controls the input to a vulnerable regular expression can cause the application to consume all available CPU time while processing a single request, making the service unavailable to legitimate users.

How to fix it

Code examples

The following code is vulnerable because the regular expressions are executed without a timeout, allowing a crafted input to trigger catastrophic backtracking.

Noncompliant code example


public void RegexPattern(string input)
{
    var emailPattern = new Regex(".+@.+", RegexOptions.None);
    var isNumber = Regex.IsMatch(input, "[0-9]+");
    var isLetterA = Regex.IsMatch(input, "(a+)+");
    // Noncompliant: missing timeout
}

Compliant solution


public void RegexPattern(string input)
{
    var emailPattern = new Regex(".+@.+", RegexOptions.None, TimeSpan.FromMilliseconds(100));
    var isNumber = Regex.IsMatch(input, "[0-9]+", RegexOptions.None, TimeSpan.FromMilliseconds(100));
    var isLetterA = Regex.IsMatch(input, "(a+)+", RegexOptions.NonBacktracking); // .NET 7 and above
    AppDomain.CurrentDomain.SetData("REGEX_DEFAULT_MATCH_TIMEOUT", TimeSpan.FromMilliseconds(100)); // process-wide setting
}

Resources

Documentation

Articles & blog posts

Standards

↑ Back to top