Fix Command Injection in Rocket
Command Injection in Rust's Rocket framework typically occurs when user-supplied data is passed directly into a shell or system command via 'std::process::Command' without proper sanitization or parameterization. In a 'hacker-style' context, we prioritize eliminating the shell execution layer and treating all input as untrusted data rather than executable code.
The Vulnerable Pattern
#[get("/ping?")] fn ping(host: String) -> String { // VULNERABLE: Direct string interpolation into a shell command let output = std::process::Command::new("sh") .arg("-c") .arg(format!("ping -c 3 {}", host)) .output() .expect("failed to execute process"); String::from_utf8_lossy(&output.stdout).to_string()
}
The Secure Implementation
The vulnerable snippet uses 'sh -c', which invokes a shell to parse the command string. This allows an attacker to append commands using metacharacters (e.g., '; rm -rf /'). The secure version calls the 'ping' binary directly. By passing arguments via the '.arg()' method, the OS treats the input as a literal string argument rather than part of a command stream. Furthermore, explicit input validation restricts the character set, providing a second layer of defense-in-depth.
#[get("/ping?")] fn ping(host: String) -> Result { // SECURE: Pass arguments as distinct elements, bypasses shell interpretation // Additionally, validate input format (e.g., IPv4/IPv6 or hostname) if !host.chars().all(|c| c.is_alphanumeric() || c == '.') { return Err("Invalid input character"); } let output = std::process::Command::new("ping") .arg("-c") .arg("3") .arg(host) .output() .map_err(|_| "Execution failed")?; Ok(String::from_utf8_lossy(&output.stdout).to_string())
}
Your Rocket API
might be exposed to Command Injection
74% of Rocket 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.