Search code examples
phpsecuritycookiesauthenticationphp-password-hash

PHP secured login cookie, am I doing it right?


I'm pretty new to PHP/MYSQL, what I'm aiming at right now is creating a secure simple login cookie, here's what I did:

  1. When a new user register, the script creates a random hashed (salted) string like this: a4c7be8b6426f34c13adc37ba69db2dd, and it's saved in the database as "special cookie".
  2. Each user has his own "special cookie".
  3. When the user attempt successfully to login, the script grabs his special cookie from the database and save it as a cookie to the browser.
  4. In every page the script makes sure the user is logged in by comparing the saved cookie in the browser by the "special cookies" in the database.

is that secure enough?

BTW, I have another question, in PHP 5.5 is password_hash() alone secure enough ?

Thanks in advance.


Solution

  • Security is a great chapter in times of NSA.

    There are different ways that may be considered "secure", here are some points you need to take care of. If one of these points is not true for your application, it might not be considered "secure".

    • Do you have SSL enabled?

    • Are the passwords stored hashed + salted in the database?

    • Is the client able to change the cookie / session contents and use someone else's "secret" to take over the session?

    • Can I brute force the "secret", password or username to gain access? (Limit requests per IP, CAPTCHA, ...)

    • How often does the "secret" change, I'd suggest to change it on every request.

    • Try to use public/private key encryption instead of symmetric hashing/encryption when possible.

    • Use greater salt, found this: <?php $salt = strtr(base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM)), '+', '.'); ?> for bcrypt

    I think your applicatio is not secure unless the "special secret" changes on every request and cannot be used by a different client. Sessions are better in this case because their values get stored on the server (in most modern configurations) instead of plain in cookies on the client. Link each "special secret" to each client's session_id and change the keys every request.