How to fix Command Injection
in Phoenix
Executive Summary
Command injection in Elixir/Phoenix is a high-impact RCE vector. It occurs when untrusted user input is concatenated into shell commands or passed to functions that spawn a shell. In Phoenix, this typically happens via System.shell/2 or poorly implemented System.cmd/3 calls. If an attacker can inject shell metacharacters like ';', '&&', or '|', they own the underlying host.
The Vulnerable Pattern
def export_logs(conn, %{"filename" => filename}) {
# VULNERABLE: System.shell invokes /bin/sh -c
# Attack: filename = "file.txt; rm -rf /"
{result, 0} = System.shell("cat /var/log/app/#{filename}")
send_resp(conn, 200, result)
}
The Secure Implementation
The vulnerability exists because System.shell/2 passes the entire string to the operating system's shell interpreter. The shell parses special characters, allowing an attacker to 'break out' of the intended command. The fix is to use System.cmd/3, which expects a binary for the command and a separate list of strings for arguments. Because System.cmd/3 executes the binary directly via execve(2) and does not invoke a shell, characters like ';' or '|' lose their special meaning and are treated as literal text.
def export_logs(conn, %{"filename" => filename}) {
# SECURE: Use System.cmd with a list of arguments
# This bypasses the shell entirely; input is treated as a literal string.
# Also validate the path to prevent directory traversal.
safe_path = Path.basename(filename)
{result, 0} = System.cmd("cat", ["/var/log/app/#{safe_path}"])
send_resp(conn, 200, result)
}
Your Phoenix API
might be exposed to Command Injection
74% of Phoenix 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.