Page 1 of 1

A secure login script

Posted: Sat Jan 08, 2011 1:12 pm
by Alexancho
I am writing a login script using some ideas from here:
http://tinsology.net/2009/06/creating-a ... right-way/

So, i use hashing to protect password:

Code: Select all

$hash = hash('sha256', $salt . $hash); 
In login page if login is ok i set the session data for this user:

Code: Select all

session_regenerate_id (); //this is a security measure; 
    $_SESSION['username'] = $username;
For the other pages there is a check if a user is logged in:

Code: Select all

function isLoggedIn()
{
    if($_SESSION['username'])
        return true;
    return false;
}
session_start();
//if the user has not logged in
if(!isLoggedIn())
{
    header('Location: login.php');
    die();
}
//page content follows
In some other article i have seen a bit different recommendation.
In the login page if login is ok:

Code: Select all

session_regenerate_id (); //this is a security measure; 
    $_SESSION['username'] = $username;
    $_SESSION['password'] = $hash;
Where $hash is a hashed password (64bit), the same as stored in DB
And in all the other pages:

Code: Select all

if(!isLoggedIn())
{
    header('Location: login.php');
    die();
}
if(isset($_SESSION['username'])) 
  
 { 
	$username = $_SESSION['username']; 
 	$password = $_SESSION['password'];  
 	
 	$check = mysql_query("SELECT * FROM login_v2_users WHERE username = '$username'")or die(mysql_error()); 

 	while($info = mysql_fetch_array( $check )) 	 

 		{ 
			$query = "SELECT password, salt
	        FROM login_v2_users
	        WHERE username = '$username';";
			$result = mysql_query($query);
			if(mysql_num_rows($result) < 1) //no such user exists
			{
			    die('Wrong login. Please, log in.</a>'); 
			}
			$userData = mysql_fetch_array($result, MYSQL_ASSOC);
			
			if($password != $info['password']) //incorrect password
			{
			    die('Incorrect password. Please, log in.');  
			}
//login successful 

 	else 
etc
The question is which way is better and if this is a good enough for a secure login.

Re: A secure login script

Posted: Sat Jan 08, 2011 3:14 pm
by josh
That's a really insecure login. SQL injection, replay attacks, session ID fixation...

Re: A secure login script

Posted: Sat Jan 08, 2011 4:16 pm
by Alexancho
josh wrote:That's a really insecure login. SQL injection, replay attacks, session ID fixation...
Thank you. I mostly thought about unauthorized login.
For SQL injection i use some secure functions like mysql_real_escape_string(). It shouldn't be a problem.
About replay attacks and session ID fixation i know less.
Could you recommend me some protecting methods or useful articles?