Regex Dos in Fiber with Cockroachdb
Regex Dos in Fiber with Cockroachdb — how this specific combination creates or exposes the vulnerability
A Regular Expression Denial of Service (Regex DoS) occurs when an attacker provides input that causes a regular expression to exhibit catastrophic backtracking, consuming excessive CPU time. In a Fiber-based API that uses CockroachDB as the backend, this risk is introduced when user-controlled data such as query parameters, path segments, or request bodies are incorporated into regex patterns before being used to validate or parse inputs destined for CockroachDB queries.
For example, consider a route that extracts an organization identifier from the URL and uses a non-anchored, complex regex to validate the format before building a CockroachDB query. If the regex is poorly constructed (e.g., using nested quantifiers without atomic groups or possessive quantifiers), an attacker can send a specially crafted string that causes exponential backtracking. Because Fiber handlers often run per request, this can lead to high CPU utilization and degraded service for all requests, effectively a denial of service.
When the regex validates input that later forms part of SQL or CockroachDB-specific query fragments (such as tenant identifiers or schema names), the impact is compounded: not only does the server face resource exhaustion, but the malformed input may also attempt to exploit parsing ambiguities in how the application constructs CockroachDB statements. Even if the application ultimately uses parameterized statements, the damage from the regex itself occurs before the database driver is invoked, making this a pre-processing vulnerability.
The combination of Fiber’s lightweight, high-performance routing and Cockroachdb’s distributed SQL nature does not introduce the regex flaw, but it can amplify the operational impact. In a distributed database environment where latency and throughput are critical, a single pathological request can degrade cluster-side observability and increase load on other nodes due to connection pool saturation and retried requests.
Cockroachdb-Specific Remediation in Fiber — concrete code fixes
To mitigate Regex DoS in a Fiber application interacting with Cockroachdb, validate and sanitize inputs before they reach regex logic, and ensure regex patterns are safe and bounded. Prefer simple, anchored patterns with limited backtracking, and enforce length and character-set constraints upstream.
Example: Unsafe regex usage
// Unsafe: vulnerable to catastrophic backtracking
app.Get('/tenant/:id', func(c *fiber.Ctx) error {
id := c.Params('id')
matched, _ := regexp.MatchString(`(a+)+@(b+)+`, id) // Dangerous pattern
if matched {
// Build Cockroachdb query using id
query := fmt.Sprintf('SELECT * FROM tenants WHERE id = %s', id)
_, err := db.Exec(context.Background(), query)
return err
}
return c.SendStatus(fiber.StatusBadRequest)
})
Example: Safe remediation with bounded validation
// Safe: simple anchored pattern and length limit
var tenantIDRegex = regexp.MustCompile(`^[a-zA-Z0-9_-]{1,64}$`)
app.Get('/tenant/:id', func(c *fiber.Ctx) error {
id := c.Params('id')
if !tenantIDRegex.MatchString(id) {
return c.SendStatus(fiber.StatusBadRequest)
}
// Use parameterized query to avoid injection
query := 'SELECT * FROM tenants WHERE id = $1'
row := db.QueryRow(context.Background(), query, id)
// process row...
return nil
})
Example: Using middleware for centralized validation
func ValidateTenantID() fiber.Handler {
re := regexp.MustCompile(`^[a-zA-Z0-9_-]{1,64}$`)
return func(c *fiber.Ctx) error {
id := c.Params('id')
if !re.MatchString(id) {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
'error': 'invalid tenant identifier',
})
}
return c.Next()
}
}
// Apply middleware to routes
app.Get('/tenant/:id', ValidateTenantID(), func(c *fiber.Ctx) error {
query := 'SELECT * FROM tenants WHERE id = $1'
var name string
err := db.QueryRow(context.Background(), query, c.Locals('id')).Scan(&name)
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{'error': 'db error'})
}
return c.JSON(fiber.Map{'name': name})
})
Operational guidance for Cockroachdb integrations
- Use parameterized queries with the Cockroachdb driver to avoid SQL injection regardless of input validation.
- Apply strict allow-lists for identifiers such as tenant IDs, and keep regex patterns simple and anchored.
- Set request size and URL length limits at the Fiber server configuration to reduce attack surface.
- Monitor regex execution time in production; if patterns become complex, consider replacing regex with deterministic parsing or dedicated validation libraries.
Related CWEs: inputValidation
| CWE ID | Name | Severity |
|---|---|---|
| CWE-20 | Improper Input Validation | HIGH |
| CWE-22 | Path Traversal | HIGH |
| CWE-74 | Injection | CRITICAL |
| CWE-77 | Command Injection | CRITICAL |
| CWE-78 | OS Command Injection | CRITICAL |
| CWE-79 | Cross-site Scripting (XSS) | HIGH |
| CWE-89 | SQL Injection | CRITICAL |
| CWE-90 | LDAP Injection | HIGH |
| CWE-91 | XML Injection | HIGH |
| CWE-94 | Code Injection | CRITICAL |