HIGH regex doschidynamodb

Regex Dos in Chi with Dynamodb

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

Regex Denial-of-Service (ReDoS) occurs when a regular expression exhibits catastrophic backtracking on certain inputs. In Chi, a common Go HTTP router, developers often compose route matchers using regular expressions. When those patterns are applied to path segments that are later used to query DynamoDB, the combination can amplify risk: the regex runs on every incoming request in the same process, while the resulting keys or filter expressions target DynamoDB operations.

Consider a Chi route that captures an identifier intended to be a DynamoDB partition key:

import (
    "github.com/go-chi/chi/v5"
    "regexp"
)

func main() {
    r := chi.NewRouter()
    // Vulnerable: complex regex on user input that becomes a DynamoDB key
    r.Get("/{id:[a-zA-Z0-9]{1,20}@[a-zA-Z0-9]{1,10}", func(w http.ResponseWriter, r *http.Request) {
        id := chi.URLParam(r, "id")
        // Use id to build a DynamoDB GetItem key
        key := map[string]*dynamodb.AttributeValue{
            "PK": {S: aws.String(id)},
        }
        // ... perform DynamoDB call
    })
}

If the regex is non-optimized (e.g., overlapping quantifiers or ambiguous groupings), an attacker can send crafted paths that cause exponential backtracking. Even though the route pattern appears constrained, subtle ambiguities can turn a short path into a CPU-intensive match. Meanwhile, the extracted id is directly embedded into a DynamoDB key. This means the expensive regex evaluation precedes any service call, turning a single malicious request into high server CPU load before any backend operation occurs.

In broader scanning contexts, tools like middleBrick detect such patterns by analyzing route definitions and flagging complex regex usage in Chi routers. The scanner does not execute or probe the regex behavior directly; it inspects the source and configuration to highlight where user-controlled input is processed by expressive matchers before being passed to services like DynamoDB. This helps teams identify risky compositions before deployment.

When OpenAPI specs are available, middleBrick cross-references spec definitions with runtime findings. For example, if a path parameter is defined with an overly permissive pattern and the operation interacts with DynamoDB, the report can highlight both the routing risk and the downstream data store usage. This correlation is valuable because it ties expressive routing constructs to specific backend integrations, making it easier to prioritize fixes.

Dynamodb-Specific Remediation in Chi — concrete code fixes

Remediation focuses on reducing regex complexity and avoiding user-controlled input in patterns that trigger heavy backtracking. Prefer exact path segments or simple, bounded patterns for Chi routes, and validate or sanitize values before using them in DynamoDB key construction.

1) Replace complex inline regex with a simple path segment and validate afterwards:

import (
    "github.com/go-chi/chi/v5"
    "regexp"
)

// Safer: simple segment, validation in handler
var idRegex = regexp.MustCompile("^[a-zA-Z0-9]+@[a-zA-Z0-9]+$")

func main() {
    r := chi.NewRouter()
    r.Get("/{id}", func(w http.ResponseWriter, r *http.Request) {
        id := chi.URLParam(r, "id")
        if !idRegex.MatchString(id) {
            http.Error(w, "invalid id", 400)
            return
        }
        key := map[string]*dynamodb.AttributeValue{
            "PK": {S: aws.String(id)},
        }
        // Proceed with DynamoDB GetItem
    })
}

2) Use strict length and character constraints in regex, or avoid regex altogether by using type switches and manual checks:

func isValidID(s string) bool {
    if len(s) < 3 || len(s) > 64 {
        return false
    }
    for _, ch := range s {
        if !(('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') || ('0' <= ch && ch <= '9') || ch == '@') {
            return false
        }
    }
    return true
}

3) When constructing DynamoDB expressions from user input, ensure parameterization rather than string interpolation to avoid injection risks, and keep the runtime path processing lightweight:

params := &dynamodb.GetItemInput{
    Key: map[string]*dynamodb.AttributeValue{
        "PK": {S: aws.String(userSuppliedID)},
    },
    // Use ExpressionAttributeNames if attribute names are dynamic
}

By simplifying route patterns and validating input before it reaches DynamoDB, you reduce the attack surface for both regex exhaustion and malformed payloads. middleBrick can surface the original route definitions and flag complex patterns, helping teams prioritize which endpoints need refactoring.

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

Can middleBrick prevent regex DoS attacks in Chi routes?
middleBrick detects and reports risky patterns, such as complex regex on user-controlled input before DynamoDB operations, but it does not fix or block attacks. It provides findings and remediation guidance.
How does middleBrick handle DynamoDB-related findings in Chi scans?
When an OpenAPI spec or routing configuration suggests interaction with DynamoDB, middleBrick cross-references route definitions and highlights findings that involve both Chi routing and DynamoDB usage, including relevant guidance.