Fix Command Injection in Gin
Command injection in Go's Gin framework occurs when untrusted user input is concatenated into system commands. This typically happens when developers use `os/exec` in conjunction with a shell (like `/bin/sh -c` or `cmd.exe /c`), allowing attackers to break out of the intended command context using shell metacharacters like `;`, `&`, `|`, or backticks.
The Vulnerable Pattern
func SetupRouter() *gin.Engine {
r := gin.Default()
r.GET("/lookup", func(c *gin.Context) {
hostname := c.Query("host")
// VULNERABLE: User input is directly concatenated into a shell command string
cmd := exec.Command("sh", "-c", "nslookup "+hostname)
out, _ := cmd.CombinedOutput()
c.String(200, string(out))
})
return r
}
The Secure Implementation
The vulnerability exists because `sh -c` interprets the entire following string as a shell command, including control characters. An attacker could pass `google.com; cat /etc/passwd` to execute arbitrary code. The fix is two-fold: First, remove the shell wrapper (`sh -c`) and call the executable directly with `exec.Command('binary', 'arg1', 'arg2')`. In this mode, Go passes arguments directly to the `execve` syscall, meaning characters like `;` are treated as literal parts of the argument rather than command separators. Second, implement strict allow-list validation (Regex) to ensure the input conforms to expected formats before processing.
func SetupRouter() *gin.Engine { r := gin.Default() r.GET("/lookup", func(c *gin.Context) { hostname := c.Query("host")// 1. Input Validation: Only allow alphanumeric and dots re := regexp.MustCompile(`^[a-zA-Z0-9.-]+$`) if !re.MatchString(hostname) { c.String(400, "Invalid input") return } // 2. SECURE: Execute binary directly without a shell wrapper // Arguments are passed as separate strings, preventing shell interpolation cmd := exec.Command("nslookup", hostname) out, err := cmd.CombinedOutput() if err != nil { c.String(500, "Execution failed") return } c.String(200, string(out)) }) return r
}
Your Gin API
might be exposed to Command Injection
74% of Gin 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.