org.sonar.plugins.csharp.S6444.html Maven / Gradle / Ivy
Not specifying a timeout for regular expressions can lead to a Denial-of-Service attack. Pass a timeout when using
System.Text.RegularExpressions
to process untrusted input because a malicious user might craft a value for which the evaluation lasts
excessively long.
Ask Yourself Whether
- the input passed to the regular expression is untrusted.
- the regular expression contains patterns vulnerable to catastrophic
backtracking.
There is a risk if you answered yes to any of those questions.
Recommended Secure Coding Practices
- It is recommended to specify a
matchTimeout
when executing a
regular expression.
- Make sure regular expressions are not vulnerable to Denial-of-Service attacks by reviewing the patterns.
- Consider using a non-backtracking algorithm by specifying
RegexOptions.NonBacktracking
.
Sensitive 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+)+");
}
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
}
See
- OWASP - Top 10 2017 Category A1 - Injection
- CWE - CWE-400 - Uncontrolled Resource Consumption
- CWE - CWE-1333 - Inefficient Regular Expression Complexity
- regular-expressions.info - Runaway Regular Expressions: Catastrophic
Backtracking
- owasp.org - Regular expression Denial of
Service - ReDoS
- CWE - CWE-1333 - Inefficient Regular Expression Complexity
- docs.microsoft.com - Best practices for regular expressions
in .NET
- docs.microsoft.com - Backtracking in
Regular Expressions
- devblogs.microsoft.com - Regular Expression Improvements in .NET 7: Backtracking (and RegexOptions.NonBacktracking)
- docs.microsoft.com - Regex.MatchTimeout
Property
- docs.microsoft.com - RegexOptions
Enum (NonBacktracking option)
© 2015 - 2024 Weber Informatics LLC | Privacy Policy