HIGH regex dosaxumdynamodb

Regex Dos in Axum with Dynamodb

Regex Dos in Axum with Dynamodb — how this specific combination creates or exposes the vulnerability

Regex-based denial-of-service (ReDoS) can manifest in Axum routes that accept user input and forward it to a DynamoDB query, for example when building filter expressions or constructing table names dynamically. Axum extractors and handlers often parse path segments, query parameters, or JSON bodies into strongly typed structures; if a route uses a regex to validate or transform a parameter before using it as a DynamoDB key condition or filter, an attacker can craft a carefully designed input that causes catastrophic backtracking. This is more likely when the regex is complex, uses nested quantifiers, or operates on large strings (such as a JSON filter or a multi-value query string).

Consider an Axum handler that expects a numeric ID but applies a lenient regex to "sanitize" the value before using it as a DynamoDB key lookup. A route like GET /items/:id where :id is validated with r#"^\d{1,10}$"# and then directly interpolated into a DynamoDB KeyConditionExpression may seem safe. However, if the regex is relaxed (for example to allow optional prefixes or variable lengths) or if the input is used in a broader filter expression involving string attributes, pathological inputs can cause excessive CPU consumption on the regex engine before the request reaches DynamoDB. Because middleBrick scans the unauthenticated attack surface and includes input validation checks, it can flag such risky patterns where user-controlled data influences DynamoDB query construction in Axum services.

The interaction between Axum routing and DynamoDB usage becomes risky when developers combine dynamic expression building with insufficient input constraints. For example, constructing a FilterExpression by concatenating user input into a string without strict validation or escaping can expose the service to ReDoS via regex-heavy custom logic or via maliciously large or malformed attribute names. Even if DynamoDB itself does not use regex, the Axum layer might apply regex-based normalization or splitting on attribute values (e.g., splitting a CSV of keys) before issuing a BatchGetItem or Query. An attacker can send inputs that maximize backtracking in these regexes, leading to elevated CPU usage and degraded availability. middleBrick’s input validation checks are designed to surface these classes of issues by correlating runtime behavior with spec definitions and highlighting endpoints where user input flows into string operations that precede DynamoDB calls.

Dynamodb-Specific Remediation in Axum — concrete code fixes

To mitigate regex-related risks in Axum services that interact with DynamoDB, prefer strict, non-backtracking validation and avoid constructing DynamoDB expressions by string interpolation. Use strongly typed extractors and validate inputs against a precise character set and length before using them in queries. When building filter or key expressions, rely on DynamoDB condition builders or the AWS SDK’s expression builders rather than manual string concatenation.

Example: a safe Axum handler that retrieves an item by a numeric ID and queries a DynamoDB table using the AWS SDK for Rust (aws-sdk-dynamodb) with validated input.

use axum::{routing::get, Router};
use aws_sdk_dynamodb::Client;
use std::net::SocketAddr;
use serde::Deserialize;

#[derive(Deserialize)]
struct ItemParams {
    id: String,
}

async fn get_item(
    params: axum::extract::Query<ItemParams>,
    client: axum::extract::State<Client>,
) -> Result<String, (axum::http::StatusCode, String)> {
    // Strict validation: only allow alphanumeric IDs of reasonable length
    let id = ¶ms.id;
    if !id.chars().all(|c| c.is_ascii_alphanumeric()) || id.len() > 64 {
        return Err((axum::http::StatusCode::BAD_REQUEST, "Invalid ID".into()));
    }

    let output = client
        .get_item()
        .table_name("Items")
        .key("id", aws_sdk_dynamodb::types::AttributeValue::S(id.to_string()))
        .send()
        .await
        .map_err(|e| (axum::http::StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;

    match output.item() {
        Some(item) => Ok(format!("{item:?}")),
        None => Err((axum::http::StatusCode::NOT_FOUND, "Not found".into())),
    }
}

#[tokio::main]
async fn main() {
    let config = aws_config::load_from_env().await;
    let client = Client::new(&config);
    let app = Router::new()
        .route("/items", get(get_item))
        .with_state(client);
    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
    axum::Server::bind(&addr)
        .serve(app.into_make_service())
        .await
        .unwrap();
}

In this example, input is validated with a simple character whitelist and length bound before being used in a DynamoDB key lookup, avoiding regex entirely. If regex is required (for example to parse a compound key), ensure it is simple, uses atomic groups or possessive quantifiers where supported, and is bounded in length. Avoid accepting unbounded concatenated inputs for filter expressions; instead, use the DynamoDB ExpressionAttributeValues map and the SDK’s built-in expression builder to keep user data out of the expression string.

For scans or queries that must support richer filtering, construct the expression programmatically using the SDK’s Expression types rather than interpolating user strings. This approach eliminates regex in the request path and reduces both ReDoS surface and injection risk. middleBrick’s CLI can be used in CI to verify that endpoints which accept structured input do not rely on unsafe string assembly for DynamoDB operations, and the dashboard can track changes over time to ensure ongoing compliance with secure coding practices.

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 Axum + DynamoDB endpoints for regex-related ReDoS using middleBrick?
Run middleBrick’s unauthenticated scan against your service URL; the input validation checks will highlight endpoints where user-controlled data flows into string operations before DynamoDB calls. Use the CLI: middlebrick scan https://your-api.example.com and review findings for risky regex patterns.
Does middleBrick fix regex or DynamoDB issues automatically?
middleBrick detects and reports findings with remediation guidance; it does not fix, patch, block, or remediate. Apply the suggested code changes, such as strict validation and SDK expression builders, and re-scan to confirm improvements.