Fix Command Injection in Chi
Command injection in Go/Chi applications typically manifests when user-controlled data—sourced from chi.URLParam or request bodies—is passed directly into system shells. Attackers exploit this by injecting shell metacharacters (e.g., ;, |, &&) to execute arbitrary code. To fix this, you must eliminate shell execution wrappers and utilize the os/exec package's ability to handle arguments as discrete, non-interpreted strings.
The Vulnerable Pattern
r.Get("/diag/{ip}", func(w http.ResponseWriter, r *http.Request) {
ip := chi.URLParam(r, "ip")
// CRITICAL VULNERABILITY: String concatenation inside a shell wrapper
cmd := exec.Command("sh", "-c", "ping -c 1 " + ip)
out, _ := cmd.CombinedOutput()
w.Write(out)
})
The Secure Implementation
The vulnerable code uses 'sh -c', which invokes a command processor that interprets shell metacharacters. If an attacker passes '8.8.8.8; id', the shell executes both. The secure version removes the shell wrapper entirely. By passing 'ip' as a separate argument to exec.Command, the OS treats it as a literal string argument for the 'ping' binary, not as a command to be parsed. Additionally, the regex validation provides a defense-in-depth layer by ensuring the input matches the expected format before it ever touches the system execution logic.
r.Get("/diag/{ip}", func(w http.ResponseWriter, r *http.Request) { ip := chi.URLParam(r, "ip")// 1. Strict Input Validation (Allow-list approach) re := regexp.MustCompile(`^[a-zA-Z0-9\.]+$`) if !re.MatchString(ip) { http.Error(w, "Invalid Input", 400) return } // 2. Secure Execution: Pass arguments individually without a shell wrapper cmd := exec.Command("ping", "-c", "1", ip) out, err := cmd.CombinedOutput() if err != nil { http.Error(w, "Execution failed", 500) return } w.Write(out)
})
Your Chi API
might be exposed to Command Injection
74% of Chi 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.