| Property | Value |
|---|---|
| Package | Philips.CodeAnalysis.SecurityAnalyzers |
| Diagnostic ID | PH2137 |
| Category | Security |
| Analyzer | RegexNeedsTimeoutAnalyzer |
| CodeFix | No |
| Severity | Error |
| Enabled By Default | Yes |
The evaluation times of a Regular Expression (using the Regex class) can be longer depending on its input. This is because of backtracking.
Regular expression evaluation times are dependant on the input format and length, malicious input can make these evaluation times so long that the system does not respond anymore, resulting in a DOS attack.
When constructing a new Regex instance, provide a timeout as this limits the evaluation time.
.NET 7+ give an alternative solution in the RegexOptions.NonBacktracking option, which as the name suggests disables backtracking and therefore making the evaluation times linear with the input length.
Code that triggers 2 diagnostics:
class BadExample {
public void BadCode() {
Regex regex = new Regex(".*");
}
}And the corrected code:
class GoodExample {
public void GoodCode() {
Regex regex = new Regex(".*", RegexOptions.Compiled, TimeSpan.FromSeconds(1));
}
}And the corrected code in .NET 7+:
class GoodExample {
public void GoodCode() {
Regex regex = new Regex(".*", RegexOptions.NonBacktracking);
}
}This analyzer does not offer any special configuration. The general ways of suppressing diagnostics apply.