views:

1082

answers:

9

Currently when user logged in, i created 2 sessions.

$_SESSION['logged_in'] = 1;
$_SESSION['username']  = $username; // user's name

So that, those page which requires logged in, i just do this:

if(isset($_SESSION['logged_id'])){
// Do whatever I want
}

Is there any security loopholes? I mean, is it easy to hack my session? How does people hack session? and how do I prevent it??

EDIT:

Just found this:

http://www.xrvel.com/post/353/programming/make-a-secure-session-login-script

http://net.tutsplus.com/tutorials/php/secure-your-forms-with-form-keys/

Just found the links, are those methods good enough?? Please give your opinions. I still have not get the best answer yet.

+1  A: 

You can find a guide on session security in PHP here.

PatrikAkerstrand
+2  A: 

You can steal sessions via javascript (XSS->crossside scripting attack).. You should always use a salted MD5 Hash to secure your session.

To avoid session hijacking, you should put the user agent

$_SERVER['HTTP_USER_AGENT']

into the hash as well.

In your example:

$_SESSION['logged_in'] = 1;
$_SESSION['username']  = $username; // user's name
$_SESSION['hash']      = md5($YOUR_SALT.$username.$_SERVER['HTTP_USER_AGENT']); // user's name hashed to avoid manipulation

Before using the session, make sure it uses the correct hash:

