cookies - 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.

People are also looking for solutions to the problem: php - Batch string replace


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.