HIGH path traversalgorilla muxapi keys

Path Traversal in Gorilla Mux with Api Keys

Path Traversal in Gorilla Mux with Api Keys — how this specific combination creates or exposes the vulnerability

Path Traversal occurs when user-controlled input used to resolve file paths is not properly sanitized, allowing sequences like ../ to escape intended directories. In a Go API built with Gorilla Mux, this risk is often coupled with Api Keys when endpoints accept both a path parameter and an authentication credential in a way that influences how the server resolves or serves files.

Consider an endpoint designed to retrieve documents for an authenticated user. With Gorilla Mux, a typical route might look like this:

r := mux.NewRouter()
r.HandleFunc("/docs/{filename}", handler).Methods("GET")

If the handler constructs a filesystem path by directly concatenating a base directory with the {filename} parameter, an attacker can supply a crafted filename such as ../../../etc/passwd to traverse outside the intended directory. The presence of Api Keys adds a layer of authentication, but does not inherently prevent path traversal; it only identifies the requester. In some designs, the Api Key influences which base directory is used (e.g., per-tenant storage), and if the key is leaked or the route is publicly exposed, the combination widens the attack surface by tying traversal to authenticated contexts.

During a black-box scan, middleBrick tests unauthenticated attack surfaces where possible. For endpoints that rely on Api Keys, it checks whether path parameters are validated independently of authentication and whether directory traversal is feasible. If an API accepts Api Keys in headers or query parameters while allowing directory traversal via path parameters, the scan can detect unsafe handling of user input, even when authentication is present. This highlights the importance of validating and sanitizing path input regardless of authentication mechanisms.

Real-world attack patterns mirror this scenario. For example, an attacker may send requests with manipulated filename values and valid Api Keys to access sensitive system files. The issue maps to OWASP API Top 10 categories such as Broken Object Level Authorization (BOLA) when traversal enables access to unintended resources, and it can intersect with Data Exposure if sensitive files are readable. middleBrick’s checks include Input Validation and BOLA/IDOR to surface these risks, emphasizing that authentication does not substitute for secure path handling.

In summary, Path Traversal in Gorilla Mux with Api Keys emerges when route parameters are used to build filesystem paths without strict validation, and authentication tokens like Api Keys do not mitigate unsafe path resolution. The vulnerability centers on how user input is processed, not merely on whether credentials are present.

Api Keys-Specific Remediation in Gorilla Mux — concrete code fixes

Remediation focuses on ensuring that path parameters never directly dictate filesystem locations and that Api Key usage does not inadvertently enable traversal. Below are concrete, safe patterns for Gorilla Mux handlers.

1. Use path.Clean and restrict to a base directory

Always clean the user-supplied filename and join it with a base directory using filepath.Join. Then verify that the cleaned path remains within the base directory.

import (
    "net/http"
    "path/filepath"
    "github.com/gorilla/mux"
)

func handler(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    filename := vars["filename"]
    base := "/safe/docs"
    // Clean and join to prevent traversal
    safePath := filepath.Clean(filepath.Join(base, filename))
    // Ensure the resolved path is still within base
    if rel, err := filepath.Rel(base, safePath); err != nil || rel == ".." || rel[:3] == ".." {
        http.Error(w, "invalid path", http.StatusBadRequest)
        return
    }
    http.ServeFile(w, r, safePath)
}

This ensures that sequences like ../../../etc/passwd are resolved and checked against the base directory before serving.

2. Validate filename format with a strict allowlist

Accept only filenames that match a safe pattern (e.g., alphanumeric, underscores, hyphens, and specific extensions).

import "regexp"

var validFilename = regexp.MustCompile(`^[a-zA-Z0-9_\-]+\.(txt|pdf|json)$`)

func validateFilename(filename string) bool {
    return validFilename.MatchString(filename)
}

func handler(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    filename := vars["filename"]
    if !validateFilename(filename) {
        http.Error(w, "invalid filename", http.StatusBadRequest)
        return
    }
    // Proceed with safe path handling
}

3. Decouple Api Key usage from path resolution

Use Api Keys for authentication and authorization, but keep path resolution independent. Determine access control based on the key, but never embed user input directly into filesystem paths without validation.

func authMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        apiKey := r.Header.Get("X-API-Key")
        if !isValidKey(apiKey) {
            http.Error(w, "unauthorized", http.StatusUnauthorized)
            return
        }
        // Attach identity to context if needed, but do not alter path resolution
        ctx := context.WithValue(r.Context(), "key", apiKey)
        next.ServeHTTP(w, r.WithContext(ctx))
    })
}

func isValidKey(key string) bool {
    // Validate against a store or constant; this is a stub
    return key == "trusted-key-example"
}

In this pattern, the Api Key is used solely for authentication. Path handling remains secure and separate, preventing traversal regardless of the key’s value.

4. Leverage middleware for consistent validation

Apply validation logic in middleware to keep handlers clean and enforce checks across routes.

func pathValidationMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        vars := mux.Vars(r)
        filename := vars["filename"]
        base := "/safe/docs"
        safePath := filepath.Clean(filepath.Join(base, filename))
        if rel, err := filepath.Rel(base, safePath); err != nil || rel == ".." || rel[:3] == ".." {
            http.Error(w, "path traversal attempt", http.StatusBadRequest)
            return
        }
        next.ServeHTTP(w, r)
    })
}

These practices ensure that Gorilla Mux routes with Api Keys remain resilient against Path Traversal by strictly controlling how user input influences filesystem operations.

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 using Api Keys in headers prevent path traversal in Gorilla Mux?
No. Api Keys identify the requester but do not affect how path parameters are resolved. Path Traversal must be addressed through input validation and safe path handling regardless of authentication.
How does middleBrick detect Path Traversal risks in Gorilla Mux APIs with Api Keys?
middleBrick tests unauthenticated attack surfaces where possible and examines whether path parameters are validated independently of authentication. It checks for unsafe concatenation and directory traversal indicators, reporting findings related to Input Validation and BOLA/IDOR.