Prevent reading or executing server files through relative path manipulation
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.
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.