Prevent unauthorized access to files and directories outside the intended path scope.
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.
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.