Missing Tls in Gorilla Mux with Basic Auth
Missing Tls in Gorilla Mux with Basic Auth — how this specific combination creates or exposes the vulnerability
Serving Basic Authentication over unencrypted HTTP in a Gorilla Mux router exposes credentials in transit. Basic Auth encodes credentials using Base64, which is trivial to decode; without Transport Layer Security (TLS), an on-path adversary can intercept the Authorization header and reuse it to impersonate the client. This combination violates confidentiality and directly maps to authentication weaknesses in the OWASP API Top 10 and relevant compliance frameworks such as PCI-DSS and SOC2.
In a Gorilla Mux setup, routes are registered with router.HandleFunc("/admin", handler). If the server listens on HTTP (port 80) and the handler checks the Authorization header, credentials are sent in cleartext. Tools that perform unauthenticated black-box scanning can detect this by checking for TLS on common API ports and inspecting whether authentication mechanisms rely on secrecy. Without TLS, the security risk score will reflect critical findings in Authentication and Data Exposure categories, with remediation guidance to enforce encryption in transit.
Attack patterns enabled by this misconfiguration include credential sniffing on shared networks, session hijacking, and replay. Even if the handler validates the username and password, the lack of TLS means the secret is exposed before any validation occurs. Compounded risks appear when APIs also expose verbose error messages or when logging captures the Authorization header inadvertently. Because middleBrick scans the unauthenticated attack surface, it can surface Missing Tls findings alongside insecure authentication mechanisms, highlighting the need to apply certificates and redirect HTTP to HTTPS.
Basic Auth-Specific Remediation in Gorilla Mux — concrete code fixes
Remediation requires enabling TLS termination in front of Gorilla Mux and ensuring the Authorization header is only accepted over HTTPS. Below are two approaches: (1) using Go’s http.Server with TLS certificates, and (2) enforcing HTTPS within the handler by rejecting cleartext requests.
Example 1: TLS-enabled server with Gorilla Mux
// tls-main.go
package main
import (
"log"
"net/http"
"github.com/gorilla/mux"
)
func secureHandler(w http.ResponseWriter, r *http.Request) {
// Basic Auth validation
username, password, ok := r.BasicAuth()
if !ok || !validateCredentials(username, password) {
w.Header().Set("WWW-Authenticate", `Basic realm="restricted", charset="UTF-8"`)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
w.Write([]byte("Authenticated over TLS"))
}
func validateCredentials(user, pass string) bool {
// Replace with secure credential checks
return user == "admin" && pass == "S3cur3P@ss!"
}
func main() {
router := mux.NewRouter()
router.HandleFunc("/admin", secureHandler).Methods("GET")
srv := &http.Server{
Addr: ":8443",
Handler: router,
TLSConfig: nil, // Use default TLS config; provide certificates via flags/env
}
log.Println("Server listening on https://localhost:8443")
if err := srv.ListenAndServeTLS("server.crt", "server.key"); err != nil {
log.Fatalf("TLS handshake failed: %v", err)
}
}
Example 2: Enforce HTTPS inside handler (defense-in-depth)
// enforce-https.go
package main
import (
"log"
"net/http"
"github.com/gorilla/mux"
)
func enforceHTTPS(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.TLS == nil {
http.Error(w, "HTTPS required", http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}
func secureHandler(w http.ResponseWriter, r *http.Request) {
username, password, ok := r.BasicAuth()
if !ok || !validateCredentials(username, password) {
w.Header().Set("WWW-Authenticate", `Basic realm="restricted"`)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
w.Write([]byte("Authenticated"))
}
func validateCredentials(user, pass string) bool {
return user == "admin" && pass == "correct-horse-battery-staple"
}
func main() {
router := mux.NewRouter()
router.Use(enforceHTTPS)
router.HandleFunc("/admin", secureHandler).Methods("GET")
log.Println("Starting HTTP server (redirect recommended)")
go func() {
if err := http.ListenAndServe(":80", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "https://"+r.Host+r.RequestURI, http.StatusPermanentRedirect)
})); err != nil {
log.Fatalf("HTTP server failed: %v", err)
}
}()
// Use TLS on 8443 in production; here we bind TLS directly
if err := http.ListenAndServeTLS(":8443", "server.crt", "server.key", router); err != nil {
log.Fatalf("TLS server failed: %v", err)
}
}
Operational and scanning considerations
When using middleBrick’s CLI (middlebrick scan <url>) or GitHub Action, ensure the target URL is the HTTPS endpoint. The scanner will flag Missing Tls when it detects authentication over non-TLS endpoints and will include this in the Authentication and Data Exposure sections of the report. Pro plan continuous monitoring can alert you if an endpoint begins serving authentication without encryption. Findings come with remediation guidance but do not apply fixes; you must configure TLS certificates and update routing or CI/CD gates accordingly.
Related CWEs: encryption
| CWE ID | Name | Severity |
|---|---|---|
| CWE-319 | Cleartext Transmission of Sensitive Information | HIGH |
| CWE-295 | Improper Certificate Validation | HIGH |
| CWE-326 | Inadequate Encryption Strength | HIGH |
| CWE-327 | Use of a Broken or Risky Cryptographic Algorithm | HIGH |
| CWE-328 | Use of Weak Hash | HIGH |
| CWE-330 | Use of Insufficiently Random Values | HIGH |
| CWE-338 | Use of Cryptographically Weak PRNG | MEDIUM |
| CWE-693 | Protection Mechanism Failure | MEDIUM |
| CWE-757 | Selection of Less-Secure Algorithm During Negotiation | HIGH |
| CWE-261 | Weak Encoding for Password | HIGH |