Fix NoSQL Injection in Gorilla
NoSQL Injection in Go/Gorilla applications occurs when untrusted input is merged directly into database filters without strict type enforcement. Attackers leverage MongoDB operators like $gt, $ne, or $where to bypass authentication or exfiltrate the entire database. If you're decoding JSON into generic maps before querying, your application is a target.
The Vulnerable Pattern
func LoginHandler(w http.ResponseWriter, r *http.Request) { // VULNERABLE: Decoding into a generic map allows operator injection var input map[string]interface{} json.NewDecoder(r.Body).Decode(&input)filter := bson.M{ "username": input["username"], "password": input["password"], } var user User err := collection.FindOne(context.TODO(), filter).Decode(&user) if err == nil { fmt.Fprint(w, "Authenticated") }
}
The Secure Implementation
The vulnerability exists because MongoDB filters accept nested objects as operators. When you use map[string]interface{}, an attacker can supply a JSON object instead of a string, which the BSON driver interprets as a command. By switching to a strictly typed struct, the Go JSON decoder forces the input into a primitive string. If the attacker attempts to inject an operator object, the decoding process will either error out or discard the malicious structure, ensuring the query logic remains intact.
func LoginHandler(w http.ResponseWriter, r *http.Request) { // SECURE: Use a strictly typed struct to enforce scalar values type LoginRequest struct { Username string `json:"username"` Password string `json:"password"` }var req LoginRequest if err := json.NewDecoder(r.Body).Decode(&req); err != nil { http.Error(w, "Bad Request", 400) return } // Even if the attacker sends {"username": {"$ne": null}}, // the decoder will fail or ignore the object, neutralizing the payload. filter := bson.M{ "username": req.Username, "password": req.Password, } var user User err := collection.FindOne(context.TODO(), filter).Decode(&user) if err == nil { fmt.Fprint(w, "Authenticated") }
}
Your Gorilla API
might be exposed to NoSQL Injection
74% of Gorilla apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.