HIGH regex dosaspnetdynamodb

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 UpdateItem or PutItem requests, 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.Compiled and 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 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

Is it safe to use [RegularExpression] attributes on DynamoDB key inputs in ASP.NET?
It can be safe if the regex is strictly bounded (whitelist characters and length) and does not embed user input into DynamoDB expressions. Avoid permissive or nested quantifier patterns and prefer simple length/format checks; never build condition strings by concatenating raw validated input.
Can DynamoDB scanning or queries be impacted by regex-based validation in the application layer?
DynamoDB itself does not evaluate regex, so scanning/query performance is unaffected. However, if validation is slow due to ReDoS-prone patterns, it adds latency to each request and can increase resource utilization in ASP.NET, indirectly affecting throughput and stability under load.