44 lines
1010 B
Plaintext
44 lines
1010 B
Plaintext
=== How to fix it in .NET
|
|
|
|
The following noncompliant 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.
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,csharp,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
public class ExampleController : Controller
|
|
{
|
|
public IActionResult Validate(string regex, string input)
|
|
{
|
|
bool match = Regex.IsMatch(input, regex);
|
|
|
|
return Json(match);
|
|
}
|
|
}
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,csharp,diff-id=1,diff-type=compliant]
|
|
----
|
|
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.
|
|
|