Unlimited Plugins, WordPress themes, videos & courses! Unlimited asset downloads! From $16.50/m
  1. Code
  2. PHP

How to Build Rate Limiting into Your Web App Login

Final product image
What You'll Be Creating

While reports vary, The Washington Post reported that the recent iCloud celebrity photo hacking centered around Find My iPhone's unprotected login point:

"...security researchers were said to have found a flaw in iCloud's Find My iPhone feature that didn't cut off brute-force attacks. Apple's statement ... suggests the company doesn't regard that revelation as a problem. And that's a problem, according to security researcher and Washington Post contributor Ashkan Soltani.

I agree. I wish Apple had been more forthcoming; its carefully worded response left room for different interpretations and seemed to blame the victims.

Hackers may have used this iBrute script on GitHub to target celebrity accounts via Find My iPhone; the vulnerability has since been closed.

Since one of the wealthiest corporations in the world didn't allocate the resources to rate limit all of their authentication points, it's likely that some of your web apps don't include rate limiting. In this tutorial, I'll walk through some of the basic concepts of rate limiting and a simple implementation for your PHP-based web application.

How Login Attacks Work

Research from prior hacks has exposed passwords that people tend to use most frequently. Xeno.net publishes a list of the top ten thousand passwords. Their chart below shows that the frequency of common passwords in their top 100 list is 40%, and the top 500 make up 71%. In other words, people commonly use and re-use a small number of passwords; in part, because they are easy to remember and easy to type.

Frequency of Common Passwords - From Xenonet

That means that even a tiny dictionary attack using just the twenty-five most common passwords could be quite successful when targeting services.

Once a hacker identifies an entry point that allows unlimited login attempts, they can automate high speed, high volume dictionary attacks. If there's no rate limiting, then it becomes easy for hackers to attack with larger and larger dictionaries - or automated algorithms with infinite numbers of permutations.

Furthermore, if personal information about the victim is known e.g. their current partner or pet's name, a hacker can automate attacks of permutations of likely passwords. This is a common vulnerability for celebrities.

Approaches to Rate Limiting

To protect logins, there are a couple of approaches that I recommend as a baseline:

  1. Limit the number of failed attempts for a specific user name
  2. Limit the number of failed attempts by IP address

In both cases, we want to measure failed attempts during a specific window or windows of time e.g. 15 minutes and 24 hours.

One risk to blocking attempts by user name is that the actual user could get locked out of their account. So, we want to make sure we make it possible for the valid user to re-open their account and/or reset their password.

A risk to blocking attempts by IP address is that they are often shared by many people. For example, a university might host both the actual account holder and someone attempting to maliciously hack their account. Blocking an IP address may block the hacker as well as the actual user.

However, one cost to increased security is often a bit of increased inconvenience. You have to decide how strictly to rate limit your services and how easy you want to make it for users to re-open their accounts.

It can be useful to code a secret question into your app which can be used to re-authenticate a user whose account was blocked. Alternately, you can send a password reset to their email (hoping that it's not been compromised).

How to Code Rate Limiting

I've written a bit of code to show you how to rate limit your web applications; my examples are based in the Yii Framework for PHP. Most of the code is applicable to any PHP/MySQL application or framework.

The Failed Login Table

First, we need to create a MySQL table to store information from failed login attempts. The table should store the ip_address of the requesting user, the attempted username or email address used and a timestamp:

Then, we create a model for the LoginFail table with several methods: add, check and purge.

Recording Failed Login Attempts

Whenever there is a failed login, we'll add a row to the LoginFail table:

For getUserIP(), I used this code from Stack Overflow.

We can also use the opportunity of a failed login, to purge the table of older records. I do this to prevent the verification checks from slowing down over time. Or, you can implement a purge operation in a background cron task every hour or every day:

Checking for Failed Login Attempts

The Yii authentication module I'm using looks like this:

Whenever my login code detects an error, I call the method to add details about it to the LoginFail table:


The verification section is here. This runs with every login attempt:

You can graft these functions on to your own code's login authentication section.

My verification check looks for a high volume of failed login attempts for the username in question and separately for the IP address being used:

I check rate limits for the last fifteen minutes as well as the last hour. In my example, I allow 3 failed login attempts per fifteen minutes and six per hour for any given username:

Note that my verification checks use Yii's ActiveRecord named scopes to simplify the database query code:

I've tried to write these examples so that you can easily customize them. For example, you could leave out the checks for the last hour and rely on the last 15 minute interval. Alternatively, you could change the constants to set higher or lower thresholds for the number of logins per interval. You could also write much more sophisticated algorithms. It's up to you.

With this example, to improve performance, you may want to index the LoginFail table by username and separately by IP address.

My sample code doesn't actually change the status of accounts to blocked or provide functionality for unblocking specific accounts, I'll leave that up to you. If you do implement a blocking and resetting mechanism, you may want to offer functionality to separately block by IP address or by username.

I hope you've found this interesting and useful. Please feel free to post corrections, questions or comments below. I'd be especially interested in alternate approaches. You can also reach me on Twitter @reifman or email me directly.

Credits: iBrute preview photo via Heise Security

Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.