HIGH regex dosaspnet

Regex Dos in Aspnet

How Regex Dos Manifests in Aspnet

Regular expression denial of service (ReDoS) attacks exploit the worst-case computational complexity of certain regex patterns. In Aspnet applications, this vulnerability often surfaces in unexpected places, creating denial of service conditions that can bring down entire web applications.

The classic ReDoS scenario involves regex patterns with nested quantifiers or ambiguous alternations. When an attacker crafts input that forces the regex engine into exponential backtracking, the CPU usage spikes dramatically. For Aspnet applications, this typically occurs in:

  • Model binding validation attributes
  • Route constraints and parameter validation
  • Custom middleware performing request filtering
  • Input sanitization in controllers
  • Logging and monitoring components that parse request data

A common Aspnet-specific manifestation occurs with route constraints. Consider this Aspnet Core route definition:

[HttpGet("/api/products/{id:regex(^[a-zA-Z0-9]{1,20}$)}")]

While this appears safe, an attacker could send a carefully crafted string like "aaaaaaaaaaa!" that triggers catastrophic backtracking. The regex engine attempts to match the input against the pattern, exploring numerous permutations before failing.

Another Aspnet-specific scenario involves model validation attributes. Many developers use regex in [RegularExpression] attributes for input validation:

[RegularExpression(@"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$")]

This email validation pattern, while common, contains nested quantifiers that can be exploited. An attacker sending a string like "test@test.com" with strategically placed characters can cause the validation to consume excessive CPU time.

Aspnet MVC's model binding system also processes regex patterns during deserialization. When binding JSON or form data to model properties, regex validation runs synchronously, blocking the request pipeline. A malicious request with a large payload containing ReDoS-vulnerable patterns can tie up thread pool threads, eventually exhausting available threads and causing HTTP 502 errors across the application.

Logging middleware presents another attack vector. Aspnet applications often log request parameters, headers, or payloads. If the logging system uses regex to parse or redact sensitive information, and that regex is vulnerable, an attacker can trigger ReDoS through the logging pipeline itself, even if the core application logic is unaffected.

The impact is particularly severe in Aspnet applications because of the synchronous nature of many Aspnet components. Unlike Node.js or Python applications that might handle such attacks with async patterns, Aspnet's thread-per-request model means each ReDoS attack consumes a dedicated thread, quickly depleting the thread pool and causing service degradation.

Aspnet-Specific Detection

Detecting ReDoS vulnerabilities in Aspnet applications requires a multi-faceted approach. Static analysis tools often miss these issues because they struggle with regex complexity analysis. Dynamic testing is more effective but requires specialized techniques.

middleBrick's scanning approach for Aspnet applications includes several ReDoS-specific checks. The scanner analyzes route definitions, model validation attributes, and middleware configurations for patterns known to be vulnerable. It tests these patterns with crafted inputs designed to trigger exponential backtracking.

For Aspnet Core applications, middleBrick examines the compiled regex patterns at runtime. It identifies nested quantifiers, ambiguous alternations, and other complexity indicators. The scanner then generates test payloads that maximize backtracking potential for each identified pattern.

Key detection areas include:

1. Route constraints in Startup.cs or Program.cs
2. Model validation attributes in ViewModel classes
3. Custom middleware regex usage
4. Filter attributes with regex validation
5. SignalR hub message validation

middleBrick's LLM security module also detects when regex patterns are used in AI-related Aspnet components, such as prompt validation or input sanitization for AI endpoints. This is particularly important as AI applications often process large text inputs where ReDoS attacks are more effective.

The scanner provides specific findings for Aspnet applications, including:

  • Line numbers and file locations of vulnerable regex patterns
  • Estimated attack complexity (how difficult it is to exploit)
  • CPU time estimates for worst-case scenarios
  • Specific test cases that demonstrate the vulnerability

For CI/CD integration, middleBrick's GitHub Action can be configured to fail builds when ReDoS vulnerabilities are detected in Aspnet code. This ensures that new regex patterns added during development are automatically screened before deployment.

Performance monitoring in production Aspnet applications can also help detect ongoing ReDoS attacks. Monitoring tools should watch for:

  • Sudden spikes in CPU usage from specific endpoints
  • Increased request processing times for certain routes
  • Thread pool exhaustion patterns
  • Memory growth from regex backtracking

middleBrick's continuous monitoring feature can alert teams when new ReDoS vulnerabilities are introduced through code changes, providing an additional layer of security beyond initial scanning.

Aspnet-Specific Remediation

Remediating ReDoS vulnerabilities in Aspnet applications requires both immediate fixes and architectural changes. The most effective approach combines regex pattern optimization with defensive coding practices.

