So I’m gearing up to protect one of my login forms against brute-force authentication attacks (essentially a bot guessing at a password over and over hoping for success).

I’ve read up on it and every solution I find appears to be more complex than it needs to be (involving adding multiple additional fields to the database).

After tabling it for a few days, an idea hit me. We can do this with very little code and one additional database field, as long as we setup a cron job to help us out.

Let me explain in three simple steps…

The database field

Just add one field to your users table:  login_attempts tinyint default 0

The code

During your authentication check, add login_attempts to your query’s SELECT statement.

Then, before checking the password, execute something like this (illustrated with PHP)

if ($user['login_attempts'] > 5) {
  header('Location: ../?errors=Too many failed login attempts. 
           Please try again in 5 minutes.');
  exit();
}

....

/* if login fails */
UPDATE		 users
SET		 login_attempts = login_attempts + 1
WHERE		 email = :email

The cron

A script that runs every 5 minutes and simply runs the following SQL statement:

UPDATE users
 SET login_attempts = 0

 

Perhaps I’ve under-thought this one, so let me know if anyone sees a hole in my thinking!

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *