Skip to content

PHP Session Security Best Practices

sobstel edited this page Jul 9, 2011 · 1 revision

PHP Session Security - Best Practices

Session lifetime control

  • Expire session after a short period of inactivity - set the idle timeout to 5 minutes for highly protected applications through to no more than 30 minutes for low risk applications.
  • Enable logout option - explicitly expire and destroy the session on logout.
  • Avoid persistent logins ("remember me" option) - optionally you can constrain the information retained and revealed by the application, i.e. force the user to re-log in before performing any critical operations.
  • Expire session on security error - any security error in the application should result in termination of the session.
  • Expire long lasting session – force re-authentication for session, which despite being active has reached the maximal allowed time, e.g. a few hours.
  • Remove session cookie when destroying a session.

Session identifier

  • Use only cookies to propagate session id, because when transmitted via a URL parameter, GET requests can potentially be stored in browser history, cache and bookmarks. It can be also easily viewable then.
  • Rotate session id - regenerate (replace with new one) session id, at least whenever the user's privilege level changes. Generally it can be regenerated prior to any significant transaction, after a certain number of requests or after a period of time.
  • Check whether session id is valid (of expected size and type) and has been generated by the application and not provided by the user.
  • Session id should be adequately long, unpredictable, hard to reproduce and created from high quality random sources.

Session cookie

  • Set the domain of the cookie to something more specific than the top level domain.
  • Don't store in cookie anything (at least any sensitive data like username or password) but session id.
  • Set http-only flag to disable capturing session id via XSS.
  • When possible, use strong encryption (SSL) as well as "secure" attribute to allow transmitting cookies only over https.

Session data storage

  • Determine where the application framework stores session data and if it is filesystem or database, determine who else might have access to these data.
  • When you store session data in files, ensure the application is configured to use separate private directory (e.g. session.save_path directive). Use filesystem permissions to protect these files from observation or modification by users other than the accounts required to operate the web and application servers. If this is not possible, the session data needs to be encrypted or contain only nonsensitive data. Note that PHP uses public system temporary directory by default.
  • All session variables must be validated to ensure that is of right form and contains no unexpected characters.
You can’t perform that action at this time.