c# regex - regex for c# - regex c#

C# Regex DoS: When Patterns Become Attack Vectors

When Regular Expressions Turn Against Performance  

A single line of C# regex can bring a production API to its knees. Poorly written patterns trigger catastrophic backtracking, burning CPU cycles, and locking threads. This is the classic Regular Expression Denial of Service (ReDoS), a subtle yet dangerous attack vector hidden in your code.

⚠️Insecure example, for educational purposes only. Do not use in production.

string pattern = @"(a+)+$";  // Vulnerable regex c#
Regex regex = new Regex(pattern);
bool isMatch = regex.IsMatch("aaaaaaaaaaaaaaaaaaaaaaaa!");

This regex for C# suffers from nested quantifiers that cause exponential backtracking. A long, malicious string can freeze an endpoint or microservice.

Secure version:

string pattern = @"^a+$";  // Safe simplified regex for C#
Regex regex = new Regex(pattern, RegexOptions.Compiled, TimeSpan.FromMilliseconds(200));
bool isMatch = regex.IsMatch("aaaaaaaaaaa");

Educational note: Always use timeouts (RegexOptions + TimeSpan) and simplify nested groups. In regex c#, performance validation is a security requirement, not an optimization.

Why C# Regex Patterns Become Vulnerable

Ambiguous quantifiers (.*, .+, or (a+)+) and unbounded repetition make regex a common DoS target.
When these appear in user-driven contexts, like input validation or log parsing, a single crafted payload can monopolize CPU.

⚠️Insecure example, for educational purposes only. Do not use in production.

// Vulnerable email validation regex for C#
var pattern = @"^([a-zA-Z0-9_\-\.]+)@([\w\-]+\.)+([a-zA-Z]{2,4})$";
var input = "a".PadLeft(10000, 'a') + "@example.com";
Regex.IsMatch(input, pattern);  // May hang or cause ReDoS

Secure version:

// Safer regex c# pattern
var pattern = @"^[^@\s]+@[^@\s]+\.[^@\s]+$";
Regex regex = new Regex(pattern, RegexOptions.Compiled, TimeSpan.FromMilliseconds(300));
bool isValid = regex.IsMatch("user@example.com");

Educational note: Avoid ambiguous repetition, restrict input size, and always benchmark regex performance under load. Functional snippet, enforce timeouts and maximum input length as guards in production.

Real Impact in APIs and CI/CD Workflows

Unsafe regex for C# isn’t limited to validation forms. Developers embed patterns in log filters, webhook matchers, and automated scans. In CI/CD, one unsafe pattern can stall the entire pipeline.

⚠️Insecure example, for educational purposes only. Do not use in production.

// Regex used to match commit messages in a CI job
var regex = new Regex(userInputPattern);
if (regex.IsMatch(commitMessage)) { /* process */ }
If userInputPattern contains (a+)+$, it can freeze the build agent.

Never process user-supplied regex without validation or timeout control.

Secure version:

// Safe usage in CI/CD context
if (userInputPattern.Length < 100 && !userInputPattern.Contains("++"))
{
    Regex regex = new Regex(userInputPattern, RegexOptions.Compiled, TimeSpan.FromMilliseconds(100));
    if (regex.IsMatch(commitMessage)) { /* safely process */ }
}

Educational note: Validate external regex input before execution. Add explicit length checks and enforce timeouts in pipelines.

Safe Practices to Prevent C# Regex DoS

ReDoS prevention in regex c# should be baked into your development and DevSecOps workflow. Here’s how to make it safe by default:

Best Practices

  1. Always set timeouts on all regex evaluations.
  2. Avoid catastrophic patterns, no nested quantifiers or ambiguous groups.
  3. Limit input size before passing to regex.
  4. Precompile trusted patterns with RegexOptions.Compiled.
  5. Sanitize user-supplied expressions or whitelist allowed patterns.

Mini preventive checklist

  • Review every regex for C# usage in your codebase.
  • Apply TimeSpan timeouts consistently.
  • Restrict input lengths on API and CI inputs.
  • Test regex performance before release.
  • Automate static regex scanning in CI/CD.

Educational note: Treat regex patterns as untrusted code. They deserve the same scrutiny as SQL or command execution.

How Xygeni Detects Risky C# Regex Usage

Xygeni Code Security automatically detects unsafe regex C# patterns during static analysis. It identifies catastrophic backtracking, missing timeouts, and patterns likely to hang services. In CI/CD, Xygeni acts as a DevSecOps gate, blocking unsafe regex for C# before it merges or deploys.

# Never expose real tokens, credentials, or internal URLs in pipelines
- name: Regex Safety Scan
  run: dotnet xygeni validate --rules regex ,performance --fail-on-risk

Educational note: Integrating Xygeni ensures secure regex handling across builds and environments, preventing regressions and DoS exposure before deployment.

Your Regex Is Powerful, Make Sure It Isn’t Weaponized

ReDoS vulnerabilities turn innocent-looking C# regex into a denial-of-service weapon. Unsafe regex for C# patterns are a common oversight,  until they freeze production or break CI/CD.

Make regex safety part of your coding hygiene:

  • Always use timeouts.
  • Avoid nested quantifiers.
  • Restrict user input.
  • Automate checks using Xygeni Code Security.

Regex will always be powerful, but with careful design, your regex C # patterns won’t become your next incident report.

sca-tools-software-composition-analysis-tools
Prioritize, remediate, and secure your software risks
7-day free trial
No credit card required

Secure your Software Development and Delivery

with Xygeni Product Suite