Login session hijack

For login session hijack, would it be good to session the login user ip and when checking if a user is logged in or not checks for its ip too?
I know i should care for X_Forwarder ip too but my question is in general how to prevent session hijack? How about if SID cookie is stolen? Please advice.

There are actually two different things you need to care of here. First is session hijacking, second is session fixation.

Session hijacking
In order to prevent session hijacking you would record the user’s IP (and browser, if you so wish), in their session. Then every time they hit a page on your website you check if their IP is the same as the one in the session. If it’s not, log them out. Whether you check for proxies here doesn’t really change the principle, and it’s arguable whether you’d want that, since it’s easy to add X_FORWARDER_FOR headers and the like, while it’s very hard (of not impossible) to fake ones IP.

Session fixation
In this case the attacker, Bob, sits behind a public computer somewhere knowing that his victim, Alice, will log in within the next few hours. What Bob does is he goes to the website he knows Alice will visit, and note down the session id. Then he leaves the computer and waits for Alice to log in. Once she does he sets the session ID on his own PC to the session ID he wrote down, and boom, he’s logged in as Alice.
The fix for this is quite easy: change the session ID when someone logs in, using [fphp]session_regenerate_id[/fphp]

Thanks for the advice.

  1. So regenerating session id, will silve SID cookie hijacking too?
  2. You said setting fake ip as X_FORWARDE_FOR, then how should i care about proxies as the ip change on any page request? If only checking REMOTE_ADDR then they will have problem if their ISP is using proxy, so how to solve this?

No, you need the IP for that.

Generally IPs don’t change within one connection from the user to their provider. If they are using a proxy, the REMOTE_ADDR you will receive is that of the proxy server. So, if multiple users use the same proxy they will be able to hijack each others cookies. On the other hand, if you do use X_FORWARDED_FOR, people can easily look at the IP of their victim and set as their X_FORWARDER_FOR to fake that they are their victim.
The best solution is probably to record more than just the IP, so for example record the REMOTE_ADDR and HTTP_USER_AGENT (browser identity string), and check for both every time. So even if someone were to hijack the cookie they would have to use the same IP, and the exact same browser. That’s already a lot harder than just the IP.

So, regarding HTTP_ADDR and X_FORWARDER_FOR, I think both solutions have pros and cons, and I can’t really decide which the worst of two evils. The best you can do is add more info.