I'm working on login form and I have to limit attempts to 3 and then block any form submit for 10 minutes. The following code isn't working correctly and I need to know how to block submitting after unsuccessful attempts. Thanks.
function autoDefender($attempts,$username,$pass)
{
$logins=0;
$logins++;
$ats = $attempts-$logins;
if (isset($_POST['password']) && isset($_POST['userName']))
{
if($_POST['password']!=$pass && $_POST['userName']!=$username)
{
if($logins == $attempts)
{
echo ("<div class='errmg'>Acess denied for 1 minute</div>");
}
echo ("<div class='errmg'>Error:
invalid username or pass; <span class='atmpts'>$ats</span> attempts left</div>");
}
}
}
The problem here is that with each call of autoDefender
the local variable $logins
is reset to 0
. So the state of how many attempts actually took place is not not maintained across multiple calls of autoDefender
.
You need to store this information somewhere persistently. In your case even across multiple requests.
Note that this does also poses an attack surface for Denial of Service attacks as you can lock-out other users. So you should think twice who you attribute a failed attempt to. If you do it per user, you an attacker might lock-out many users when doing a bulk attack on all users. If you do it per remote client (e.g. IP address), you might lock-out other innocent users that just happen to use the same system (e.g. company or university network). If you do it per session, an attacker might just drop the issued session ID.
Because your code is being executed each time from the beginning, so every time $logins initialized with 0. So, you need to initialize your variable not with 0, but from value of number of previous login attempts from this ip (which should be stored somewhere, i.e. on database).
Don't listen suggestions to store $logins on cookie (or sesstion). It can (and it WILL) be simply erased by attacker. Instead, store it somewhere on server-side: sql database, memcached, berkley db, ... there is a lot of options.
Lastly, for me it seems you are misunderstanding basic (web, and maybe not only web) programming concepts, so it's better to double-check your code with your mentor or use code review site from stackexchange network. Especially when writing so important security-related code.