Review code for regex injection vulnerabilities
Review code for regex injection vulnerabilities
Microsoft docsDescription
When working with untrusted input, be mindful of regex injection attacks. An attacker can use regex injection to maliciously modify a regular expression, to make the regex match unintended results, or to make the regex consume excessive CPU resulting in a Denial of Service attack.
This rule attempts to find input from HTTP requests reaching a regular expression. This rule can't track data across assemblies. For example, if one assembly reads the HTTP request input and then passes it to another assembly that creates a regular expression, this rule won't produce a warning. There is a configurable limit to how deep this rule will analyze data flow across method calls. See Analyzer Configuration for how to configure the limit in an EditorConfig file.
Cause
Potentially untrusted HTTP request input reaches a regular expression.
By default, this rule analyzes the entire codebase, but this is configurable.
How to fix violations
Some mitigations against regex injections include:
- Always use a match timeout when using regular expressions.
- Avoid using regular expressions based on user input.
- Escape special characters from user input by calling System.Text.RegularExpressions.Regex.Escape or another method.
- Allow only non-special characters from user input.
Example
using System;
using System.Text.RegularExpressions;
public partial class WebForm : System.Web.UI.Page
{
public string SearchableText { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
string findTerm = Request.Form["findTerm"];
Match m = Regex.Match(SearchableText, "^term=" + findTerm);
}
}When to suppress
If you know you're using a match timeout and the user input is free of special characters, it's okay to suppress this warning.