HIGH path traversalgorilla mux

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.ServeContent with mux.Vars values
  • os.Open, ioutil.ReadFile using 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%2f URL-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:0 from /etc/passwd, Windows C:\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 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

Does middleBrick's path traversal check work with Gorilla Mux's regex route variables?
Yes. middleBrick parses the OpenAPI spec (or infers from responses) to identify route variables, including those with regex constraints like {filepath:.*}. It then sends traversal payloads in those variable positions, regardless of the regex, to test if the backend improperly handles directory sequences.
Can Gorilla Mux's built-in features prevent path traversal?
Gorilla Mux itself does not sanitize route variables—it only extracts them. Prevention requires application-level checks: canonicalize paths with path.Clean, validate with filepath.Join and prefix checks, or avoid filesystem operations entirely. Use regex constraints to limit allowed characters, but never rely solely on regex for security.