Path Traversal in Gorilla Mux
How Path Traversal Manifests in Gorilla Mux
Path traversal (CWE-22) in Gorilla Mux occurs when route variables capturing user-supplied path segments are used directly in filesystem operations without validation. Gorilla Mux's flexible routing syntax—such as {filepath:.*} or {path:.*}—can inadvertently capture ../ sequences, enabling directory escape.
A typical vulnerable pattern:
r := mux.NewRouter()
// Vulnerable route: captures entire path including '../'
r.HandleFunc("/download/{filepath:.*}", func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
filePath := vars["filepath"] // e.g., "../../../etc/passwd"
http.ServeFile(w, r, filePath) // Direct filesystem access
}).Methods("GET")Here, the regex :.* matches any characters, allowing slashes. An attacker requests /download/../../../etc/passwd, and http.ServeFile reads files outside the intended directory. Even without regex, a route like /{filename} is vulnerable if filename contains ../.
Another manifestation: using mux.Vars values to construct paths for os.Open, ioutil.ReadFile, or template rendering without canonicalization. Gorilla Mux does not sanitize variables—it merely extracts them. The risk is compounded when the application runs with high filesystem privileges.
Gorilla Mux-Specific Detection
Code Review: Search for routes with variables used in filesystem operations. Look for:
http.ServeFile,http.ServeContentwithmux.Varsvaluesos.Open,ioutil.ReadFileusing route variables- Template execution with user-controlled paths (e.g.,
template.ParseFiles(vars["tpl"]))
Dynamic Testing: Manipulate route variables with payloads:
../sequences (e.g.,%2e%2e%2fURL-encoded)- Absolute paths (e.g.,
/etc/passwd) - Double encoding (e.g.,
%252e%252e%252f)
If the API returns file contents or error messages revealing filesystem structure, it's vulnerable.
middleBrick Scanning: middleBrick's BOLA/IDOR check automatically tests for path traversal. When scanning a Gorilla Mux endpoint, it:
- Identifies route variables from the OpenAPI spec (or infers from responses).
- Sends probes with
../and other traversal sequences in variable positions. - Analyzes responses for signs of unauthorized file access (e.g.,
root:x:0:0from/etc/passwd, WindowsC:\Windows\System32). - Assigns a severity score and maps the finding to OWASP API Top 5:2023 (BOLA).
For example, scanning https://api.example.com/download/{filepath} with middleBrick would yield a report highlighting the path traversal risk with proof and remediation steps.
Gorilla Mux-Specific Remediation
1. Canonicalize and Validate Paths
Use Go's path package to clean the path and ensure it stays within a base directory:
r.HandleFunc("/download/{filepath:.*}", func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
userPath := vars["filepath"]
// Clean the path (removes ".", "..", duplicate slashes)
cleanPath := path.Clean(userPath)
// Ensure the path is relative and does not escape baseDir
baseDir := "/safe/downloads"
absBase, _ := filepath.Abs(baseDir)
absPath, _ := filepath.Abs(filepath.Join(baseDir, cleanPath))
// Check that absPath is within absBase
if !strings.HasPrefix(absPath, absBase+string(os.PathSeparator)) {
http.Error(w, "Invalid path", http.StatusBadRequest)
return
}
http.ServeFile(w, r, absPath)
}).Methods("GET")2. Avoid Filesystem Operations Altogether
If possible, serve files via a controlled mapping (e.g., database IDs) instead of paths:
// Route: /download/{id}
r.HandleFunc("/download/{id}", func(w http.ResponseWriter, r *http.Request) {
id := mux.Vars(r)["id"]
file, err := lookupFileByID(id) // Validate ID, fetch from safe location
if err != nil { /* ... */ }
http.ServeFile(w, r, file.Path)
})3. Restrict Route Variables with Regex
Use Gorilla Mux's regex constraints to exclude .. and slashes if the variable should be a simple filename:
r.HandleFunc("/download/{filename:[a-zA-Z0-9._-]}", ...) // No slashes or ".."4. Use Chroot or Containerization
Run the application in a chroot jail or container with minimal filesystem access. This is a defense-in-depth measure.
5. Log and Monitor
Log attempts with ../ in route variables. middleBrick's continuous monitoring (Pro plan) can alert on new path traversal findings in staging or production APIs.
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 |