csharp.lang.security.regular-expression-dos.regular-expression-dos.regular-expression-dos
semgrep
Author
172
Download Count*
License
When using System.Text.RegularExpressions
to process untrusted input, pass a timeout. A malicious user can provide input to RegularExpressions
that abuses the backtracking behaviour of this regular expression engine. This will lead to excessive CPU usage, causing a Denial-of-Service attack
Run Locally
Run in CI
Defintion
rules:
- id: regular-expression-dos
severity: WARNING
languages:
- C#
metadata:
cwe:
- "CWE-1333: Inefficient Regular Expression Complexity"
owasp: A01:2017 - Injection
references:
- https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS
- https://docs.microsoft.com/en-us/dotnet/standard/base-types/regular-expressions#regular-expression-examples
category: security
technology:
- .net
confidence: MEDIUM
subcategory:
- audit
likelihood: LOW
impact: MEDIUM
license: Commons Clause License Condition v1.0[LGPL-2.1-only]
vulnerability_class:
- Denial-of-Service (DoS)
message: When using `System.Text.RegularExpressions` to process untrusted input,
pass a timeout. A malicious user can provide input to
`RegularExpressions` that abuses the backtracking behaviour of this
regular expression engine. This will lead to excessive CPU usage, causing
a Denial-of-Service attack
patterns:
- pattern-inside: |
using System.Text.RegularExpressions;
...
- pattern-either:
- pattern: |
public $T $F($X)
{
Regex $Y = new Regex($P);
...
$Y.Match($X);
}
- pattern: |
public $T $F($X)
{
Regex $Y = new Regex($P, $O);
...
$Y.Match($X);
}
- pattern: |
public $T $F($X)
{
... Regex.Match($X, $P);
}
- pattern: |
public $T $F($X)
{
... Regex.Match($X, $P, $O);
}
Examples
regular-expression-dos.cs
using System.Text.RegularExpressions;
namespace RegularExpressionsDos
{
public class RegularExpressionsDos
{
// ruleid: regular-expression-dos
public void ValidateRegex(string search)
{
Regex rgx = new Regex("^A(B|C+)+D");
rgx.Match(search);
}
// ruleid: regular-expression-dos
public void ValidateRegex2(string search)
{
Regex rgx = new Regex("^A(B|C+)+D", new RegexOptions { });
rgx.Match(search);
}
// ok: regular-expression-dos
public void ValidateRegex3(string search)
{
Regex rgx = new Regex("^A(B|C+)+D", new RegexOptions { }, TimeSpan.FromSeconds(2000));
rgx.Match(search);
}
// ruleid: regular-expression-dos
public void Validate4(string search)
{
var pattern = @"^A(B|C+)+D";
var result = Regex.Match(search, pattern);
}
// ruleid: regular-expression-dos
public void Validate5(string search)
{
var pattern = @"^A(B|C+)+D";
var result = Regex.Match(search, pattern, new RegexOptions { });
}
// ok: regular-expression-dos
public void Validate5(string search)
{
var pattern = @"^A(B|C+)+D";
var result = Regex.Match(search, pattern, new RegexOptions { }, TimeSpan.FromSeconds(2000));
}
}
}
Short Link: https://sg.run/RPyY