Regex Dos in Aspnet with Cockroachdb
Regex Dos in Aspnet with Cockroachdb — how this specific combination creates or exposes the vulnerability
A Regular Expression Denial of Service (ReDoS) occurs when a regex pattern can cause catastrophic backtracking on certain inputs, consuming high CPU for long durations. In an ASP.NET application that uses CockroachDB as the backend database, the combination of complex regex validation in application code and CockroachDB query patterns can amplify the impact on availability, even when CockroachDB itself is not directly responsible for the regex processing.
ASP.NET commonly uses regex-based validation for model binding, route constraints, and input sanitization. If a developer writes a permissive pattern with nested quantifiers (e.g., (a+)+ or patterns with overlapping repetitions), an attacker can craft a long, specially designed string that causes the regex engine to explore an exponential number of paths. Because the scan reports include Availability and Input Validation checks, middleBrick can surface inefficient regexes that lead to DoS conditions in the API surface.
When such a vulnerable endpoint is backed by CockroachDB, the DoS does not originate from the database protocol, but from the application layer before requests ever reach CockroachDB. An attacker can saturate request-handling threads or the thread pool by triggering regex catastrophic backtracking, which in turn increases connection pressure on the CockroachDB cluster. Even though CockroachDB handles concurrency efficiently, an overwhelmed API service can exhaust connection pools, timeouts, or circuit-breakers, leading to elevated latencies or failed requests for legitimate users. Because CockroachDB is often deployed in distributed, multi-region topologies, the increased load and retry storms can propagate stress across nodes, making the overall system more fragile to regex-based attacks.
The interplay is observable when OpenAPI/Swagger specs are analyzed: path parameters, query strings, and body schemas may implicitly or explicitly encourage broad pattern matching. If regex validation is implemented manually rather than using constrained patterns or dedicated parsers, the unauthenticated scan can expose these risky definitions. middleBrick runs checks in parallel, including Input Validation and Availability (via rate limiting and resource exhaustion indicators), which helps highlight endpoints where regex behavior could degrade service under load.
In practice, a vulnerable endpoint might look like an ASP.NET Core controller that validates an identifier with a loose regex before issuing a CockroachDB query. An attacker can send crafted identifiers that cause exponential runtime in the regex, effectively turning a simple lookup into a CPU-bound operation. Because the scan tests the unauthenticated attack surface, it can identify such endpoints without credentials, surfacing the need for safer validation strategies and reducing reliance on runtime mitigation alone.
Cockroachdb-Specific Remediation in Aspnet — concrete code fixes
To mitigate regex-related DoS risks in an ASP.NET application that uses CockroachDB, focus on avoiding catastrophic backtracking in application-side validation and ensuring that database interactions remain efficient and resilient under load. The following patterns demonstrate secure approaches.
Use non-backtracking or bounded quantifiers. Replace patterns with nested or ambiguous quantifiers with atomic groups or explicitly bounded repeats. For example, prefer ^[A-Za-z0-9_-]{1,64}$ over ^(a+)+$. In ASP.NET model binding, use data annotations with limited character classes and lengths.
// Bad: vulnerable to ReDoS
// [RegularExpression(@"(a+)+$", ErrorMessage = "Invalid format")]
// public string Username { get; set; }
// Good: bounded, non-backtracking
[RegularExpression(@"^[A-Za-z0-9_-]{1,64}$", ErrorMessage = "Invalid username")]
public string Username { get; set; }
Validate inputs before invoking CockroachDB queries. Perform length and character-set checks early in the request pipeline to avoid unnecessary database work. Use straightforward parsers instead of complex regexes when possible.
public IActionResult GetUser(string id)
{
// Basic length and character checks (fast fail)
if (string.IsNullOrEmpty(id) || id.Length > 128 || !id.All(c => char.IsLetterOrDigit(c) || c == '-' || c == '_'))
{
return BadRequest("Invalid identifier");
}
// Safe parameterized query to CockroachDB
using var conn = new NpgsqlConnection(Configuration.GetConnectionString("CockroachDb"));
conn.Open();
using var cmd = new NpgsqlCommand("SELECT id, name FROM users WHERE id = @id LIMIT 1", conn);
cmd.Parameters.AddWithValue("@id", id);
using var reader = cmd.ExecuteReader();
if (!reader.Read()) return NotFound();
return Ok(new { Id = reader["id"], Name = reader["name"] });
}
Use asynchronous patterns and timeouts to limit resource consumption. In ASP.NET Core, ensure that endpoints use async database calls and configure command timeouts to prevent thread pool starvation if an unexpected input reaches the database layer.
public async Task<IActionResult> GetUserAsync(string id)
{
if (!IsValidId(id)) return BadRequest("Invalid identifier");
await using var conn = new NpgsqlConnection(Configuration.GetConnectionString("CockroachDb"));
await conn.OpenAsync(CancellationToken.None);
await using var cmd = new NpgsqlCommand("SELECT id, name FROM users WHERE id = @id", conn);
cmd.CommandTimeout = 10;
cmd.Parameters.AddWithValue("@id", id);
await using var reader = await cmd.ExecuteReaderAsync(CancellationToken.None);
if (!await reader.ReadAsync(CancellationToken.None)) return NotFound();
var name = reader.GetString(1);
return Ok(new { Id = id, Name = name });
}
private static bool IsValidId(string id)
{
if (string.IsNullOrEmpty(id) || id.Length > 128) return false;
foreach (var ch in id)
{
if (!char.IsLetterOrDigit(ch) && ch != '-' && ch != '_') return false;
}
return true;
}
Leverage middleware for global protection. Implement regex usage policies and request size limits in ASP.NET Core to reduce the attack surface before requests reach handlers that may interact with CockroachDB.
// In Startup.cs or Program.cs
app.Use(async (context, next) =>
{
// Reject overly long paths or query strings early
if (context.Request.Path.Value?.Length > 1024 ||
context.Request.QueryString.Value?.Length > 2048)
{
context.Response.StatusCode = 400;
return;
}
await next();
});
By combining bounded validation, early checks, safe database drivers, and timeouts, you reduce the likelihood that regex inefficiencies or malicious inputs will disrupt service availability for CockroachDB-backed APIs.
Related CWEs: inputValidation
| CWE ID | Name | Severity |
|---|---|---|
| CWE-20 | Improper Input Validation | HIGH |
| CWE-22 | Path Traversal | HIGH |
| CWE-74 | Injection | CRITICAL |
| CWE-77 | Command Injection | CRITICAL |
| CWE-78 | OS Command Injection | CRITICAL |
| CWE-79 | Cross-site Scripting (XSS) | HIGH |
| CWE-89 | SQL Injection | CRITICAL |
| CWE-90 | LDAP Injection | HIGH |
| CWE-91 | XML Injection | HIGH |
| CWE-94 | Code Injection | CRITICAL |