Serious Session Issues

Robizzle01

Limp Gawd
Joined
Sep 30, 2005
Messages
159
I spent nearly all of my weekend toying with this code and I just cant seem to get it to work. Hopefully whatever i'm doing is something simple. I think I documented it fairly well so you should be able to follow but if not, I'll answer any questions.

The idea was to write a script that I can include on all my pages and it will allow me to easily check if a user is logged in or not. It provides me with a function I can call that will display the login form but the nice part is, if the user is already logged in the function wont display the form -- it will display a welcome message instead. My problem is that the session variables aren't getting set. Maybe some kind of a scope issue? I haven't really figured out exactly how includes and functions effect the scope of variables.

I have created a user for you guys to play with, username is HardOPC@msu.edu (my script checks domain name portion of email address hence the @msu.edu.) The password is simply 'password'. I set up a page containing only the login form at http://www.robmeyer.net/store/login_test.php.

Here is the code for all of those pages...

login_test.php
Code:
<?php

include 'login2.php';

$logged_in = checkLoggedIn();

echo "<p>\n\$_SESSION['Username'] == '".$_SESSION['Username']."'<br />";
echo "\$_SESSION['Password'] == '".$_SESSION['Password']."'<br />";
echo "\$_COOKIE['Username'] == '".$_COOKIE['Username']."'<br />";
echo "\$_COOKIE['Password'] == '".$_COOKIE['Password']."'<br />";

echo "\$logged_in == ".$logged_in."\n</p>";

displayLogin();

?>

login2.php
Code:
<?php

/*
 * Details about this specific implementation
 * The database structure we are using contain fields with the following names and values:
 * 	Email		- varchar(50)	- email address of user in the form [email]user@domain.exte[/email]nsion
 * 	PasswordSalt	- varchar(32)	- random string different for each user
 * 	Password	- varchar(40)	- The result of sha1(PasswordSalt.Plain Text Password)
 * 	Active		- binary	- 0 if user has not activated account, 1 if user has
 *
 * For security, the SESSION['Username' / 'Password'] and COOKIE['Username' / 'Password']
 * will be set to the plain text username (email address) and the sha1(PasswordSalt.Password)
 */

// checkUsernamePassword - Given the username in plain text and sha1 and salted password
// this function will check if they are a valid combination.  If they are, then
// we will further check to see that the 'Active' bit is set in the database.
// This gets set when the user activates his/her account by following a link provided
// in email.
// Possible return codes:
//	0: Username / Password combination is valid and Active bit is set
//	1: Username is not in database
//	2: Username / Password combination is not valid
//	3: Username / Password combination is valid, however, Active bit is not set
//	4: Unknown error occured
// Note: in this case, the user's login name is the same as his/her email address
function checkUsernamePassword ($username, $password)
{
	// connect to mysql
	require 'shared_files/mysql_usedtastic.php'; // defines $mysql_username, $mysql_password and $mysql_database
	$db = mysql_connect("localhost", $mysql_username, $mysql_password);
	mysql_select_db($mysql_database, $db);

	// check if $username is in our database
	$sql = "SELECT Password, Active FROM Users WHERE Email = '".$username."'";
	$result = mysql_query($sql, $db);

	mysql_close();

	if (!$result)
	{
		echo "<!-- MySQL Error: ".mysql_error()." -->";
		return 4;
	}

	if ($row = mysql_fetch_array($result))
	{
		// user exists so we will check if passwords match
		if ($password == $row['Password'])
		{
			if ($row['Active'] == 1)
			{
				$_SESSION['Username'] = $username;
				$_SESSION['Password'] = $password;

				return 0; // Username/Password combination is correct and Active bit is set
			}
			else
				return 3; // Username/Password combination is correct, however, Active bit is not set
		}
		else
			return 2; // Username/Password combination is not correct
	}

	return 1; // No such user listed in database
}

// checkLoggedIn - Checks if we either have a session or a cookie set that says the user
// is already logged in.  If we find a cookie, then we set a session as well.
// If we do, then we check if the Username/Password combination they supply is valid
// Possible return codes:
//	0: Either a cookie or session validates this user as logged in
//		Note: if it was a cookie, we will set the session to the same value
//	1: User has neither a valid cookie or valid session
function checkLoggedIn()
{
	// Check if user has a valid cookie, if so, make it the session as well
	if(isset($_COOKIE['Username']) && isset($_COOKIE['Password']))
	{
		$_SESSION['Username'] = $_COOKIE['Username'];
		$_SESSION['Password'] = $_COOKIE['Password'];
	}

	// Check if session Username and Password are set
	if(isset($_SESSION['Username']) && isset($_SESSION['Password']))
	{
		/* Confirm that username and password are valid */
		if(checkUsernamePassword($_SESSION['Username'], $_SESSION['Password']) != 0){
			/* Variables are incorrect, user not logged in */
			unset($_SESSION['Username']);
			unset($_SESSION['Password']);
			return 1;
		}
		return 0; // user is logged in
	}
	// User not logged in
	else
	{
		return 1;
	}
}

