Regex Dos in Aspnet with Firestore
Regex Dos in Aspnet with Firestore — how this specific combination creates or exposes the vulnerability
A Regular Expression Denial of Service (Regex DoS) occurs when an attacker provides input that causes a regular expression to exhibit catastrophic backtracking, consuming excessive CPU time. In an Aspnet application that uses Firestore as a backend, combining complex regex validation on user input with Firestore query construction can amplify risk if untrusted input influences regex patterns or query filters.
Consider an endpoint that accepts a Firestore document ID or a custom string tag and validates it using a permissive regex before issuing a read request. If the regex is poorly designed (e.g., using nested quantifiers without atomic groups or possessive quantifiers), an attacker can submit crafted input that causes exponential backtracking. Because Aspnet often processes requests synchronously on the thread pool, this can lead to high CPU usage and thread starvation, degrading service for all users.
When Firestore operations are triggered only after regex validation, an attacker may not directly manipulate Firestore behavior, but they can indirectly impact availability. In a scenario where the regex is built dynamically using string concatenation, an attacker might also probe for ReDoS patterns to infer validation logic. Moreover, if regex validation is applied to user-supplied values that are later used in Firestore queries (such as mapping a validated tag to a collection name or document path), malformed input that bypasses regex could lead to unexpected query behavior or injection issues, compounding the impact.
For example, an Aspnet controller might validate a product identifier with a regex before fetching product details from a Firestore collection. If the regex is vulnerable, an attacker can send a single malicious request that stalls the server, while the Firestore read never executes due to the blocked thread. In another case, if the regex is applied to user input that is later used in a Firestore array-contains or in query ordering, subtle bugs in pattern design could expose sensitive data paths or enable bypasses when combined with other weaknesses.
Because middleBrick scans API endpoints without authentication and tests input validation among 12 parallel checks, it can surface ReDoS risks alongside Firestore-related behaviors. It does not fix the regex, but it highlights the finding with severity, reproduction steps, and remediation guidance, helping teams identify problematic patterns before they are exploited in production.
Firestore-Specific Remediation in Aspnet — concrete code fixes
To mitigate Regex DoS in an Aspnet application that interacts with Firestore, focus on safe regex design, input sanitization, and defensive query patterns. Avoid constructing regex from concatenated strings, prefer compiled and non-backtracking patterns, and validate input length and structure before using it in Firestore operations.
Below are concrete code examples for Aspnet using the Google Cloud Firestore client library. These examples show how to validate input safely and perform Firestore reads without introducing regex or query risks.
1. Safe Regex Usage with Non-Backtracking Patterns
Use simple, linear regex patterns and avoid nested quantifiers. Prefer explicit length checks and character whitelisting where possible. If regex is necessary, use RegexOptions.Compiled and avoid repeated matches on untrusted input.
using System.Text.RegularExpressions;
public static bool IsValidProductId(string input)
{
// Simple, non-backtracking pattern: alphanumeric, 6–12 chars
if (string.IsNullOrEmpty(input) || input.Length < 6 || input.Length > 12)
return false;
// Use compiled regex for repeated calls; avoid complex groups or *+ constructions
return Regex.IsMatch(input, "^[A-Za-z0-9]{6,12}$", RegexOptions.Compiled);
}
2. Validated Firestore Read in an Aspnet Controller
Validate input first, then use the validated value to construct a safe Firestore document reference. Do not allow user input to directly dictate collection names unless strictly constrained and mapped.
using Google.Cloud.Firestore;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
private readonly FirestoreDb _db;
public ProductsController(FirestoreDb db)
{
_db = db;
}
[HttpGet("{productId}")]
public async Task<IActionResult> GetProduct(string productId)
{
if (!IsValidProductId(productId))
{
return BadRequest("Invalid product identifier.");
}
// Safe: productId is validated and used only in document path
DocumentReference docRef = _db.Collection("products").Document(productId);
DocumentSnapshot snapshot = await docRef.GetSnapshotAsync();
if (!snapshot.Exists)
{
return NotFound();
}
return Ok(snapshot.ConvertTo<Product>());
}
}
3. Avoid Dynamic Collection Names Based on User Input
If you must map input to collections, use a whitelist or a strict mapping instead of direct concatenation. This prevents path traversal or collection enumeration via crafted regex bypasses.
public static string MapToCollection(string category)
{
return category.ToLower() switch
{
"electronics" => "electronics_products",
"books" => "books_catalog",
"clothing" => "apparel_items",
_ => throw new ArgumentException("Invalid category")
};
}
4. MiddleBrick Integration
middleBrick can detect vulnerable regex patterns and flag related Firestore usage in unauthenticated scans. Use its findings to prioritize ReDoS fixes and validate that input validation logic does not introduce secondary risks in Firestore queries.
Defenses should combine regex hardening, strict input validation, and careful Firestore path construction. Do not rely on runtime blocking or WAF-like behavior; instead, design patterns that avoid backtracking pitfalls and limit exposure of Firestore structure through error messages.
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 |