Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Developing a secure PHP login and authentication strategy

I'm developing a login and authentication system for a new PHP site and have been reading up on the various attacks and vulnerabilities. However, it's a bit confusing, so I want to check that my approach makes sense.

I plan on storing the following data:

  • In the session: user-id, hashed + salted HTTP_USER_AGENT

  • In the cookie and in the database: random token, hashed + salted identifier

On every page, I plan on doing the following:

  1. If a session exists, authenticate using that. Check that the HTTP_USER_AGENT matches the one in the stored session.

  2. If no session exists, use the cookie to authenticate. Check that the token and identifier in the cookie match those in the database.

  3. If the cookie is invalid or doesn't exist, ask user to login.

Are there any obvious flaws in this? As long as I set a timeout in the cookie, I should be fairly safe, right? Is there anything I'm missing?

Many thanks in advance.

like image 252
Philip Morton Avatar asked Dec 16 '09 20:12

Philip Morton


2 Answers

A few random thoughts :

  1. What if I steal the cookie of one of your users (using an XSS attack by injecting some JS code in your website) ? I will then fall in case 2. and thus be able to log in. IMHO, if you want a really secure authentication, do not use "remember me"-type cookies to store user credentials.
  2. If you do store the credentials in a cookie, please don't store the password in clear.
  3. Checking for the HTTP_USER_AGENT is a good first step to prevent session hijacking, but maybe you could combine it with the IP address ? It is far more difficult to be on the same host than your target than to simply use the same browser.

But in any case, thanks for taking the time of thinking about a good authentication scheme. A lot of PHP developers don't.

EDIT: for the record, let me clarify a point here : there are two cookies in this discusion. One being set automatically by PHP to propagate the session ID (sometimes, we see websites putting it in the URL, eg www.example.com/page.php?sessionId=[...]), and the second one created by you in order to store the user credentials and authenticate him when the session is lost. The XSS attack applies to both, ie an attacker could either steal the session cookie and hijack the session (which has a limited lifetime), or steal the credentials cookie and authenticate later.

like image 122
Wookai Avatar answered Oct 12 '22 02:10

Wookai


there shouldn't be. the php session is stored on your server not the user. php simpily leaves a session cookie pointing to it. if you're not on shared hosting the session doesn't even have to be hashed.

joe

like image 45
Joe Simpson Avatar answered Oct 12 '22 01:10

Joe Simpson