/* displayLogIn() - This function will call checkLoggedIn() to see if the user is
 * logged in or not.  If not, then it will display the log in form.  If the user
 * is logged in, it will display a welcome message and a link that may be used to
 * log out at any time.
 */
function displayLogIn()
{
	if (checkLoggedIn() == 0)
	{
		// user is logged in
?>

<p>You are currently logged in as, <?php echo $_SESSION['Username'];  ?></p>
<p>To log out, click <a href="logout2.php">here</a></p>

<?php				
	}
	else
	{
		// user is not logged in
?>

<form action="" method="post">
<table border="0" cellspacing="0" cellpadding="3">
<tr>
	<td align="left">Email:</td>
	<td><input type="text" name="Username" /></td>
</tr>
<tr>
	<td align="left">Password:</td><td><input type="password" name="Password" /></td>
</tr>
<tr>
	<td align="left" colspan="2"><input type="checkbox" name="RememberMe" /> Remember me
	<input type="submit" name="SubmitLogin" value="Login" />
	<a href="index.php?ShowPage=CreateAccount">Sign Up</a></td>
</tr>
</table>
</form>

<?php
	}
}


/* Outside of all functions
 * We will check if the user has supplied a username and password
 * in the login form.  If so, we will check if they are correct and
 * set the session variables.  If the user checked the "remember me"
 * checkbox then we will set cookies as well.
 */

if (isset($_POST['SubmitLogin']))
{

	require 'shared_files/mysql_usedtastic.php'; // defines $mysql_username, $mysql_password and $mysql_database
	$db = mysql_connect("localhost", $mysql_username, $mysql_password);
	mysql_select_db($mysql_database, $db);

	$sql = "SELECT PasswordSalt FROM Users WHERE Email = '".$_POST['Username']."'";
	$result = mysql_query($sql, $db);

	if (!$result)
		echo "<!-- MySQL Error: ".mysql_error()." -->";

	$row = mysql_fetch_array($result);

	mysql_close();

	// if form information is not correct
	if (checkUsernamePassword($_POST['Username'], sha1($row['PasswordSalt'].$_POST['Password'])) != 0)
	{
?>

<p>Invalid username and password combination.</p>

<?php
	}
	else 
	{
		$_SESSION['Username'] = $_POST['Username'];
		$_SESSION['Password'] = sha1($row['PasswordSalt'].$_POST['Password']);

		if (isset($_POST['RememberMe']))
		{
			// if user requested to be remembered, we will set a cookie 
			// with the current session info (expires in 30 days.)
			setcookie("Username", $_SESSION['Username'], time()+60*60*24*30, "/");
			setcookie("Password", $_SESSION['Password'], time()+60*60*24*30, "/");
		}
	}
}

?>

logout2.php
Code:
<?php

session_destroy();

?>

<p>You have been logged out, please click <a href="index.php">here</a> to go back to the main page</p>
 
These forums have some sort of magical property such that I can spend days working on buggy code then immidiatly after posting I notice a problem.

My script still has issues and ontop of that probably some security problems but I just want to get a basic working copy before I tackle that stuff.

So it looks like the session information is working now. The cookies also show up, however, when i click view cookies in firefox i see Username is listed as 'HardOPC%40msu.edu' ... that %40 should be @. What gives? When I echo it right back on the login_text.php it shows up as an @ so maybe its just firefox??

One weird problem is that the cookie appears on my computer as soon as I submit, however, test_login.php echos this back and it is showing the cookies as being blank. Now if i manually refresh once more it fills in these values.

My logout link isn't working. Why does it say?
Code:
Warning: session_destroy() [function.session-destroy]: Trying to destroy uninitialized session in /var/www/localhost/htdocs/store/logout2.php on line 3

I also find the warning about post data extreamly annoying. Is there any way I can get rid of this so that users don't see it every time they refresh a page?
 
for the post warning, try using header("Location: ..."); and send the browser to another page rather than continuing the script when the user logs in... i'm not sure if this is the 'correct' way, but it works for me...

as for the @ being %40, it might be the url encoding for the @ sign, like a space is a %20 in a url.

