CRITICAL
Rule Definition
Regular expressions that perform poorly are surprisingly easy to create. In some cases, regular expression operations that rely on excessive backtracking can appear to stop responding when they process text that nearly matches the regular expression pattern.
Starting with the .NET Framework 4.5, you can define a time-out interval for regular expression matches to limit excessive backtracking. Depending on the regular expression pattern and the input text, the execution time may exceed the specified time-out interval, but it will not spend more time backtracking than the specified time-out interval.
Remediation
Use the timeout parameter of the constructor and static method.
Violation Code Sample
Regex format = new Regex("(a|aa)+$"); // violation
==========================================================
Match match = Regex.Match("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa5", "(a|aa)+$"); // violation
Fixed Code Sample
Regex format = new Regex("(a|aa)+$", RegexOptions.None, new TimeSpan(0, 0, 10)); // No violation
==========================================================
Match match = Regex.Match("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa5", "(a|aa)+$", RegexOptions.None, new TimeSpan(0, 0, 10)); //No violation
Reference
MS documentation - Defining a Time-Out Value
https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex?view=net-8.0#define_timeout
MS documentation - Details of regular expression behavior
https://learn.microsoft.com/en-us/dotnet/standard/base-types/details-of-regular-expression-behavior
OWASP: Regular expression Denial of Service - ReDoS
https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS
CWE-400: Uncontrolled Resource Consumption
https://cwe.mitre.org/data/definitions/400.html
Related Technologies
Technical Criterion
CWE-664 - Improper Control of a Resource Through its Lifetime [Pillar]
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.