logo

Local File Inclusion - Elixir


Need

Prevent reading or executing server files through relative path manipulation


Context

  1. Usage of Elixir for building scalable and fault-tolerant applications
  2. Usage of Plug Cowboy for building web applications with Elixir
  3. Usage of file handling for reading, writing, and manipulating files
  4. Usage of path sanitization for preventing directory traversal attacks

Description

Insecure Code Example

defmodule MyApp.Router do
  use Plug.Router

  plug :match
  plug :dispatch

  get "/file" do
    file_path = conn.params["path"]
    file_contents = File.read!(file_path)
    send_resp(conn, 200, file_contents)
  end

  match _ do
    send_resp(conn, 404, "Oops, not found!")
  end
end

This Elixir code is vulnerable because it does not sanitize the file path provided by the user, allowing local file inclusion attacks.

Steps

  1. Sanitize the file path to remove any relative path characters.
  2. Ensure that the file path is within the expected directory.

Secure Code Example

defmodule MyApp.Router do
  use Plug.Router

  plug :match
  plug :dispatch

  get "/file" do
    file_path = conn.params["path"]
    sanitized_path = Path.expand(file_path, "/expected_directory")
    if String.starts_with?(sanitized_path, "/expected_directory") do
      file_contents = File.read!(sanitized_path)
      send_resp(conn, 200, file_contents)
    else
      send_resp(conn, 403, "Access Denied")
    end
  end

  match _ do
    send_resp(conn, 404, "Oops, not found!")
  end
end

This Elixir code is safe because it includes validation and sanitization of the file path. It checks that the file path is within the expected directory and does not contain relative path characters.


References

  • 123 - Local File Inclusion

  • Last updated

    2023/09/18