and maybe use some sort of encryption for storing your passwords in cookies? like store the md5 hash or something...

- jj
 
johnglenn said:
and maybe use some sort of encryption for storing your passwords in cookies? like store the md5 hash or something...

Right now the password that I store for cookies and session id is the sha1(PasswordSalt.Plain_Text_Password). This is also what I have stored in the database as "Password" in the users table, however, I dont think its a security issue because there is no way to login directly using this information. They would have to know the PasswordSalt and then do a brute force check
Code:
X = "aaaaaaaaaa"; // kind of a thing
while ( sha1 (Salt.X) != CookieValue )
  increment X;

As for your suggestion as to how to fix the warning, I'm not sure I follow what you are saying. Which parts of code would I chage? Also, its not just a warning, the biggest problem is that its not working. My session still exists after going to logout2.php.

This also brings up another thing I have wondering about for a long time. Right now my entire page is run by index.php. It includes a header and a footer and in the middle it runs a switch ($_GET['ShowPage']) to decide which page to include. Then every page i write doesn't need to be concerned with the header and footer and really just worries about what to display in the main content area. Not sure if this is a good way or if i'm going to run myself into problems later on when I try to add more functionality. Since all my php is self-taught I never really got formal training on how to organize file structure and manage all these includes and function calls.
 
Robizzle01 said:
As for your suggestion as to how to fix the warning, I'm not sure I follow what you are saying. Which parts of code would I chage? Also, its not just a warning, the biggest problem is that its not working. My session still exists after going to logout2.php.
for your sessions not going away, clear your $_SESSION array. this is how i log out:
Code:
$_SESSION = array();  // clear all your $_SESSION var

// clear your cookies
if (isset($_COOKIE[session_name()])) {

    setcookie(session_name(), '', time()-42000, '/');
}

setcookie("Username", '', time() - 60*60*24*30, "/");
setcookie("Password", '', time() - 60*60*24*30, "/");

session_destroy();
be sure to start a session every page.

for the 'header' thing i suggested...
Code:
// login psuedocode
if($password == $row['password']) {

    // i'm logged in
    header("Location: www.site.com/index.php?showpage=page");
}
i don't know if it's the 'legit' way to do it, but if 'page' is the page you want users to see after they log in, php will redirect the browser there.

as for having everything go through index.php... i do sites like that. i think something to watch out for is using the showpage variable as a filename. like if you have...

Code:
www.site.com/index.php?showpage=file

and in your php, you have

Code:
include $_GET['showpage'].'html';

then someone could enter

Code:
www.site.com/index.php?showpage=www.mysite.com/page

and your php would include a foreign file (i think).

my php is self taught too so it might not be the correct way to do things...

i hope this helps.
 
Alright, got it working. I hope nobody minds that I take down those files so they don't clutter up my test server. A few misc questions that came up during my learning experience:

Where is the session information stored? I'm guessing serverside which i'd like for security reasons but then what is this "cookie" firefox shows me called PHPSESSID?

When storing cookies, I understand that you never want to put any confidential information on the user's computer. Equally importantly, all cookie data flows through the internet and can be packet sniffed easily i'm told. So when I was writting my login scripts I had the Username cookie save the user's email address (what my site uses as username for all logins) and the salt hashed version of the user's password. Now, as I understand it, in order for an attacker to reverse calculate the users plaintext password he/she would need to run a brute force attack. Furthermore, since I salted the password hash, that complicates things to the attacker to a 1.55 million year attack (Scroll down to tables) with today's computers. Now my question...
When I check that the user is logged in, all they need is a cookie with the correct username and hash. What is stopping a packet sniffer from making a duplicate version of this cookie and logging on to my website? Should I add more security by logging the user's IP and verifying it on every page load? This has its own problems though since some people's IP addresses can change within the same session. Also many computers behind one router would have the same external IP so an attacker could still get in if he/she was on the same network as the user.

A little confused about session_start() still. You say to make sure you do it on every page but then wouldn't that erase old session information? I thought once you started it, it would keep going until killed or browser window closed on the user's end. Right now since i'm only using index.php I dont have to worry much about this, but maybe this is why my logout.php wasn't working ... it tried to call destroy_session() but it was a standalone page that never started the session.

I've seen lots of ways to kill sessions. Some people do $_SESSION = array(), others just set the values that they want hidden = "" while session_destroy() is used on occasion as well. Then some people do all three and call it good. What are the pros and cons of these approaches? Right now i'm doing all of the above and its working great, but maybe this is big overkill?

Thanks for the help. I hate bothering you all with these questions but php.net and searches didn't answer these questions for me.
 
Back
Top