HIGH regex dosfiber

Regex Dos in Fiber

How Regex DoS Manifests in Fiber

Regular Expression Denial of Service (ReDoS) is a critical vulnerability where malicious input causes catastrophic backtracking in regex patterns, potentially freezing or crashing your Fiber application. In Go's standard regexp package, this manifests when regex engines spend exponential time matching certain pathological inputs.

Fiber applications are particularly vulnerable because they process every incoming request through middleware chains. A single malicious request with crafted input can tie up a goroutine for seconds or minutes, effectively creating a denial of service condition. During this time, the goroutine remains blocked, consuming memory and preventing the Fiber server from handling legitimate requests.

The most common Fiber-specific scenario involves route parameter validation. Consider this middleware pattern:

app.Use(func(c *fiber.Ctx) error {
    if !regexp.MustCompile(`^[a-zA-Z0-9_-]+$`).MatchString(c.Params("id")) {
        return c.Status(fiber.StatusBadRequest).SendString("Invalid ID")
    }
    return c.Next()
})

While this seems reasonable for validating alphanumeric IDs, the regex pattern ^[a-zA-Z0-9_-]+$ can be exploited with inputs containing nested quantifiers or alternating character classes. The Go regex engine uses backtracking, making it susceptible to exponential time complexity on certain inputs.

Another Fiber-specific manifestation occurs in request body validation. Many Fiber applications use JSON schema validation or custom regex patterns to validate request payloads. When processing multipart form data or large JSON bodies, a single malicious field with a ReDoS payload can consume significant CPU resources before validation fails.

Path traversal prevention code in Fiber applications often uses regex patterns like ^[^/]*$ to validate file paths. Attackers can craft inputs that cause the regex engine to explore millions of possible matches, effectively creating a CPU-based DoS attack.

The impact is amplified in Fiber's default configuration, which uses a default pool of goroutines. A few ReDoS attacks can exhaust available goroutines, causing legitimate requests to queue indefinitely. This is particularly problematic in serverless environments where each goroutine consumes memory that could be used for other functions.

Fiber-Specific Detection

Detecting ReDoS vulnerabilities in Fiber applications requires both static analysis and runtime monitoring. The most effective approach combines automated scanning with manual code review of regex patterns.

middleBrick's API security scanner includes specialized ReDoS detection for Go/Fiber applications. When you scan your Fiber API endpoints, middleBrick analyzes the request validation patterns and identifies regex expressions that could be vulnerable to catastrophic backtracking. The scanner tests your endpoints with crafted inputs designed to trigger exponential regex behavior, measuring response times to detect potential ReDoS conditions.

For manual detection, examine all regex patterns in your Fiber middleware and route handlers. Look for patterns with nested quantifiers like (a+)+, alternations with overlapping character classes like (a|a)*, or patterns that validate user input without length limits. Pay special attention to validation middleware that processes URL parameters, query strings, and JSON request bodies.

Runtime monitoring can help identify active ReDoS attacks. Implement request timing middleware in your Fiber application to log requests that take unusually long to process. A sudden spike in requests taking >100ms for simple operations often indicates ReDoS exploitation.

app.Use(func(c *fiber.Ctx) error {
    start := time.Now()
    err := c.Next()
    duration := time.Since(start)
    
    if duration > 100*time.Millisecond {
        log.Printf("Slow request: %s %s took %v", c.Method(), c.Path(), duration)
        // Alert or block suspicious requests
    }
    
    return err
})

middleBrick's continuous monitoring (Pro plan) can automatically scan your Fiber APIs on a schedule, detecting new ReDoS vulnerabilities that might be introduced through code changes. The scanner provides severity ratings and specific remediation guidance for each finding.

Fiber-Specific Remediation

Remediating ReDoS vulnerabilities in Fiber applications requires a multi-layered approach. The most effective strategy combines safer regex patterns, input length limits, and alternative validation methods.

First, always limit input length before applying regex validation. In Fiber middleware, validate string length before pattern matching:

app.Use(func(c *fiber.Ctx) error {
    id := c.Params("id")
    if len(id) > 50 {
        return c.Status(fiber.StatusBadRequest).SendString("ID too long")
    }
    
    if !regexp.MustCompile(`^[a-zA-Z0-9_-]+$`).MatchString(id) {
        return c.Status(fiber.StatusBadRequest).SendString("Invalid ID")
    }
    return c.Next()
})

This simple length check prevents attackers from submitting excessively long inputs that could cause exponential backtracking.

Replace vulnerable regex patterns with safer alternatives. Instead of complex patterns, use simple character class checks or Go's built-in string functions:

// Vulnerable pattern
if !regexp.MustCompile(`^[a-zA-Z0-9_-]+$`).MatchString(id) {
    return c.Status(fiber.StatusBadRequest).SendString("Invalid ID")
}

// Safer alternative
if !isValidID(id) {
    return c.Status(fiber.StatusBadRequest).SendString("Invalid ID")
}

func isValidID(id string) bool {
    if len(id) == 0 || len(id) > 50 {
        return false
    }
    for _, char := range id {
        if !unicode.IsLetter(char) && !unicode.IsDigit(char) && char != '_' && char != '-' {
            return false
        }
    }
    return true
}

For path validation, use Go's path.Clean instead of regex:

import "path"

func sanitizePath(p string) string {
    clean := path.Clean("/" + p)
    if clean == "/" || strings.Contains(clean, "..") {
        return ""
    }
    return clean[1:]
}

middleBrick's GitHub Action can automatically scan your Fiber API endpoints during CI/CD pipelines, failing builds if ReDoS vulnerabilities are detected. This ensures that new code changes don't introduce regex vulnerabilities into production.

For production Fiber applications, consider implementing a circuit breaker pattern that temporarily blocks requests showing ReDoS characteristics. Combine this with rate limiting middleware to prevent abuse:

app.Use(rate.New(rate.Every(10*time.Second), 100))

// Circuit breaker for suspicious requests
var reDoSDetector = circuit.NewBreaker("redos", circuit.Option{
    ShouldTrip: func(counts circuit.Counts) bool {
        return counts.Timeout+counts.Rejected > 10
    },
    Timeout: 30 * time.Second,
})

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 Fiber API for ReDoS vulnerabilities?
Use middleBrick's self-service scanner to test your Fiber API endpoints. The scanner automatically tests for ReDoS by sending crafted inputs designed to trigger catastrophic backtracking. You can also manually test by sending inputs with nested quantifiers and measuring response times. Look for requests that take significantly longer than normal to process.
Are there specific regex patterns that are safe to use in Fiber applications?
Yes, patterns without nested quantifiers, alternations with overlapping character classes, or unbounded repetition are generally safe. Simple character class patterns like ^[a-zA-Z0-9_-]+$ are safe when combined with input length limits. For complex validation, consider using Go's built-in string functions or parsing libraries instead of regex. Always validate input length before applying regex patterns.