For immediate fixes, replace vulnerable regex patterns with safer alternatives. Consider this Aspnet Core example:

// Vulnerable pattern
[RegularExpression(@"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$")]

Replace with a non-regex approach or a safer pattern:

// Safer alternative using built-in validation
[EmailAddress]

For Aspnet MVC route constraints, avoid complex regex patterns entirely. Use simple constraints or custom route handlers:

// Instead of complex regex
[HttpGet("/api/products/{id:int}")]

When regex is unavoidable, use timeouts to prevent ReDoS:

public class SafeRegexAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        if (value == null) return true;
        
        var input = value.ToString();
        var regex = new Regex(@"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$", 
            RegexOptions.IgnoreCase | RegexOptions.CultureInvariant,
            TimeSpan.FromMilliseconds(100)); // 100ms timeout
            
        try
        {
            return regex.IsMatch(input);
        }
        catch (RegexMatchTimeoutException)
        {
            return false; // Treat timeout as validation failure
        }
    }
}

For Aspnet Core middleware, implement rate limiting on endpoints that use regex validation. This limits the impact of potential ReDoS attacks:

public void ConfigureServices(IServiceCollection services)
{
    services.AddRateLimiting();
    services.AddControllers(options =>
    {
        options.Filters.Add(new RequestRateLimitFilter("regexValidation"));
    });
}

Aspnet's built-in validation attributes provide safer alternatives to custom regex. Use [EmailAddress], [Phone], [Url], and other specialized attributes instead of generic regex patterns.

For complex validation scenarios, consider moving from regex to state machine validation or parser combinators. These approaches provide better performance guarantees and are less susceptible to ReDoS:

public class EmailValidator
{
    public bool IsValid(string email)
    {
        // Simple character-by-character validation
        // More predictable performance than regex
        if (string.IsNullOrWhiteSpace(email)) return false;
        
        int atCount = 0;
        bool hasLocalPart = false;
        bool hasDomain = false;
        
        foreach (char c in email)
        {
            if (c == '@') atCount++;
            else if (atCount == 0) hasLocalPart = true;
            else hasDomain = true;
        }
        
        return atCount == 1 && hasLocalPart && hasDomain;
    }
}

Implement circuit breaker patterns for Aspnet endpoints that perform regex validation. This prevents cascading failures when ReDoS attacks occur:

public class RegexValidationCircuitBreaker
{
    private readonly CircuitBreaker _breaker = new CircuitBreaker(failureThreshold: 5, timeout: TimeSpan.FromMinutes(1));
    
    public async Task<bool> ValidateAsync(string input)
    {
        if (_breaker.IsOpen) return false;
        
        try
        {
            var result = await PerformValidationAsync(input);
            _breaker.OnSuccess();
            return result;
        }
        catch
        {
            _breaker.OnFailure();
            throw;
        }
    }
}

For Aspnet applications using Entity Framework, be cautious with LINQ queries that use regex in database operations. These can also be vulnerable to ReDoS when translated to SQL:

// Potentially vulnerable
var results = context.Users.Where(u => Regex.IsMatch(u.Email, pattern)).ToList();

Instead, use database-native pattern matching or pre-filter in application code with proper timeouts.

Related CWEs: inputValidation

CWE IDNameSeverity
CWE-20Improper Input Validation HIGH
CWE-22Path Traversal HIGH
CWE-74Injection CRITICAL
CWE-77Command Injection CRITICAL
CWE-78OS Command Injection CRITICAL
CWE-79Cross-site Scripting (XSS) HIGH
CWE-89SQL Injection CRITICAL
CWE-90LDAP Injection HIGH
CWE-91XML Injection HIGH
CWE-94Code Injection CRITICAL

Frequently Asked Questions

How can I test my Aspnet application for ReDoS vulnerabilities?
Use middleBrick's API security scanner to automatically detect ReDoS patterns in your Aspnet application. The scanner analyzes route constraints, model validation attributes, and middleware configurations. For manual testing, craft inputs with many repeated characters for any regex patterns in your application and monitor CPU usage. Tools like regsz can help identify vulnerable regex patterns before deployment.
Are there any Aspnet-specific features that help prevent ReDoS attacks?
Yes, Aspnet Core provides several built-in features. The Regex class supports timeout parameters (added in .NET 4.5), allowing you to limit how long a regex can run. Aspnet's model validation system also provides specialized attributes like [EmailAddress] that use optimized validation logic instead of regex. Additionally, Aspnet Core's middleware pipeline allows you to implement request filtering and rate limiting to mitigate the impact of potential ReDoS attacks.