How to fix Command Injection
in Plug
Executive Summary
Command injection in Elixir/Plug applications typically occurs when user-supplied parameters are passed directly into functions that interface with the underlying OS shell, such as System.shell/1 or :os.cmd/1. This allows an attacker to execute arbitrary system commands by injecting shell metacharacters like ;, |, or &&.
The Vulnerable Pattern
defmodule Router do use Plug.Router plug :match plug :dispatch
get “/check-host” do # VULNERABLE: Direct concatenation into a shell string host = conn.params[“host”] output = System.shell(“nslookup ” <> host) send_resp(conn, 200, elem(output, 0)) end end
The Secure Implementation
The vulnerability exists because System.shell/1 invokes /bin/sh, which interprets shell metacharacters. An attacker providing 'google.com; cat /etc/passwd' would trigger RCE. The fix involves replacing System.shell/1 with System.cmd/2. System.cmd/2 executes the binary directly and treats the elements in the second argument as literal strings, preventing command chaining or shell expansion. Furthermore, implementing strict input validation using regular expressions adds a layer of defense-in-depth.
defmodule Router do use Plug.Router plug :match plug :dispatch
get “/check-host” do host = conn.params[“host”] # SECURE: Using System.cmd with an argument list avoids shell expansion # Additionally, validate input format (e.g., regex for domain/IP) if host =~ ~r/^[a-zA-Z0-9.-]+$/ do {result, _exit_code} = System.cmd(“nslookup”, [host]) send_resp(conn, 200, result) else send_resp(conn, 400, “Invalid input”) end end end
Your Plug API
might be exposed to Command Injection
74% of Plug 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.