This is ReDos checking for .NET C#.
Based on Backtracking in .NET Regular Expressions | Microsoft Learn and WEB+BDB PRESS Vol.130.
In C#, Regex engine implement with VM (NFA) so develop has responsibility for it's quality of matching.
.NET 7 introduce opt-in DFA Regex engine with RegexOptions.NonBackTracking
.
See [Regular Expression behavior | Microsoft Learn)[https://learn.microsoft.com/en-us/dotnet/standard/base-types/details-of-regular-expression-behavior] for why .NET Regex is using NFA.
However, there are ReDos vulnerability on VM (NFA) engine. This sample shows back track effect and mitigation.
- NotBacktrack: No backtrack pattern and input.
- BacktrackInput: Has backtrack pattern and input.
- BacktrackInput30: Has backtrack pattern and 30 charactor length input.
- BacktrackInput31: Has backtrack pattern and 31 charactor length input.
- BacktrackInput31b: Has backtrack pattern and 31 charactor length input, missed result increase effect.
- ComplexBacktrackMatch: Complex backtrack pattern and input. Match effect with backtrack even result is matched.
- ComplexBacktrackMissed: Complex backtrack pattern and input. More effect then match when missed.
- NoLookBehindAssertion: Email input and backtrack, no mitigation.
- LookBehindAssertion: Email input and LookBegind backtrack mitigation.
- NoLookAheadAssertion: Input and backtrack, no mitigation.
- LookAheadAssertion: Unput and LookAhead backtrack mitigation.
- Session level timeout: In general Dos can mitigate with session level timeout. It can offer with Middleware or something similar.
- Use DFA match implemenation: DFA generally worth match speed or memory effiency, but it guaranteed match complete in liner time. .NET 7 will introduce DFA with RegexOptions.NonBacktracking. Other languages supported with re2(C++), regexp(Go) and regex(Rust). See RegexOptions.Constrained · Issue #57891 · dotnet/runtime and Add RegexOptions.NonBacktracking by stephentoub · Pull Request #60607 · dotnet/runtime for .NET 7 DFA detail.
- Restrict input length: Accept only shorter input can ignore ReDos impact. However exponential ReDos may have X sec impact on 100 letter and around.
- ReDos detection: recheck is one of libary detect ReDos.
- Don't use Regular expression: You know, trim space doesn't need regular expressions.
- Regex Timeout: .NET C# Regex has timeout option like
new Regex(pattern, RegexOptions.IgnoreCase, TimeSpan.FromSeconds(1));
, also Ruby 3.2 plan it. - Selective memorize: Using Selective Memorization to Defeat Regular Expression Denial of Service(ReDos) explains correct cache can make regular expression linear, but it describe M-NFA consume memory.