Regex Dos in Aspnet with Dynamodb
Regex Dos in Aspnet with Dynamodb — how this specific combination creates or exposes the vulnerability
Regular expression denial of service (ReDoS) occurs when a regular expression exhibits worst-case time complexity on certain inputs, causing excessive CPU consumption. In an ASP.NET application that interacts with DynamoDB, combining complex regex validation with DynamoDB request construction can amplify risk if user-controlled data influences the regex pattern or the data used to build queries.
ASP.NET often uses model binding and action parameters that are validated with custom or framework regex attributes (e.g., [RegularExpression]). If these regexes are applied to untrusted input that is later embedded into a DynamoDB condition expression or used to construct low-level query parameters, pathological inputs can cause the regex engine to backtrack extensively. Because DynamoDB operations are typically invoked synchronously within request processing, a slow regex evaluation adds directly to request latency and can exhaust thread pool resources under concurrent attack.
The interaction surface includes:
- Validation regex applied to IDs or key attributes that are used verbatim in DynamoDB key conditions (e.g., partition key or sort key expressions).
- Regex-based sanitization or extraction from JSON payloads before building
UpdateItemorPutItemrequests, where a maliciously crafted value triggers catastrophic backtracking. - Dynamic construction of filter expressions where regex-derived substrings are concatenated, potentially creating expressions that are both complex and regex-dependent for parts of the logic.
Real-world patterns that increase exposure include using common but vulnerable patterns such as repeated quantifiers without atomic groups or possessive quantifiers (e.g., (a+)+), regexes that rely on alternation over large character classes, and naive trimming or validation of keys that map to DynamoDB attribute names. Because DynamoDB does not perform regex evaluation, the cost is entirely incurred within the ASP.NET runtime before any service call is issued, making it a classic ReDoS vector at the application layer.
An example scenario: an endpoint accepts an itemId query parameter, validates it with a permissive regex to ensure format, then uses that value in a GetItem key. A crafted input like a...a (many repetitions) can cause the regex engine to spend disproportionate time attempting matches and backtracking, delaying the DynamoDB call and increasing resource saturation under load.
Dynamodb-Specific Remediation in Aspnet — concrete code fixes
Mitigation focuses on avoiding regex over user-controlled data used in DynamoDB request construction and validating inputs with bounded, non-backtracking logic. Prefer strict length and format checks, use constant-time comparisons where feasible, and avoid embedding raw user input into condition or key expressions.
Example: Safe key validation and DynamoDB GetItem
Replace broad regex validation with a bounded check and direct parameter usage. Do not construct expression strings by concatenating raw user input.
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.Model;
using System.Text.RegularExpressions;
public class ItemService
{
private readonly IAmazonDynamoDB _ddb;
private static readonly Regex SafeIdRegex = new Regex("^[A-Z0-9-]{1,64}$", RegexOptions.Compiled | RegexOptions.CultureInvariant);
public ItemService(IAmazonDynamoDB ddb)
{
_ddb = ddb;
}
public async Task<GetItemResponse> GetItemAsync(string itemId)
{
// Bounded format check instead of permissive regex; fail early on malformed input
if (string.IsNullOrEmpty(itemId) || !SafeIdRegex.IsMatch(itemId))
{
throw new ArgumentException("Invalid item identifier");
}
var request = new GetItemRequest
{
TableName = "Items",
Key = new Dictionary<string, AttributeValue>
{
{ "ItemId", new AttributeValue { S = itemId } }
},
ConsistentRead = true
};
var response = await _ddb.GetItemAsync(request);
return response;
}
}
Example: Avoid regex in UpdateItem condition expressions
Do not build condition expressions that include regex or patterns derived from user input. Use explicit attribute checks instead.
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.Model;
public class InventoryService
{
private readonly IAmazonDynamoDB _ddb;
public InventoryService(IAmazonDynamoDB ddb)
{
_ddb = ddb;
}
public async Task UpdateStockAsync(string sku, int quantity)
{
// Avoid regex-derived condition parts; use direct attribute existence checks
var updateRequest = new UpdateItemRequest
{
TableName = "Inventory",
Key = new Dictionary<string, AttributeValue>
{
{ "Sku", new AttributeValue { S = sku } }
},
UpdateExpression = "SET Available = :val",
ConditionExpression = "attribute_exists(Sku)",
ExpressionAttributeValues = new Dictionary<string, AttributeValue>
{
{ ":val", new AttributeValue { N = quantity.ToString() } }
},
ReturnValuesOnConditionCheckFailure = "ALL_OLD"
};
await _ddb.UpdateItemAsync(updateRequest);
}
}
General defensive practices
- Use
RegexOptions.Compiledand avoid patterns with nested quantifiers; prefer simple character class and length bounds. - Validate IDs and keys with whitelist patterns (e3-9, a-z, A-Z, limited symbols) and enforce maximum lengths to bound backtracking work.
- Keep regex usage limited to client-side validation; never use regex to construct DynamoDB expression attribute values or condition strings dynamically.
- Instrument and monitor request duration and thread pool metrics to detect anomalous CPU usage that may indicate ongoing abuse.
By constraining regex application to safe, bounded checks and avoiding dynamic expression assembly from untrusted sources, you reduce ReDoS risk while preserving the utility of input validation in ASP.NET applications using DynamoDB.
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 |