logo

Data Uniqueness Not Properly Verified - Elixir


Need

To ensure that sensitive data intended for single use cannot be reused or regenerated.


Context

  1. Usage of Elixir for building scalable and fault-tolerant applications
  2. Usage of Elixir Ecto for database query and manipulation
  3. Usage of unique tokens for database record identification

Description

Insecure Code Example

defmodule VulnerableApp.Accounts do
  alias VulnerableApp.Repo
  alias VulnerableApp.Accounts.User

  def create_user(attrs \ %{}) do
    %User{}
    |> User.changeset(attrs)
    |> Repo.insert()
  end
end

The following Elixir code creates a user record with a unique token but does not validate the uniqueness of the token. This means that an attacker could create multiple users with the same token, leading to potential security issues.

Steps

  1. Use Ecto's unique constraint feature to ensure that the token is unique across all users.
  2. Handle Ecto's unique violation error when inserting a new user.

Secure Code Example

defmodule SecureApp.Accounts do
  alias SecureApp.Repo
  alias SecureApp.Accounts.User

  def create_user(attrs \ %{}) do
    %User{}
    |> User.changeset(attrs)
    |> Ecto.Changeset.unique_constraint(:token)
    |> Repo.insert()
  rescue
    Ecto.ConstraintError -> {:error, "Token must be unique"}
  end
end

The following Elixir code creates a user record with a unique token and validates the uniqueness of the token. This prevents an attacker from creating multiple users with the same token.


References

  • 095 - Data Uniqueness Not Properly Verified

  • Last updated

    2023/09/18