logo

Unauthorized access to files - Elixir


Need

To prevent unauthorized access to files


Context

  1. Usage of Elixir (v1.12+) for building scalable and fault-tolerant applications
  2. Usage of Ecto.Repo for interacting with databases

Description

Insecure Code Example

defmodule MyApp.UserController do
  use MyApp.Web, :controller

  def update(conn, params) do
    user = MyApp.Repo.get!(User, params["id"])
    user = MyApp.Repo.update!(User.changeset(user, params))

    path = "/sharepoint/files/#{user.id}/"
    send_resp(conn, 200, "File updated at #{path}")
  end
end

The Elixir code allows a user to update their data and get access to a specific path in the Sharepoint. However, it doesn't perform any validation or checks on the user input, which could lead to unauthorized access to files.

Steps

  1. Validate user input
  2. Check whether the user is authenticated
  3. Check whether the authenticated user is the same user that is trying to update the data
  4. Only give access to the specific path in the Sharepoint if the user is authenticated and is the same user that is trying to update the data

Secure Code Example

defmodule MyApp.UserController do
  use MyApp.Web, :controller

  def update(conn, params) do
    user = MyApp.Repo.get!(User, params["id"])
    user = MyApp.Repo.update!(User.changeset(user, params))

    if user && conn.assigns.current_user && conn.assigns.current_user.id == user.id do
      path = "/sharepoint/files/#{user.id}/"
      send_resp(conn, 200, "File updated at #{path}")
    else
      send_resp(conn, 403, "Unauthorized")
    end
  end
end

The secure Elixir code checks whether the user is authenticated and is the same user that is trying to update the data before giving access to the specific path in the Sharepoint.


References

  • 201 - Unauthorized access to files

  • Last updated

    2023/09/18