Regex Dos in Chi with Basic Auth
Regex Dos in Chi with Basic Auth — how this specific combination creates or exposes the vulnerability
Chi is a lightweight HTTP router for Go. When you use Basic Authentication in Chi, you typically rely on middleware that inspects the Authorization header and validates credentials. If the validation logic uses regular expressions to parse or compare credentials, poorly constructed patterns can trigger ReDoS (Regular Expression Denial of Service) vulnerabilities.
Consider a Basic Auth scenario where a server extracts the username and password from the header and validates them using a regex. An attacker can supply a specially crafted credential string that causes catastrophic backtracking. For example, a pattern like ^(user|admin):(.+)$ applied to a long, malformed input can force exponential time complexity if the regex engine engages in excessive backtracking due to nested quantifiers or ambiguous groupings.
Chi itself does not impose a regex engine, so the risk comes from how developers implement matching logic in their handlers or middleware. When integrating Basic Auth with custom regex checks, each request undergoes the 5–15 second scan window that middleBrick uses to profile unauthenticated attack surfaces. Although middleBrick does not test regex patterns directly, it can surface authentication bypass or input validation findings when misconfigurations enable authentication bypass or excessive processing.
Real-world impact includes CPU exhaustion, which can degrade service for all users. This is especially dangerous in environments where Basic Auth credentials are checked on every request. Patterns that look harmless can become dangerous under specific input lengths and character distributions, often involving repeated optional groups or ambiguous greedy repetitions.
To contextualize within middleBrick’s checks, insecure authentication logic can contribute to a poor Authentication score, and findings may map to frameworks such as OWASP API Top 10 and SOC2. middleBrick’s scans test unauthenticated endpoints, so misconfigured regex validation in Basic Auth flows can be observed as part of the authentication assessment without requiring credentials.
Basic Auth-Specific Remediation in Chi — concrete code fixes
Remediation focuses on avoiding regular expressions for credential validation and using constant-time comparison methods. When Basic Auth is used in Chi, prefer standard library functions for parsing and comparing credentials instead of custom regex patterns.
Example 1: Safe Basic Auth parsing without regex
Use base64.StdEncoding.DecodeString to decode the credentials and validate them with simple string comparison. This avoids regex entirely and prevents ReDoS.
package main
import (
"encoding/base64"
"net/http"
"strings"
)
func basicAuthMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
auth := r.Header.Get("Authorization")
if auth == "" {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
const prefix = "Basic "
if !strings.HasPrefix(auth, prefix) {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
payload, err := base64.StdEncoding.DecodeString(auth[len(prefix):])
if err != nil {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
// Expected format: username:password
parts := strings.SplitN(string(payload), ":", 2)
if len(parts) != 2 {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
username, password := parts[0], parts[1]
if !validateCredentials(username, password) {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
func validateCredentials(username, password string) bool {
// Use constant-time comparison in production for real credentials
return username == "admin" && password == "securepassword123"
}
Example 2: Using Chi with middleware and avoiding regex
Define a Chi route and attach the safe middleware. This demonstrates how to integrate Basic Auth cleanly without regex-based checks.
package main
import (
"net/http"
"github.com/go-chi/chi/v5"
)
func main() {
r := chi.NewRouter()
r.Use(basicAuthMiddleware)
r.Get("/secure", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("OK"))
})
http.ListenAndServe(":8080", r)
}
Example 3: If regex is required, use safe patterns
If your use case genuinely needs regex, ensure patterns are simple, avoid nested quantifiers, and set timeouts or size limits on input. For example, validate usernames and passwords with bounded lengths and avoid ambiguous groups.
// Prefer this kind of bounded check over open-ended patterns
// Do not use complex regex for credential validation; this is illustrative only.
import "regexp"
func safePatternCheck(input string) bool {
// Bounded pattern: alphanumeric, 1-32 chars, no nested quantifiers
re := regexp.MustCompile(`^[a-zA-Z0-9]{1,32}$`)
return re.MatchString(input)
}
By removing regex from credential validation and relying on standard decoding and comparison, you eliminate ReDoS risks while maintaining compatibility with Chi’s idiomatic middleware patterns. This approach aligns with middleBrick’s findings for Authentication and Input Validation checks, and it supports better outcomes in scans that assess authentication robustness.
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 |