OS Command Injection - Elixir

OS Command Injection - Elixir

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

Non compliant code

        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

  • 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.

Compliant code

        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