Preventing execution of arbitrary OS commands
defmodule MyApp.CommandController do
use Plug.Router
plug :match
plug :dispatch
post "/execute" do
command = conn.body_params["command"]
{result, 0} = System.cmd("/bin/sh", ["-c", command])
send_resp(conn, 200, result)
end
end
This insecure code takes a command from the user via a POST request and directly executes it using the System.cmd function. An attacker can craft a command to retrieve or modify sensitive data, or even gain control over the system.
defmodule MyApp.CommandController do
use Plug.Router
plug :match
plug :dispatch
post "/execute" do
command = conn.body_params["command"]
if command in [@allowed_command1, @allowed_command2] do
{result, 0} = System.cmd("/bin/sh", ["-c", command])
send_resp(conn, 200, result)
else
send_resp(conn, 403, "Forbidden command")
end
end
end
The secure code checks whether the provided command is in a list of allowed commands before executing it. This whitelist approach prevents the execution of any arbitrary command, thus mitigating the risk of OS command injection.