Skip to main content

Data Uniqueness Not Properly Verified

Need

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

Context

  • Usage of Elixir for building scalable and fault-tolerant applications
  • Usage of Elixir Ecto for database query and manipulation
  • Usage of unique tokens for database record identification

Description

Non compliant code

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

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

Compliant code

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