logo

Database

Need

Prevent brute force attacks by enforcing a strong password policy.

Context

• Usage of Elixir (version 1.11 and above) for building scalable and fault-tolerant applications

• Usage of Ecto library for data validation

Description

1. Non compliant code

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.

2. Steps

• Add password validation in the changeset function. This should enforce a minimum length and complexity requirements.

• Test the application to ensure the password policy is being enforced correctly.

3. 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")
...

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.