tags:

views:

60

answers:

2

Hi, I need to set a cookie to keep user login state. I'm going to hash username, password and IP. My code:

login process:
$hashed = md5($username.$pwd.IP);
setcookie('userstate', $username.':'.$hashed);

restore user state:
$vars = split(':', $_COOKIE['userstate']);
pseudo: get user with username in $vars[0]
$hashed = md5($username.$pwd.IP);
if($hashed == $vars[1]) return true;
else return false;

Is this way safe with XSS attack?

+5  A: 

A XSS attack is only possible when you are outputting content to the client. Because you aren't, it's not possible.

Another attack vector is SQL injection. You cannot trust the input of the $_COOKIE values. So you would have to escape it when you are trying to get the information from the database.

Ikke
A: 

The code snippet you pasted is NOT SECURE. Assuming that an attacker gets the cookie, it is possible to figure out the password of the user. This is bad - because users tend to reuse passwords across websites.

How can the password be retrieved? Dictionary attacks. The username and IP Address are trivial to figure out. The attacker just needs to use a dictionary of passwords, generate the hash they way you are doing, and then compare it with the hash in the cookie.

The missing thing in your implementation is a server side secret key that is unknown to the attacker. See this page to learn how Spring Security generates the cookie - you should do something similar.

sri
i beg to differ. pwd and IP basically work as a salt, an attacker would have to recompute all of his rainbowtables – which is still infeasable without millions of dollars and decades of years
knittl
I didn't say rainbow tables, I said dictionary attacks. There are common lists of passwords available on the internet. If an attacker tries each of those passwords and compares with the hash in the cookie, there is a very high chance that he will get the right password. By including a server side secret, you make that impossible.
sri