Skip to main content

Local File Inclusion

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

Non compliant code

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

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

Compliant code

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