OS Command Injection
Need
Preventing execution of arbitrary OS commands
Context
• Usage of Elixir (version 1.10 and above) for building scalable and fault-tolerant applications
• Usage of Plug and Cowboy for HTTP request and response handling
Description
1. Non compliant code
defmodule MyApp.CommandController do
use Plug.Router
plug :match
plug :dispatch
post "/execute" do
command = conn.body_params["command"]
send_resp(conn, 200, result)...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.
2. Steps
• Implement a whitelist of allowed commands.
• Check the provided command against the whitelist before executing it.
• If possible, avoid executing OS commands based on user inputs.
3. Secure code example
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])...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.
References
• 404. OS Command Injection