How secure are PHP sessions?

James picture James · Apr 15, 2012 · Viewed 29.1k times · Source

I'm primarily a C++ programmer, but I'm trying to pick up some PHP.

Apparently the way to implement web user sessions is to store the user's login ID in a cookie using the $_SESSION variable.

Is it not possible for someone to just modify their cookie, to give them different privileges or log in as a different user?

It seems like this authentication mechanism is just having the user store their ID in a file - and then just trusting them not to change it.

Is there something that prevents this?

Thanks!

Answer

0b10011 picture 0b10011 · Apr 15, 2012

PHP sessions are only secure as your application makes them. PHP sessions will give the user a pseudorandom string ("session ID") for them to identify themselves with, but if that string is intercepted by an attacker, the attacker can pretend to be that user.

What to do

This information is taken from "Session Management Basics" in the PHP manual, but simplified a bit. Some things may have been missed. Be sure to read through that as well.

  1. Always use HTTPS

    • Prevents attackers from reading the session ID cookie
  2. Enable session.use_strict_mode:

  3. Enable session.use_only_cookies and disable session.use_trans_sid

    • Avoids user sharing session ID accidentally by sharing a URL with the session ID in it
    • Prevents the session ID from appearing in a Referer header
  4. Periodically regenerate the session ID and invalidate old session IDs shortly after regenerating

    • If an attacker uses another user's session ID, regenerating will invalidate either the user's or attacker's session, depending on which makes the request that regenerates the ID. You can then track when someone tries to use a session that has been regenerated already, and invalidate the regenerated session at that point. The user will be able to log in, but the attacker (hopefully) won't be able to.
  5. Optionally keep track of additional information in $_SESSION that relates to the request (IP address, user agent string, etc)

    • If an attacker somehow gains access to a session ID, this can possibly detect the intrusion before the attacker can access any data. However, keep in mind that this may worsen the user experience. For example, the IP address may change when the user switches from a mobile network to Wi-Fi, and the user agent string may change when their browser automatically updates. Adjust the data checked according to the tradeoffs your site is willing to deal with.