Insecure Object Reference - Files
Need
Prevent unauthorized users from accessing or manipulating information
Context
- Usage of Elixir 1.12 for functional programming
- Usage of Phoenix Framework 1.6 for web development
Description
Non compliant code
def show(conn, %{"id" => id}) do
file = Repo.get!(File, id)
send_resp(conn, :ok, file)
end
This insecure code example shows an Elixir Phoenix application that retrieves a file by its ID without checking the user's permissions. An attacker can exploit this by guessing or brute-forcing the file IDs to access other users' files.
Steps
- Before returning the file, check if the authenticated user has the necessary permissions to access it
- Return a 403 Forbidden status code if the user does not have the necessary permissions
Compliant code
def show(conn, %{"id" => id}) do
file = Repo.get!(File, id)
if has_permission?(conn.assigns[:current_user], file) do
send_resp(conn, :ok, file)
else
send_resp(conn, :forbidden, "You do not have permission to access this file")
end
end
defp has_permission?(user, file) do
user.id == file.user_id
end
This secure code example includes a check to ensure the authenticated user has the necessary permissions to access the file before it is returned. If they do not, a 403 Forbidden status code is returned.