Skip to content

Latest commit

 

History

History
56 lines (43 loc) · 1.92 KB

File metadata and controls

56 lines (43 loc) · 1.92 KB

PH2137: Regex needs a timeout

Property Value
Package Philips.CodeAnalysis.SecurityAnalyzers
Diagnostic ID PH2137
Category Security
Analyzer RegexNeedsTimeoutAnalyzer
CodeFix No
Severity Error
Enabled By Default Yes

Introduction

The evaluation times of a Regular Expression (using the Regex class) can be longer depending on its input. This is because of backtracking.

Regular expression evaluation times are dependant on the input format and length, malicious input can make these evaluation times so long that the system does not respond anymore, resulting in a DOS attack.

How to solve

When constructing a new Regex instance, provide a timeout as this limits the evaluation time.

.NET 7+ give an alternative solution in the RegexOptions.NonBacktracking option, which as the name suggests disables backtracking and therefore making the evaluation times linear with the input length.

Example

Code that triggers 2 diagnostics:

class BadExample {
  public void BadCode() {
    Regex regex = new Regex(".*");
  }
}

And the corrected code:

class GoodExample {
  public void GoodCode() {
    Regex regex = new Regex(".*", RegexOptions.Compiled, TimeSpan.FromSeconds(1));
  }
}

And the corrected code in .NET 7+:

class GoodExample {
  public void GoodCode() {
    Regex regex = new Regex(".*", RegexOptions.NonBacktracking);
  }
}

Configuration

This analyzer does not offer any special configuration. The general ways of suppressing diagnostics apply.