logo

Weak credential policy - Password strength - Elixir


Need

To prevent unauthorized account access due to weak passwords, which can be easily compromised by brute force or dictionary attacks.


Context

  1. Usage of Elixir (1.12.0 and above) for building scalable and fault-tolerant applications
  2. Usage of Comeonin package for password hashing

Description

Insecure Code Example

defmodule MyAppWeb.UserController do
  use MyAppWeb, :controller

  def create(conn, %{"password" => password}) do
    hashed_password = Comeonin.Bcrypt.hashpwsalt(password)
    # ... rest of the code
  end
end

In the insecure code, the application accepts any password provided by the user, without any strength checks. This can lead to weak passwords that can be easily cracked by an attacker.

Steps

  1. Add a password strength check before hashing the password.
  2. The check should ensure the password is a certain length, contains a mix of uppercase and lowercase letters, numbers, and special characters.

Secure Code Example

defmodule MyAppWeb.UserController do
  use MyAppWeb, :controller

  def create(conn, %{"password" => password}) do
    if strong_password?(password) do
      hashed_password = Comeonin.Bcrypt.hashpwsalt(password)
      # ... rest of the code
    else
      # Respond with an error
    end
  end

  defp strong_password?(password) do
    String.length(password) >= 12 && Regex.match?(~r/[A-Z]/, password) && Regex.match?(~r/[a-z]/, password) && Regex.match?(~r/[0-9]/, password) && Regex.match?(~r/[!@#\$%\^&]/, password)
  end
end

In the secure code, the application checks the strength of the password before accepting it. This prevents users from creating accounts with weak passwords.


References

  • 363 - Weak credential policy - Password strength

  • Last updated

    2023/09/18