HIGH regex doschi

Regex Dos in Chi

How Regex DoS Manifests in Chi

Regex Denial of Service (DoS) in Chi applications typically occurs when user-controlled input is passed directly to regular expression engines without proper validation or timeout controls. This vulnerability allows attackers to craft input that causes exponential backtracking, consuming CPU resources and potentially crashing services.

In Chi middleware and route handlers, regex DoS often appears in these patterns:

// Vulnerable: No timeout or validation
func validateEmail(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        email := r.URL.Query().Get("email")
        
        // Malicious regex: ([a-z]+)*$
        matched, _ := regexp.MatchString(`^([a-z]+)*$`, email)
        if !matched {
            http.Error(w, "Invalid email", 400)
            return
        }
        next.ServeHTTP(w, r)
    })
}

The above pattern is particularly dangerous in Chi because middleware executes for every request. An attacker can send input like a!a!a!... that causes the regex engine to explore exponential backtracking paths.

Another common manifestation appears in route parameter validation:

// Vulnerable: Complex regex in route parameter
chi.Route("/users/{id:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}}", func(r chi.Router) {
    r.Get("/profile", getUserProfile) // UUID regex DoS vulnerability
})

When processing requests with crafted UUIDs containing nested character classes or alternations, the regex engine can consume significant CPU time before rejecting invalid input.

Chi-Specific Detection

Detecting regex DoS in Chi applications requires both static analysis and runtime monitoring. middleBrick's API security scanner specifically identifies regex patterns that are susceptible to exponential backtracking when analyzing Chi middleware and route handlers.

middleBrick detects these Chi-specific regex DoS patterns:

  • Unbounded quantifiers with nested expressions: (a+)*, (a*)*
  • Excessive alternation without anchors: (a|b|c|d|e|f|g|h|i|...)
  • Recursive patterns that can trigger catastrophic backtracking
  • Regex patterns in route parameters that process user input
  • Middleware chains that apply regex validation to every request

The scanner analyzes the actual running application, not just source code, to identify which regex patterns are exposed to unauthenticated users. For Chi applications, this includes:

# Scan a Chi API with middleBrick
middlebrick scan https://api.example.com/v1

# Results show regex DoS findings with:
# - Vulnerable endpoint URLs
# - Specific regex patterns detected
# - Severity assessment
# - Remediation guidance

middleBrick's LLM security module also checks for regex DoS in AI-related endpoints, as regex patterns are commonly used in prompt validation and content filtering for LLM APIs.

Chi-Specific Remediation

Remediating regex DoS in Chi applications involves multiple strategies. The most effective approach combines input validation, timeout controls, and safer regex patterns.

Input Validation First:

// Safer: Validate length before regex
func validateEmail(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        email := r.URL.Query().Get("email")
        
        // Reject based on length first
        if len(email) > 255 {
            http.Error(w, "Invalid email", 400)
            return
        }
        
        // Use simpler, safer regex
        matched, _ := regexp.MatchString(`^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`, email)
        if !matched {
            http.Error(w, "Invalid email", 400)
            return
        }
        next.ServeHTTP(w, r)
    })
}

Chi-Specific Timeout Middleware:

// Add timeout to prevent regex DoS from blocking requests
func timeoutMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        ctx, cancel := context.WithTimeout(r.Context(), 100*time.Millisecond)
        defer cancel()
        
        // Wrap response writer to handle timeout
        rw := &responseWriter{ResponseWriter: w, ctx: ctx}
        next.ServeHTTP(rw, r.WithContext(ctx))
    })
}

For route parameters, use Chi's built-in validation with simpler patterns:

// Safer: Use simpler validation in routes
chi.Route("/users/{id:[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}}", func(r chi.Router) {
    r.Use(timeoutMiddleware) // Add timeout protection
    r.Get("/profile", getUserProfile)
})

Precompiled regex patterns with timeout context:

var emailRegex = regexp.MustCompile(`^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`)

func validateEmail(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        email := r.URL.Query().Get("email")
        
        if len(email) > 255 {
            http.Error(w, "Invalid email", 400)
            return
        }
        
        if !emailRegex.MatchString(email) {
            http.Error(w, "Invalid email", 400)
            return
        }
        next.ServeHTTP(w, r)
    })
}

For comprehensive protection, integrate middleBrick's continuous monitoring to scan your Chi APIs regularly and receive alerts when new regex DoS vulnerabilities are introduced.

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 does middleBrick detect regex DoS vulnerabilities in Chi applications?
middleBrick performs black-box scanning of your Chi API endpoints, analyzing regex patterns in middleware and route handlers that process user input. It identifies vulnerable patterns like unbounded quantifiers, excessive alternations, and recursive expressions. The scanner tests these patterns with crafted input to confirm if they trigger exponential backtracking, then provides specific findings with severity levels and remediation guidance.
Can regex DoS affect my Chi API's availability?
Yes, regex DoS can severely impact availability. When attackers send crafted input that triggers catastrophic backtracking, the regex engine consumes 100% CPU, causing legitimate requests to time out or fail. In Chi applications, this is particularly dangerous because middleware executes for every request, potentially affecting your entire API surface. middleBrick's continuous monitoring can alert you to these vulnerabilities before attackers exploit them.