Skip to main content

Here's an example of how to prevent a Regular Expression DoS (denial-of-service) attacks in C#.

---
title: "How to Prevent Regular Expression DoS Attacks in C#"
subtitle: "SonarCloud Security SonarAnalyzer (C#)"
author: "SonarCloud Security SonarAnalyzer (C#)"
date: October 28, 2018
source: https://sonarcloud.io/
notoc: false
---

Evaluating regular expressions against input strings is potentially an extremely
CPU - intensive task. Specially crafted regular expressions such as(a +) + will
take several seconds to evaluate the input string
`aaaaaaaaaaaaaaaaaaaaaaaaaaaaa!`. The problem is that with every additional a
added to the input, the time required to evaluate the regex doubles. The
equivalent regular expression, a+ (without grouping), is however efficiently
evaluated in milliseconds and scales linearly with the input size.

Evaluating user-provided strings as regular expressions opens the door for
Denial Of Service attacks. In the context of a web application, attackers can
force the web server to spend all of its resources evaluating regular
expressions thereby making the service inaccessible to genuine users.

## Non-compliant Code Example

```cs
public class RegexDoS : Controller
{
    // GET /RegexDoS/Validate
    public IActionResult Validate(string regex, string input)
    {
        // Enables attackers to force the web server to evaluate
        // regex such as "^(a+)+$" on inputs such as "aaaaaaaaaaaaaaaaaaaaaaaaaaaaa!"
        bool match = Regex.IsMatch(input, regex); // Non-compliant

        return Content("Valid? " + match);
    }
}
```

## Compliant Solution

```cs
public class RegexDoS : Controller
{
    // GET /RegexDoS/Validate
    public IActionResult Validate(string regex, string input)
    {
        // Option 1: Use a hard-coded regex
        bool match = Regex.IsMatch(input, "^a+$");

        // Option 2: Set a timeout on the regex's evaluation
        match = new Regex(regex, RegexOptions.None, TimeSpan.FromMilliseconds(100)).IsMatch(input);

        return Content("Valid? " + match);
    }
}
```

**Also See**

- [OWASP Regular expression Denial of Service - ReDoS](https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS)