Lack of Data Validation - Elixir

Lack of Data Validation - Elixir

Need

Prevent injection of malicious characters

Context

  • Usage of Elixir (v1.10+) for building scalable and fault-tolerant applications
  • Usage of Phoenix framework for building web applications

Description

Non compliant code

        defmodule MyAppWeb.UserController do
  use MyAppWeb, :controller

  def create(conn, %{"user" => user_params}) do
    %User{} |> User.changeset(user_params) |> Repo.insert!()
    send_resp(conn, 200, "User created")
  end
end
        
        

In this Elixir code, the application takes user input directly from the request parameters and uses it to create a new User record. This is insecure because there's no validation on the user_params. An attacker could inject potentially malicious characters or pass in invalid data for certain fields.

Steps

  • Always validate user input on the server-side before using it.
  • Use Ecto changesets or a similar mechanism for data validation.

Compliant code

        defmodule MyAppWeb.UserController do
  use MyAppWeb, :controller

  def create(conn, %{"user" => user_params}) do
    changeset = User.changeset(%User{}, user_params)

    if changeset.valid? do
      Repo.insert!(changeset)
      send_resp(conn, 200, "User created")
    else
      send_resp(conn, 400, "Invalid user data")
    end
  end
end
        
        

In this Elixir code, the application validates user input before using it to create a new User record. The changeset.valid? check ensures that the user_params data is valid before attempting to insert it into the database.

References