logo

Guessed Weak Credentials - Elixir


Need

Prevent brute force attacks by enforcing a strong password policy.


Context

  1. Usage of Elixir (version 1.11 and above) for building scalable and fault-tolerant applications
  2. Usage of Ecto library for data validation

Description

Insecure Code Example

def register_user(username, password) do
  User.changeset(%User{}, %{username: username, password: password})
  |> Repo.insert()
end

This Elixir function allows a user to register with any password, regardless of its length or complexity. This makes it easy for an attacker to guess weak passwords.

Steps

  1. Add password validation in the changeset function. This should enforce a minimum length and complexity requirements.
  2. Test the application to ensure the password policy is being enforced correctly.

Secure Code Example

def changeset(user, attrs) do
  user
  |> cast(attrs, [:username, :password])
  |> validate_length(:password, min: 8)
  |> validate_format(:password, ~r/[a-z]/, message: "must include a lower-case letter")
  |> validate_format(:password, ~r/[A-Z]/, message: "must include an upper-case letter")
  |> validate_format(:password, ~r/[0-9]/, message: "must include a number")
end

def register_user(username, password) do
  User.changeset(%User{}, %{username: username, password: password})
  |> Repo.insert()
end

This Elixir function enforces a strong password policy during user registration. The password must be at least 8 characters long and include a lower-case letter, an upper-case letter, and a number.


References

  • 050 - Guessed Weak Credentials

  • Last updated

    2023/09/18