So I have a few different ways to try and prevent session hijacking, one uses the HTTP_USER_AGENT
and detects if it has changed during a session. The problem with this is, if a user goes to the website on a mobile phone, and changes from the mobile view to a desktop view, the user agent changes and the user gets the following error:
if (isset($_SESSION['HTTP_USER_AGENT']))
{
if ($_SESSION['HTTP_USER_AGENT'] != md5($_SERVER['HTTP_USER_AGENT']))
{
echo "Error: security issue #1 (Please use contact us if recieving this error)";
exit;
}
}
else
{
$_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);
}
Now I still want this small layer of security, but i don't want an error message appearing and i want the site to remain viewable to the user. How should i do this?
The user will need to re-authenticate themselves when switching device (rather than causing the error), then you can use both authenticated $_SESSION['HTTP_USER_AGENT']
variables to compare against on future requests.
To hijack a session you need to know its ID. You do this either by guessing a valid session ID or by obtaining it from either the client or the server.
The former is quite easy to mitigate: the more entropy, the better. But the latter cannot be mitigated with just one measure as a session ID can be exposed/obtained on multiple ways:
Some of these can be fixed quite easy: eavesdropping can be avoided by using a secure channel (i. e. HTTPS) and leakage via URL can be avoided by transmitting the session ID in a cookie (with both HttpOnly and Secure flag). Preventing XSS is the hardest as you have to take care of every user originated input data before returning it back to the client.
But if you do this, you’re quite well protected against Session Hijacking. At least the part you can control as an attacker could obtain the cookie directly from the browser’s cookie jar. But that’s out of your scope.
The premise behind the question reflects a misunderstanding.
The User-agent is not an effective way to prevent session hijacking. Any attacker worth their salt can trivially spoof their User-agent to match that of the hijacked user. This defense is at best security through obscurity.
The proper way to prevent session hijacking is to use proper security practices, such as secure session management, site-wide SSL, CSRF protection, proper input validation and output escaping, preventing XSS, and the like. OWASP has some excellent resources on securing web applications.