46 lines
983 B
Plaintext
46 lines
983 B
Plaintext
![]() |
=== How to fix it in .NET
|
||
|
|
||
|
The following non-compliant code is vulnerable to Regex Denial of Service
|
||
|
because untrusted data is used as a regex to scan a string without prior
|
||
|
sanitization or validation.
|
||
|
|
||
|
[cols="a"]
|
||
|
|===
|
||
|
h| Non-compliant code example
|
||
|
|
|
||
|
[source,csharp]
|
||
|
----
|
||
|
public class ExampleController : Controller
|
||
|
{
|
||
|
public IActionResult Validate(string regex, string input)
|
||
|
{
|
||
|
bool match = Regex.IsMatch(input, regex); // Noncompliant
|
||
|
|
||
|
return Json(match);
|
||
|
}
|
||
|
}
|
||
|
----
|
||
|
h| Compliant solution
|
||
|
|
|
||
|
[source,csharp]
|
||
|
----
|
||
|
public class ExampleController : Controller
|
||
|
{
|
||
|
public IActionResult Validate(string regex, string input)
|
||
|
{
|
||
|
bool match = Regex.IsMatch(input, Regex.Escape(regex));
|
||
|
|
||
|
return Json(match);
|
||
|
}
|
||
|
}
|
||
|
----
|
||
|
|===
|
||
|
|
||
|
=== How does this work?
|
||
|
|
||
|
include::../../common/fix/validation.adoc[]
|
||
|
|
||
|
In the compliant solution example, `Regex.Escape` escapes metacharacters and escape sequences that
|
||
|
could have broken the initially intended logic.
|
||
|
|