logo

Lack of Data Validation - URL - Elixir


Need

To prevent unauthorized access to user data


Context

  1. Usage of Elixir (version 1.12 and above) for building scalable and fault-tolerant applications
  2. Usage of Phoenix framework for building real-time web applications
  3. User authentication implementation

Description

Insecure Code Example

defmodule PortalController do
  use PortalWeb, :controller

  def show(conn, %{"date" => date}) do
    docs = Portal.get_documents_by_date(date)
    render(conn, "show.html", docs: docs)
  end
end

The Elixir code directly uses the date parameter from the URL to fetch documents. There are no checks to verify if the current user has the rights to access these documents.

Steps

  1. Retrieve the current user
  2. Check if the user has the necessary permissions to access the documents
  3. If the user is authorized, proceed as before
  4. If the user is not authorized, display an error message and redirect them to the home page

Secure Code Example

defmodule PortalController do
  use PortalWeb, :controller

  def show(conn, %{"date" => date}) do
    user = get_current_user(conn)
    if user and Portal.user_can_access_documents?(user) do
      docs = Portal.get_documents_by_date(date)
      render(conn, "show.html", docs: docs)
    else
      conn
      |> put_flash(:error, "You are not authorized to access this page.")
      |> redirect(to: "/")
    end
  end
end

The secure Elixir code first gets the current user. If the user exists and they have the necessary permissions to access the documents, we proceed as before. Otherwise, we display an error message and redirect the user to the home page.


References

  • 141 - Lack of Data Validation - URL

  • Last updated

    2023/09/18