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 Sub RegexPattern(Input As String)
Dim EmailPattern As New Regex(".+@.+", RegexOptions.None)
Dim IsNumber as Boolean = Regex.IsMatch(Input, "[0-9]+")
Dim IsLetterA as Boolean = Regex.IsMatch(Input, "(a+)+")
End Sub
Compliant Solution
Public Sub RegexPattern(Input As String)
Dim EmailPattern As New Regex(".+@.+", RegexOptions.None, TimeSpan.FromMilliseconds(100))
Dim IsNumber as Boolean = Regex.IsMatch(Input, "[0-9]+", RegexOptions.None, TimeSpan.FromMilliseconds(100))
Dim IsLetterA As Boolean = Regex.IsMatch(Input, "(a+)+", RegexOptions.NonBacktracking) '.Net 7 And above
AppDomain.CurrentDomain.SetData("REGEX_DEFAULT_MATCH_TIMEOUT", TimeSpan.FromMilliseconds(100)) 'process-wide setting
End Sub
See