Regular expressions without a timeout can be exploited to cause a Denial-of-Service attack.
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).
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.
The following code is vulnerable because the regular expressions are executed without a timeout, allowing a crafted input to trigger catastrophic backtracking.
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
}
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
}