21-void
21-void

Reputation: 43

PHP - Sessions security and reliability

I'm currently learning PHP and I came up with a question about Sessions. Before making this post, I've already read some information and topics such as this one about this subject, but the most part of them are a bit old, so I would like to make sure that I'm handling them the right way.

So, here is my question: Assuming the following items are true,

$_SESSION['check'] = hash('ripemd128', $rand1 . $_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT'] . $rand2).

That value is sent to the database and, in every page, I'm checking if the value on the database matches that $_SESSION['check'] variable;

$_SESSION = array(); setcookie(session_name(), '', time()-259200, '/'); session_unset(); session_destroy();

This way, and assuming that the values put into session variables are properly validated, can I trust 100% on my session variables? If not, what can I improve/change to make them safer?

The reason why I'm asking this is because when the user logs in, I save some information into session variables to avoid overloading the database with queries, so I need to make sure that they can't be compromised.

Thank you.

Upvotes: 2

Views: 1051

Answers (1)

deceze
deceze

Reputation: 521995

The whole dance and song with hashing (not "encripting"!) the user agent and IP with some random values is pretty superfluous. I also don't see the point in bothering the database with it on every request.

What is that good for, what are you trying to prevent? If anything, you want to prevent session hijacking. Let's look at it in detail:

  • Session hijacking means a man-in-the-middle or other 3rd party was able to steal the user's session cookie. You can prevent that simply with HTTPS, it's the only real thing you can do.
  • If some malware on the user's computer stole the cookie instead of a MitM, HTTPS doesn't help. In that case the attacker would likely be sitting elsewhere entirely. In this case checking the IP would help. Checking the user agent is largely superfluous, since it can easily be imitated.
  • To check the IP you simply store the IP directly in the session and do a simple if ($_SESSION['ip'] !== $_SERVER['REMOTE_ADDR']); hashing doesn't add anything to that process.
  • Note that IPs may suddenly legitimately change, which would invalidate the login.
  • Note that malware which is able to steal somebody's cookie might as well impersonate the user right from their own computer, in which case no sort of checking would do anything at all.

Bottom line: any sort of additional check and protection is rather useless. If you're using HTTPS and somebody is still able to hijack the session, you're mostly SOL either way. Don't bother. If you're not using HTTPS, start using it now.

Upvotes: 1

Related Questions