Search code examples
phpsecuritysessionsession-hijacking

PHP Checking User Agent and IP To Prevent Session Hijacking


I'm trying to figure out how to prevent session hijacking. Here's what I was thinking of doing:

Along with the user id session, add a user agent and user IP session too. Every time a page is loaded, these sessions will be checked to see if they match - will this be enough? For example:

<?php

$userIp = $_SESSION['userIp'];
$userAgent = $_SESSION['userAgent'];

if ($userIp != $_SERVER['REMOTE_ADDR'] || $userAgent != $_SERVER['HTTP_USER_AGENT'] {
    session_destroy();
}

?>

Thanks.


Solution

  • It's much more complex than that. Your site/service will be accessed by a variety of people with different setups. The first thing that can go wrong is if someone is going through a proxy server. The IP that your app will see can change, and the session will break even for a valid user.

    If you absolutely need to do something with the IP, the most you can do without getting too many false positives is checking the originating country/region. If you detect one login from Canada and another one from India, there might be an issue. Even then, it's not fool-proof.

    The user agent is also too easy to fake: if I can get someone's PHPSESSIONID, then I can definitely get their User Agent as well. So not much has been accomplished here.

    The best way to protect someone's session is to put everything authenticated behind HTTPS, and make sure that the session cookie is HTTPS-only.

    EDIT: If it comes to the point where the data you are protecting behind the session is extremely sensitive, and your users need to be aware of it, you can always show them other sessions that are logged in for their users. The same thing is done by GMail for example.