Blog: How Tos

The Right Way To Do Session Management

Pedro Venda 25 Feb 2015

sessionmanagement

Even today, despite years and years of cumulative experience, we find web applications that fail in many ways to provide good security. An issue we often across often is how badly session management is implemented.

In order to understand the problem let’s go back to basics.

The fundamentals

HTTP and the web exist on the basis that browsers are dumb terminals that process information pushed by web servers, in particular HTML, JavaScript, CSS + and whatever else via plugins. Not the other way around (generally speaking).

HTTP is by definition stateless and web servers simply push content via this protocol. Today of course HTTP is anything but stateless at multiple levels. And most of this holds up simply at the cost of cookies – themselves part of the HTTP protocol.

Apart from user input via GET, POST and cookies, there is very little that the browser sends back to the application, one example being the user agent. You could come up with a way of identifying tabs and windows (both entities are essentially the same) but really what would this achieve in addition to what we have?

What you can do on the server side is track activity and track a timeout of inactivity after which you destroy the session. The same should happen immediately if the user triggers the logout (and indeed we report it as a vulnerability if it does not happen).

I have seen heartbeat systems implemented in AJAX that allow the session to be destroyed very quickly once a tab or window has been shut, causing the heartbeat to stop. Personally I reckon that this misses the point and introduces a new weakness. If the user leaves the workstation unlocked the heartbeat ensures the session is kept alive, despite the user being inactive.

NB: In this case heartbeat relates to client side code that every few seconds sends an asynchronous AJAX request to the server. On the server side, these heartbeat requests mean that a session is established and a browser is open. Once the heartbeats stop, the application can infer that communication has been cut either because the browser window has been closed or the client lost connectivity.

What can be done about this?

So what makes a web application session management layer secure? The following suggestions cover most of it:

  • Enforcing https with the HSTS header and session cookies marked ‘secure’
  • Renewing the session cookie upon login
  • Ensuring a good long random session identifier
  • Killing the session upon logout
  • Ensuring the session expires within a short period of time
  • Perhaps ensuring that multiple sessions cannot be established

Secure session management is not difficult, it just needs a bit of attention.