logo

OS Command Injection - Elixir


Need

Preventing execution of arbitrary OS commands


Context

  1. Usage of Elixir (version 1.10 and above) for building scalable and fault-tolerant applications
  2. Usage of Plug and Cowboy for HTTP request and response handling

Description

Insecure 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])
    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.

Steps

  1. Implement a whitelist of allowed commands.
  2. Check the provided command against the whitelist before executing it.
  3. If possible, avoid executing OS commands based on user inputs.

Secure Code Example

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.


References

  • 404 - OS Command Injection

  • Last updated

    2023/09/18