PHP Checking User Agent and IP To Prevent Session Hijacking
Asked Answered
S

2

6

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.

Sciatica answered 29/5, 2012 at 18:0 Comment(0)
C
12

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.

Carbonic answered 29/5, 2012 at 18:4 Comment(3)
Thanks for the answer. I'm not too bothered about the first point to be honest, but your second is valid. If I can't figure out a way to prevent this, I'll just use HTTPS.Sciatica
Thanks! By the way, whatever option you decide to go with, I would always suggest adding HTTPS on top. The proliferation of public WiFi hotspots means that anything going without HTTPS is pretty much open for everyone to see.Carbonic
Since you just want to use http, your user's username and password already can get by a hacker if the user doesn't use vpn. Not even need to think for session.Surfing
S
1

I agree with z42

also i would like to suggest an approach, everytime an user logins successfully to your site you can generate a SALT and store it in a session and in your db aswell, and make conditions to check if the user is already logged or not, with this you cant prevent multiple users to logon with the same account more than once and destroy the SALT from db when user loggs off.

Shire answered 29/5, 2012 at 18:17 Comment(1)
Thanks for the suggestion, very helpful! I'll be sure to make use of this technique.Sciatica

© 2022 - 2024 — McMap. All rights reserved.