User Authentication

From SecurePHPWiki
Jump to: navigation, search

Be wary of code that requires an authenticated user. The first thing such a script should do is to check for user authentication. Otherwise, it may be possible for a malicious user to execute code without being authenticated.

Password Protection

Passwords for user accounts that are stored in a database should be stored as a hash. Assuming a malicious user manages to gain access to your database, this will help prevent user passwords from being compromised. Also enforce strong passwords. Passwords should be a minimum of six characters in length and contain some non-alphanumeric characters. See Default Passwords

Using MD5-encryption

One hash-algoritm is the MD5-method. Using this method is used by many PHP-applications and is considered rather secure.

When using it, you should always use a "salt", making the password more difficult to crack. Example:

$pass = "password"; // from registration-form
$pass = md5($pass); // Restult: 5f4dcc3b5aa765d61d8327deb882cf99

Store md5($pass) in the database and when the user logges in, it checks md5($_POST['pwd']) against the database. But if a hacker gains access to the MD5-hash, he could run a dictionary attack on the hash and easily crack it, therefor you should "salt" your password.

One way of salting is using the username along with the password, and including a "salt" that's used on all users:

$salt = "dfvbkjlkhaeopirenlnads"; // save in config.php
$pass = "password"; // from registration-form
$user = "admin"; // from registration-form
$pass = md5($pass.$salt.$user); // equals running md5("passworddfvbkjlkhaeopirenlnadsadmin") 
(hash: c94f7230ea596512824824c11c2e8072) which takes longer to crack

Then store that into the database and compare in the same way upon login.

Brute Force

It is difficult to defend against brute force attacks. The easiest defense is to enforce strong passwords, see Password Protection above.

An application simulates the requests from a web browser, attempting to gain valid credentials from an authentication system by large numbers of repeated login attempts, using different passwords.

To defend against such an attack, implement a logging system which watches for brute force attempts and slows the attacker down (i.e. sleep()). Also, temporarily block IP addresses which have made repeated failed login attempts.