logo

Database

Need

Prevent reading or executing server files through relative path manipulation

Context

• Usage of Elixir for building scalable and fault-tolerant applications

• Usage of Plug Cowboy for building web applications with Elixir

• Usage of file handling for reading, writing, and manipulating files

• Usage of path sanitization for preventing directory traversal attacks

Description

1. Non compliant code

defmodule MyApp.Router do
  use Plug.Router

  plug :match
  plug :dispatch

  get "/file" do
    file_contents = File.read!(file_path)...

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

2. Steps

• Sanitize the file path to remove any relative path characters.

• Ensure that the file path is within the expected directory.

3. Secure code example

defmodule MyApp.Router do
  use Plug.Router

  plug :match
  plug :dispatch

  get "/file" do
    sanitized_path = Path.expand(file_path, "/expected_directory")...

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.