logo

Lack of data validation - Path Traversal - Elixir


Need

Prevent unauthorized access to files and directories outside the intended path scope.


Context

  1. Usage of Elixir for building scalable and fault-tolerant applications
  2. Usage of Plug and Cowboy for HTTP request and response handling
  3. File access or operations based on user-supplied path

Description

Insecure Code Example

defmodule VulnerableApp do
  use Plug.Router

  plug :match
  plug :dispatch

  get '/read_file' do
    path = conn.params['path']
    file_content = File.read!(path)
    send_resp(conn, 200, file_content)
  end
end

This code takes a user-supplied path to read a file without validating or sanitizing the input, allowing an attacker to access files outside the intended directory.

Steps

  1. Always validate and sanitize user-supplied input.
  2. Prevent the user from supplying the full path; consider using identifiers to reference files or directories.
  3. Use a whitelist of allowed paths or files.
  4. Check for path traversal sequences (.., ~, /) in the user input and neutralize them.

Secure Code Example

defmodule SecureApp do
  use Plug.Router

  plug :match
  plug :dispatch

  get '/read_file' do
    path = conn.params['path']
    if valid_path?(path) do
      file_content = File.read!(path)
      send_resp(conn, 200, file_content)
    else
      send_resp(conn, 400, 'Bad Request')
    end
  end

  defp valid_path?(path) do
    # Add your path validation logic here
  end
end

This code validates and sanitizes the user-supplied path before reading the file, effectively preventing path traversal attacks.


References

  • 063 - Lack of data validation - Path Traversal

  • Last updated

    2023/09/18