Fix Command Injection in Rails
Command injection in Rails is a critical vulnerability that allows an attacker to execute arbitrary OS commands with the privileges of the web application. This typically occurs when developers use shell-executing methods like backticks, %x, system(), or exec() with unsanitized user input. If you're passing strings containing user data directly to the shell, you've already lost.
The Vulnerable Pattern
def generate_pdf
# DANGEROUS: String interpolation allows shell metacharacters like ; | & `
filename = params[:filename]
`wkhtmltopdf reports/#{filename} output.pdf`
end
The Secure Implementation
The vulnerability exists because Ruby's backticks and single-string system() calls spawn a subshell (/bin/sh). This shell interprets metacharacters, allowing an attacker to inject payloads like 'file.txt; rm -rf /'. By passing arguments as an array to system() or Open3.capture3(), Ruby executes the command directly via execve(2), bypassing the shell entirely. This ensures that user input is never parsed for shell commands.
def generate_pdf filename = params[:filename]SECURE: Pass arguments as a list to bypass the shell interpreter
This treats input as literal data, not executable code
system(“wkhtmltopdf”, “reports/#{filename}”, “output.pdf”)
ALTERNATIVE: Use Open3 for more control and security
stdout, stderr, status = Open3.capture3(“wkhtmltopdf”, “reports/#{filename}”, “output.pdf”)
end
Your Rails API
might be exposed to Command Injection
74% of Rails 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.