C Sharp Redos Vulnerable Regex
Description
Detects regular expressions vulnerable to ReDoS (Regular Expression Denial of Service) attacks in C# code. ReDoS vulnerabilities occur when a regex pattern can cause catastrophic backtracking, leading to excessive CPU usage that could freeze or crash the application.
Detection Strategy
• Identifies calls to .NET Regex methods: IsMatch, Match, and Matches
• Examines the regular expression pattern used in these method calls
• Reports a vulnerability if the regex pattern contains constructs that could cause catastrophic backtracking (e.g., nested repetition quantifiers, overlapping patterns)
• Flags regex patterns that could allow an attacker to supply input that causes exponential evaluation time
Vulnerable code example
using System.Text.RegularExpressions;
public class RegexController
{
public void ValidateInput(string userInput)
{
// Unsafe: Using unvalidated input directly in regex pattern
Regex regex = new Regex(userInput, RegexOptions.IgnoreCase);...✅ Secure code example
using System.Text.RegularExpressions;
public class RegexController
{
public void ValidateInput(string userInput)
{
// Safe: Use a predefined pattern instead of user input as regex pattern
const string safePattern = @"^[a-zA-Z0-9]+$"; // Define expected pattern...Search for vulnerabilities in your apps for free with Fluid Attacks' automated security testing! Start your 21-day free trial and discover the benefits of the Continuous Hacking Essential plan. If you prefer the Advanced plan, which includes the expertise of Fluid Attacks' hacking team, fill out this contact form.