Command Injection in Phoenix
Phoenix-Specific Remediation
The primary defense against command injection in Phoenix is avoiding shell command execution entirely when possible. For file operations that typically require external tools, Phoenix developers can use Elixir libraries instead:
# Instead of using ImageMagick's convert via System.cmd
# Use the image_processing library
defmodule ThumbnailService do
import ImageProcessing
def create_thumbnail(input_path, output_path) do
File.cp(input_path, output_path)
|> resize(100, 100)
|> save!
end
endWhen external commands are unavoidable, Phoenix developers should use argument lists instead of shell strings. The System.cmd/3 function accepts a list of arguments that bypasses the shell:
# SAFE: Argument list prevents shell interpretation
# User input is treated as data, not executable code
System.cmd("convert", ["-resize", "100x100", safe_path, "/tmp/thumb.jpg"])For database operations that might use shell commands, Phoenix developers should use database adapter libraries:
# Instead of shelling out to mysql
# Use Ecto with a database adapter
defmodule QueryExecutor do
import Ecto.Query
def execute_query(query_string) do
# Use prepared statements through Ecto
Repo.query("SELECT * FROM users WHERE name = $1", [query_string])
end
endIf you must use shell commands with user input, validate and sanitize the input rigorously. Phoenix developers can use the Port module with careful argument construction:
def safe_system_command(command, args) when is_list(args) do
# Validate each argument against a whitelist
sanitized_args = args
|> Enum.map(&String.trim/1)
|> Enum.filter(&valid_argument?/1)
Port.open({:spawn_executable, command}, args: sanitized_args)
endFor file processing operations, Phoenix applications should validate file paths and use safe libraries:
def extract_text_from_pdf(pdf_path) do
# Validate path is within allowed directory
unless String.starts_with?(pdf_path, "/app/uploads/") do
raise "Invalid file path"
end
# Use a pure Elixir PDF library instead of shelling out
PDFTextExtractor.extract_text(pdf_path)
endmiddleBrick's scanner helps verify these remediations by continuously testing your Phoenix endpoints even after fixes are applied, ensuring that command injection vulnerabilities remain closed as your application evolves.
Related CWEs: inputValidation
| CWE ID | Name | Severity |
|---|---|---|
| CWE-20 | Improper Input Validation | HIGH |
| CWE-22 | Path Traversal | HIGH |
| CWE-74 | Injection | CRITICAL |
| CWE-77 | Command Injection | CRITICAL |
| CWE-78 | OS Command Injection | CRITICAL |
| CWE-79 | Cross-site Scripting (XSS) | HIGH |
| CWE-89 | SQL Injection | CRITICAL |
| CWE-90 | LDAP Injection | HIGH |
| CWE-91 | XML Injection | HIGH |
| CWE-94 | Code Injection | CRITICAL |