if (!$_SESSION['hash']==md5($YOUR_SALT.$username.$_SERVER['HTTP_USER_AGENT'])){
  die ('session hash not corrected')
}
Peter Parker
Okay. Seems like your answer being voted up the most. Well, after I create the hash session, in other pages that require login, I need to check the $_SESSION['logged_in'] or $_SESSION['hash']? U get what i mean? e.g if(isset($_SESSION['XXX']){ // do watever}
bbtang
User agent? $_SESSION['hash'] = md5($YOUR_SALT.$username.Firefox); ????
bbtang
It depends on how you logout the user. By right, you should unuset the entire session. You should check for both logged_in and the hash, IMHO.
Extrakun
Yes, The user agent is the browser name (plus version etc.)
Colin
+2  A: 

This is the usual log-in code, some improvements can be made to make it harder to break. First, you can do a checksum with the username and the time of the log in or alternatively, a predefined string (or a salt), and store it in the session, and compare it.

So when the user log in:

// not the most secure hash!
$_SESSION['checksum'] = md5($_SESSION['username'].$salt);

And before entering a sensitive area:

if (md5($_SESSION['username'].$salt) != $_SESSION['checksum'])
{
  handleSessionError();
}

By default, sessions are often store as files on the server side, and a cookie is put on the user's browser to remember which file to refer to. When it comes to session hacking, somehow the hacker retrieve enough information to duplicate the log-in or managed to change the session data, by using information from the cookie.

You could code your own session handling using databases for added security. Some stricter CMS, like Joomla, also logs the IP. However, this cause problems for people using certain ISP

Extrakun
Looks like your method is very good, and I can understand immediately. But I am wonder why nobody vote this answer up?? Is extrakun's method anything wrong??
bbtang
No it is fully OK. +1 for mentioning unsecureness of md5 hashs
Peter Parker
+1  A: 

You can store the IP address, browser signature, etc. to identify the user. At each request, check it against the current values to see if anything suspicious happened.

Be aware that some people are behind providers that use absolutely dynamic IP addresses, so those people might get often logged out.

Zed
I, myself, using dynamic IP, i think its kinda troublesome and might pissed of dynamic IP users.. U have better way? How about extrakun method? Is it good?
bbtang
+2  A: 

I guess the second one needs to be 'logged_in'?

Some resources regarding session security:

phpsec

shiflett

koen
Based on the link you provided, after user login, i should call this: session_regenerate_id()? is that all? I just set this session_regenerate_id() and $_SESSION['logged_in'], so in other pages that required login, i just do: if(isset($_SESSION['XXX']){ // do watever}
bbtang
session_regenerate_id() is a way to handle session hijacking. But it has disadvantages too (eg the back button of the browser won't work as expected).If you don't have a website with highly sensitive data, I would advice regenerating session id only when the user does special things like changing password, edit his account, or enters the area where he does those things.
koen
@koen: can you elaborate on what you meant by "the back button of the browser won't work as expected"? After seeing this comment, I did some research, and there was another user on this site who said a similar thing, but appeared to have been debunked: http://stackoverflow.com/questions/2490707/what-are-the-weaknesses-of-this-user-authentication-method/2490749#2490749
Kristina
@Kristina. I'll quote from the book Pro PHP Security (page 323): "Permitting session IDs to be transferred as $_GET variables appended to the URI is known to break the Back button. Since that button is familiar to, and relied upon by, even the most naive users, the potential for disabling this behavior is just another reason to avoid transparent session IDs."
koen
@koen: So the problem only exists if you pass a session id in the URL? That makes sense, though I don't understand why anyone would pass a session ID via GET in the first place.
Kristina
@Kristina It's often a fallback. I believe that's also how PHPBB3 does it if you need an example (not sure though).
koen
+6  A: 

This is ridiculous.

Session hijacking occurs when (usually through a cross site scripting attack) someone intercepts your sessionId ( which is a cookie automatically sent to the web server by a browser).

Someone has posted this for example.

So when the user log in:

// not the most secure hash! $_SESSION['checksum'] = md5($_SESSION['username'].$salt);

And before entering a sensitive area:

if (md5($_SESSION['username'].$salt) != $_SESSION['checksum']) {
handleSessionError(); }

Lets go through what is wrong with this

  1. Salts - Not wrong, but pointless. No one is cracking your damn md5, who cares if it is salted
  2. comparing the md5 of a SESSION variable with the md5 of the same variable stored in the SESSION - you're comparing session to session. If the thing is hijacked this will do nothing.
$_SESSION['logged_in'] = 1;
$_SESSION['username']  = $username; // user's name
$_SESSION['hash']      = md5($YOUR_SALT.$username.$_SERVER['HTTP_USER_AGENT']);

// user's name hashed to avoid manipulation

Avoid manipulation by whom? magical session faeries? You're session variables will not be modified unless your server is compromised the hash is only really there to nicely condense your string into a 48 character string (user agents can get a bit long).

At least however we're now checking some client data in instead of checking SESSION to SESSION data, they've checked the HTTP_USER_AGENT (which is a string identifying the browser), this will probably be more than enough to protect you but you have to realise if the person has already taken your sessionId in someway, chances are you've also sent a request to the bad guys server and given the bad guy your user agent, so a smart hacker would spoof your user agent and defeat this protection.

Which is were you get to the sad truth.

As soon as your session ID is compromised, you're gone. You can check the remote address of the request and make sure that stays the same in all requests ( as I did ) and that'll work perfectly for 99% of your client base. Then one day you'll get a call from a user who uses a network with load balanced proxy servers, requests will be coming out from here through a group of different IPs (sometimes even on the wrong network) and he'll be losing his session left right and centre.

linead
definitely the best answer. hashing information inside the session doesn't help anything.another approach is to store the hash in a separate cookie, this way the bad boys have to spoof the cookie too
knittl
So can you give me some code? I am stupid, can read php code but cant read the long text, or at least I dun quite get wad you mean. All I know is that, you are quite disagree with others people method, as they had used pointless salt. Okay, when an user logged in, what session you will stored?? And which session you will validate before entering sensitive area??
bbtang
Another idea instead of checking the remote address is to check the user-agent. I won't be as effective as ips (about 45% effective) but won't cause problem with users on load balanced proxies.
Andrew Moore
@Andrew: no need to store session? Just check the user agent??? Sounds weird to me.. Can write some code in new answer instead of in comment? I understand php code more than long text :blush: ^^,
bbtang
**@bbtang:** $_SESSION holds just enough information to uniquely identify your user and then something to identify the client (IP or user-agent or both). The end user cannot see that information, he only receives a randomly generated id which the server then associates to that information. There is no way for the client to see what's in `$_SESSION`
Andrew Moore
+1  A: 

To prevent session fixation, which is basically guessing the SID or stealing it using various methods. NO matter how sophistacated your session logic is, it will definitely be vulnerable to sessid stealing to some degree. That's why you have to regenerate the ID everytime you do something important. For example if you're gonna be making a post or changing a setting in the admin, first run session-regenerate-id. Then the hacker has to go through the process of hacking you again. This basically gives the hacker a one time shot with an ID with all the time he wasted.

http://us.php.net/manual/en/function.session-regenerate-id.php

Or you can change the id every so turns

if($_SESSION['counter']==3) {session_regenerate_id();$_SESSION['counter']==0}

Also, $_SERVER['HTTP_USER_AGENT'] isn't very reliable. Try to avoid it not only for that reason, but because it's convenient for hackers bc they know agents are widely used for this. Instead try using $_SESSION['id_token'] = sha1(some crazy info like file memory, filename, time).

Stanislav Palatnik
U got a point (voted up), hackers could easily guess what user-agent being used. So how about doing multiple check? Hash a session, compare IP with IP session and compare user-agent with user-agent session. BTW, u mentioned that I need to regenerate ID everytime I do something important, thats mean I need to destroy every session before regenerate a new one??
bbtang
Not necessarily, as long as you regenerate the ID the hax will have to start over, unless he has access to the filesystem, in which case he can just modify the script himself!
Stanislav Palatnik
+14  A: 

Terminology

  • User: A visitor.
  • Client: A particular web-capable software installed on a particular machine.


Understanding Sessions

In order to understand how to make your session secure, you must first understand how sessions work.

Let's see this piece of code:

session_start();

As soon as you call that, PHP will look for a cookie called PHPSESSID (by default). If it is not found, it will create one:

PHPSESSID=h8p6eoh3djplmnum2f696e4vq3

If it is found, it takes the value of PHPSESSID and then loads the corresponding session. That value is called a session_id.

That is the only thing the client will know. Whatever you add into the session variable stays on the server, and is never transfered to the client. That variable doesn't change if you change the content of $_SESSION. It always stays the same until you destroy it or it times out. Therefore, it is useless to try to obfuscate the contents of $_SESSION by hashing it or by other means as the client never receives or sends that information.

Then, in the case of a new session, you will set the variables:

$_SESSION['user'] = 'someuser';

The client will never see that information.


The Problem

A security issue may arise when a malicious user steals the session_id of an other user. Without some kind of check, he will then be free to impersonate that user. We need to find a way to uniquely identify the client (not the user).

One strategy (the most effective) involves checking if the IP of the client who started the session is the same as the IP of the person using the session.

if(logging_in()) {
    $_SESSION['user'] = 'someuser';
    $_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
}

// The Check on subsequent load
if($_SESSION['ip'] != $_SERVER['REMOTE_ADDR']) {
    die('Session MAY have been hijacked');
}

The problem with that strategy is that if a client uses a load-balancer, or (on long duration session) the user has a dynamic IP, it will trigger a false alert.

Another strategy involves checking the user-agent of the client:

if(logging_in()) {
    $_SESSION['user'] = 'someuser';
    $_SESSION['agent'] = $_SERVER['HTTP_USER_AGENT'];
}

// The Check on subsequent load
if($_SESSION['agent'] != $_SERVER['HTTP_USER_AGENT']) {
    die('Session MAY have been hijacked');
}

The downside of that strategy is that if the client upgrades it's browser or installs an addon (some adds to the user-agent), the user-agent string will change and it will trigger a false alert.

Another strategy is to rotate the session_id on each 5 requests. That way, the session_id theoretically doesn't stay long enough to be hijacked.

if(logging_in()) {
    $_SESSION['user'] = 'someuser';
    $_SESSION['count'] = 5;
}

// The Check on subsequent load
if(($_SESSION['count'] -= 1) == 0) {
    session_regenerate_id();
    $_SESSION['count'] = 5;
}

You may combine each of these strategies as you wish, but you will also combine the downsides.

Unfortunately, no solution is fool-proof. If your session_id is compromised, you are pretty much done for. The above strategies are just stop-gap measures.

Andrew Moore
Cool. i think your method works best, no doubt about it. What if, I combine the check, first check if user logged in, check if the IP matched with the session IP and check if the user agent matched with the session user agent?? Is it pointless? I just need to use 1 of it issit??
bbtang
BTW, based on koen answer. Seems like session_regenerate_id() is another good stuff huh? Can I do this way, after user logged in, session_start() and then call the sessio_regenerate_id()?? Is it good or its pointless (extra things only)??
bbtang
**@bbtang:** Combining both methods will also combine their downsides. You can do so at your discretion.
Andrew Moore
**@bbtang:** You definitely don't want to do it every request, but you can. I've updated my post...
Andrew Moore
@andrew: I see. Well, seems like there is no best method to avoid hacking. Just curious, which method u have used so far?? (I think must be a more advanced method huh??)
bbtang
**@bbtang:** I've used all three, separately and combined depending of the requirements. Unfortunately, there is no more advanced method as there is only so many things the client sends you that you can use to uniquely identify it.
Andrew Moore
I would like to point out that by default session data is stored in /tmp (on linux) and therefore can be read by either a vulnerability in an application, or if you are on a shared host by other users on the same host. You should not assume the content of the session stored locally is safe.
DeveloperChris
A: 

When I was encountering this issue while building SugarCRM, I tracked and validated the IP address of the user (in addition to some other things). I only compared the first three sections of the IP address. This allowed for most of the locally variable IP addresses. I also made it possible to turn off the IP address validation for installations where a major variation in IP address was common. I think only comparing the beginning of the IP address helps you with the security without adding such a severe limitation to your application.

Example: "###.###.###.---" Only the portion of the IP address marked with '#' would be verified.

192.168.1.101
192.168.1.102
192.168.1.XXX

Are all considered equal.

Jacob

TheJacobTaylor
Most load balancer setups I know use multiple ISPs. You can't rely on that.
Andrew Moore
What I have encountered is that under normal conditions, many customers are quite well served with this approach. If they have a very aggressive network management setup they might well need to turn the feature off. It was easy to turn off the verification. Many customers would only have a major change when a network pipe was modified or broken.
TheJacobTaylor