HIGH server side template injectiongorilla muxbasic auth

Server Side Template Injection in Gorilla Mux with Basic Auth

Server Side Template Injection in Gorilla Mux with Basic Auth — how this specific combination creates or exposes the vulnerability

Server Side Template Injection (SSTI) in a Gorilla Mux router context occurs when user-controlled input is passed into a server-side template function without adequate validation or escaping. Gorilla Mux is a widely used HTTP router and matcher for Go that does not render templates itself, but it often routes requests to handlers that do. When those handlers combine route variables, query parameters, or request bodies with a template engine (for example html/template, text/template, or a third-party engine), failing to sanitize or isolate user input can lead to template injection.

Basic Auth in Gorilla Mux typically adds credentials to the request context via a handler that validates a username and password before allowing access to a route. This authentication layer may give developers a false sense of security, leading them to trust data extracted from the context (such as username) in templates. If a handler uses values from the request context alongside untrusted user input in a template, and the template evaluates that combined data, an attacker who bypasses or knows the Basic Auth credentials can inject template directives. These injected directives can cause the server to execute unintended logic, read files, or make network calls depending on the template engine’s capabilities and the Go environment’s permissions.

A realistic scenario: a handler uses Basic Auth to identify a user, places the username into the template context, and then renders a dashboard that includes a user-controlled parameter such as a search term. If the search term is not properly escaped and the template engine supports actions or variable substitutions, an attacker can craft a payload that modifies control flow or accesses backend resources. Because the route is protected by Basic Auth, the vulnerability may only be reachable by authenticated users, but the presence of Basic Auth does not prevent the template engine from interpreting malicious input. The combination therefore creates a situation where authentication narrows who can trigger the flaw, but does not mitigate the injection itself.

Consider an engine such as text/template where user input is executed as code. An attacker might supply a payload that leverages built-in functions or access to underlying data structures to execute commands. In Go’s html/template, automatic escaping usually prevents execution, but if the developer explicitly marks content as safe or uses custom delimiters, the risk can materialize. The key takeaway is that route protection and authentication mechanisms like Basic Auth do not substitute for output encoding, strict context-aware escaping, and validation of any data that flows into server-side templates.

Basic Auth-Specific Remediation in Gorilla Mux — concrete code fixes

To remediate SSTI in Gorilla Mux when using Basic Auth, ensure that no user-controlled data reaches the template engine in a way that can change template syntax or execution flow. This involves strict separation of trusted template structure from untrusted data, using the correct escaping mechanisms, and avoiding the inclusion of authentication-derived fields in template input.

First, always use html/template (or text/template) with its built-in escaping for HTML, URLs, and JavaScript contexts. Never mark user input as safe or use template.HTML on values that originate from users, including values placed into the request context by authentication handlers.

Second, keep authentication data separate from template data. Do not place usernames or other credentials into the template execution context. If you must pass user metadata to the template, ensure it is treated as plain text and never interpreted as template code.

Third, validate and sanitize all inputs that could reach the template, including query parameters, form fields, and JSON payloads. Use allowlists for expected values and avoid reflection-based or dynamic function calls inside templates.

Example of a vulnerable handler that combines Basic Auth context with a user-controlled query parameter and uses text/template in a risky way:

// Vulnerable example — do not use
func vulnerableHandler(tmpl *template.Template) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        user, pass, ok := r.BasicAuth()
        if !ok || !validUser(user, pass) {
            w.Header().Set("WWW-Authenticate", `Basic realm="restricted"`)
            http.Error(w, "Unauthorized", http.StatusUnauthorized)
            return
        }
        // Risk: user-controlled value injected into template context
        data := map[string]interface{}{
            "Username": user,
            "Query":    r.URL.Query().Get("q"),
        }
        tmpl.Execute(w, data)
    }
}

Example of a secure handler that uses Gorilla Mux, Basic Auth, and safe template rendering:

// Secure example
func secureHandler(tmpl *template.Template) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        user, pass, ok := r.BasicAuth()
        if !ok || !validUser(user, pass) {
            w.Header().Set("WWW-Authenticate", `Basic realm="restricted"`)
            http.Error(w, "Unauthorized", http.StatusUnauthorized)
            return
        }
        // Safe: only trusted, non-executable data passed to template
        safeData := struct {
            Username string
        }{
            Username: user, // treated as plain text
        }
        // User-controlled input is not passed to the template
        // If you need to render dynamic content, process and sanitize it separately
        w.Header().Set("Content-Type", "text/html; charset=utf-8")
        tmpl.Execute(w, safeData)
    }
}

func validUser(username, password string) bool {
    // Replace with secure credential validation
    return username == "admin" && password == "correct-horse-battery-staple"
}

In summary, protect against SSTI in Gorilla Mux by isolating authentication context from templates, using auto-escaping template engines, and rigorously validating all user-influenced data. MiddleBrick can detect such misconfigurations during scans and provide findings mapped to relevant frameworks when you integrate scans via the CLI, Web Dashboard, GitHub Action, or MCP Server.

Frequently Asked Questions

Does Basic Auth prevent Server Side Template Injection?
No. Basic Auth can limit who reaches an endpoint, but it does not prevent a template engine from interpreting malicious input. If user-controlled data is included in templates, authenticated attackers can still inject template directives. Treat authentication as a boundary, not a sanitization mechanism.
How can I safely pass user identity to a template in Gorilla Mux?
Avoid passing raw usernames or authentication context into templates. If you must display user identity, pass it as a plain string and ensure the template engine escapes output for the intended context (HTML, JS, URL). Do not allow user input to influence template structure or function calls.