Lack of Data Validation - URL - Elixir

Lack of Data Validation - URL - Elixir

Need

To prevent unauthorized access to user data

Context

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

Description

Non compliant code

        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

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

Compliant code

        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