Skip to main content

Lack of data validation - Path Traversal

Need

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

Context

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

Description

Non compliant code

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

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

Compliant code

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