Skip to main content

Weak credential policy - Password strength

Need

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

Context

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

Description

Non compliant code

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

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

Compliant code

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