php - Is this safe with XSS
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?
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.
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.
精彩评论