Page 1 of 1

Are Sessions safe with only a username

Posted: Fri Sep 26, 2008 11:15 am
by miloske
On login page, I use this

Code: Select all

//validation completed and OK
$_SESSION['user']=$username;
later, on each page I use

Code: Select all

if   (!isset ($_SESSION['user'])){
die;
}
else{
//run the page
}
 
I don't use cookies.

Is this safe enough? Could users somehow switch value of the session and be treated as other user? This would be really bad for me, because I use username from that session not just for authentication, but for everything else, for example, when I need to write to database, and I need User_id, I query the database like this

Code: Select all

 
$user=$_SESSION['user'];
$query=mysql_query("SELECT id FROM table WHERE username='$user'");
Administrator panel is out of reach (because it uses separate session - $_SESSION['admin']), but someone could pretend to be other user and mess up with their profile.

So - is it possible to someone to change value of a session (I know it shouldn't be because sessions are stored on the server), and should I add some random data to my sessions?

Re: Are Sessions safe with only a username

Posted: Mon Sep 29, 2008 3:47 am
by Mordred
1. When you say session_start(), you're most probably using cookies - they are the link between the user and his session.
2. Use mysql_real_escape_string on the username before the DB query.

Re: Are Sessions safe with only a username

Posted: Mon Sep 29, 2008 7:21 am
by miloske
Mordred wrote:2. Use mysql_real_escape_string on the username before the DB query.
I'm already using:

Code: Select all

 
if(!get_magic_quotes_gpc()){
$username=addslashes($username);
}

Should I change it to what you said (then I would have to use stripslashes, right)?

Re: Are Sessions safe with only a username

Posted: Mon Sep 29, 2008 8:09 am
by Mordred

Re: Are Sessions safe with only a username

Posted: Tue Sep 30, 2008 7:38 am
by papa
I use a code snippet from php.net for killing sessions:

Code: Select all

 
//if not valid username etc
session_unset();
session_destroy();
$_SESSION = array();
 
Simple mysql escape:

Code: Select all

 
$query = sprintf("SELECT user_name, password FROM ".$user_table." WHERE user_name ='%s' AND password ='%s'", 
mysql_real_escape_string($user_name, $link),
mysql_real_escape_string($password, $link));

Re: Are Sessions safe with only a username

Posted: Fri Oct 03, 2008 11:00 am
by shaneiadt
A session is a type of cookie essentially :)

Re: Are Sessions safe with only a username

Posted: Fri Oct 03, 2008 11:25 am
by Mordred
shaneiadt wrote:A session is a type of cookie essentially :)
... not.

Re: Are Sessions safe with only a username

Posted: Sun Oct 05, 2008 11:12 am
by miloske
Thanks for your replies, they are really helpful.