TalkPHP
 
 
Account Login
Latest Articles
» The basic usage of PHPTAL, a XML/XHTML template library for PHP
» Vulnerable methods and the areas they are commonly trusted in.
» Simple way to protect a form from bot
» The Basics On: How Session Stealing Works
» How to keep your forms from double posting data
IRC Channel
IRC Speech Bubble Join the friendly bunch on IRC...
(#TalkPHP on Freenode)

...Also available via a web interface.

See this thread for information on the TalkPHP Free Hugs Initiative™. Subject to availability.
Associates
Associates
CSS Tutorials
Reply
 
LinkBack Thread Tools Search this Thread Display Modes
Old 09-20-2007, 09:04 PM   #1 (permalink)
The Frequenter
Prolific Welcomer Upcoming Programmer 
 
Join Date: Sep 2007
Posts: 360
Thanks: 24
Haris is on a distinguished road
Default Authentication class

PHP Code:
<?php

    
/* 
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

    Title : Authentication class for users login
    Author : Muhammad Haris
    URL : http://www.mharis.net
    CONTACT: isharis@gmail.com

    Description : Class used for authentication of 
    the users login on secure pages.

    Created : 20th September 2007
    Modified: 21th September 2007

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
    */
    
    
class Auth {
        
        
/*
         * Summary:     Starts session and sets default value
         */
        
        
public function __construct(){
            
session_start();
            
$_SESSION['logged'] = false;
            
$_SESSION['username'] = ''
            
$_SESSION['rank'] = '';
        }
        
        
/*
         * Summary:     Authenticates a user and registers its sessions
         * Parameters:  Username | Passwords
         * Return:      Returns true if session is user is succesfully
                       authenticated else returns false
        *              
         */
        
        
public function authenticate($szUser$szPassword){
            
$szSQL sprintf("SELECT *
                     FROM
                     users
                     WHERE
                     user = '%s' LIMIT 0,1"
$szUser);
            
$aResult mysql_query($szSQL) or die(mysql_error());
            while(
$row mysql_fetch_array($aResult)){
                
$dbPass $row['pass'];
                
$dbSalt $row['salt'];
                
$dbRank $row['rank'];
            }
            
$szPassword md5($dbSalt.$szPassword);
            if(
$szPassword == $dbPass){
                
session_regenerate_id();
                
$_SESSION['logged'] = true;
                
$_SESSION['username'] = $szUser;
                
$_SESSION['rank'] = $dbRank;
                return 
true;
            }
            else{
                
$_SESSION['logged'] = false;
                
$_SESSION['username'] = '';
                
$_SESSION['rank'] = '';
                return 
false;
            }
        }

        
/*
         * Summary:     Checks if the user is logged in or not.
         * Return:      Returns true if session is user is logged
                       in else returns false
        *              
         */
        
        
public function check(){
            if(
$_SESSION['logged'] == true){
                return 
true;
            }
            else {
                return 
false;
            }
        }
        
    }
    
?>
I've finally made my own authentication class. I want to know if my class is secure enough. I know it's secure from sql injections and session hijacking.

What more?
Haris is offline  
Reply With Quote
Old 09-20-2007, 10:31 PM   #2 (permalink)
Moderateur
RegEx Guru PHP Guru Top Contributor Advanced Programmer 
 
Salathe's Avatar
 
Join Date: Apr 2007
Posts: 1,393
Thanks: 5
Salathe is on a distinguished road
Default

How do you protect against SQL injections? Your method for checking a valid password is a bit convoluted and personally I'd rather let MySQL handle checking the password than go the way of bring back all of the user data and checking it in PHP.
Salathe is offline  
Reply With Quote
Old 09-20-2007, 11:38 PM   #3 (permalink)
The Frequenter
Prolific Welcomer Upcoming Programmer 
 
Join Date: Sep 2007
Posts: 360
Thanks: 24
Haris is on a distinguished road
Default

Quote:
Originally Posted by Salathe View Post
How do you protect against SQL injections? Your method for checking a valid password is a bit convoluted and personally I'd rather let MySQL handle checking the password than go the way of bring back all of the user data and checking it in PHP.
PHP Code:
            $szSQL sprintf("SELECT *
                     FROM
                     users
                     WHERE
                     user = '%s' LIMIT 0,1"
mysql_escape_string($szUser)); 
It uses sprintf to make sure that it is a string and also escapes the string. :)

I'm yet to learn more about MySQL.
Haris is offline  
Reply With Quote
Old 09-20-2007, 11:51 PM   #4 (permalink)
Moderateur
RegEx Guru PHP Guru Top Contributor Advanced Programmer 
 
Salathe's Avatar
 
Join Date: Apr 2007
Posts: 1,393
Thanks: 5
Salathe is on a distinguished road
Default

I only asked because you aren't escaping anything in the code in your first post, in the authenticate method.

As for doing things in SQL, you could try something like the following (note, just typed off of the top of my head -- may contain errors).

PHP Code:
public function authenticate($szUser$szPassword){
    
// Only the 'rank' column actually needs to be returned
    // so no "SELECT *" here
    
$szSQL sprintf("SELECT rank
                      FROM users
                       WHERE 
                           pass = MD5(CONCAT(salt, '%s'))
                           AND user = '%s' 
                       LIMIT 0,1"
,
                       
mysql_real_escape_string($szPassword), 
                       
mysql_real_escape_string($szUser));

    
$aResult mysql_query($szSQL) or die(mysql_error());

    
// If no rows are returned, our password didn't match
    // for the supplied user name.
    
if (mysql_num_rows($aResult) == 1)
    {
        
$aRow mysql_fetch_assoc($aResult);
        
        
session_regenerate_id();
        
$_SESSION['logged']   = true;
        
$_SESSION['username'] = $szUser;
        
$_SESSION['rank']     = $aRow['rank'];
        return 
true;
    }
    else
    {
        
$_SESSION['logged']   = false;
        
$_SESSION['username'] = '';
        
$_SESSION['rank']     = '';
        return 
false;
    }
    

Salathe is offline  
Reply With Quote
Old 09-21-2007, 12:28 AM   #5 (permalink)
The Frequenter
Prolific Welcomer Upcoming Programmer 
 
Join Date: Sep 2007
Posts: 360
Thanks: 24
Haris is on a distinguished road
Default

Hmm, new and improved class.

PHP Code:

<?php

    
/* 
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

    Title : Authentication class for users login
    Author : Muhammad Haris
    URL : http://www.mharis.net
    CONTACT: isharis@gmail.com

    Description : Class used for authentication of 
    the users login on secure pages.

    Created : 20th September 2007
    Modified: 21th September 2007

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
    */
    
    
class Auth {
        
        
/*
         * Summary:     Starts session and sets default value
         */
        
        
public function __construct(){
            
session_start();
            if(!isset(
$_SESSION['logged'])){
                
$_SESSION['logged'] = false;
                
$_SESSION['username'] = '';
                
$_SESSION['rank'] = '';
            }
        }
        
        
/*
         * Summary:     Authenticates a user and registers its sessions
         * Parameters:  Username | Passwords
         * Return:      Returns true if session is user is succesfully
                       authenticated else returns false
        *              
         */
        
        
public function authenticate($szUser$szPassword){
            
$szSQL sprintf("SELECT rank
                               FROM users
                                WHERE 
                             pass = MD5(CONCAT(salt, '%s'))
                             AND user = '%s' 
                                LIMIT 0,1"
,
                             
mysql_real_escape_string($szPassword), 
                             
mysql_real_escape_string($szUser)); 
                             
            
$aResult mysql_query($szSQL) or die(mysql_error());
                             
            if (
mysql_num_rows($aResult) == 1){
                
$aRow mysql_fetch_assoc($aResult); 
                
session_regenerate_id();
                
$_SESSION['logged'] = true;
                
$_SESSION['username'] = $szUser;
                
$_SESSION['rank'] = $aRow['rank'];
                return 
true;
            }
            else {
                
session_destroy(); // Destroies session if failed to authenticate
                
return false;
            }
        }

        
/*
         * Summary:     Checks if the user is logged in or not.
         * Return:      Returns true if session is user is logged
                       in else returns false
        *              
         */
        
        
public function check(){
            if(
$_SESSION['logged'] != true){
                return 
false;
            }
                return 
true;
        }
        
        
/*
         * Summary:     Checks if the the logged in user is admin or
        *              a normal user
         * Return:      Returns true user is a admin else returns false
        *              
         */
        
        
public function admin_auth(){
            if(
$_SESSION['rank'] != 1){
                return 
false;
            }
            return 
true;
        }
        
    }
    
?>
Haris is offline  
Reply With Quote
Old 09-21-2007, 09:01 AM   #6 (permalink)
The Prestige
Upcoming Programmer Inquisitive 
 
Tanax's Avatar
 
Join Date: Sep 2007
Location: Sweden, Stockholm
Posts: 1,080
Thanks: 115
Tanax is on a distinguished road
Default

What does session_regenerate_id do?

And btw, to have a page that only logged in users can see, I would have to do first a login page, and then the authentification.
And then:
PHP Code:
if($auth->check()) {
logged in page...
} else {
echo 
'you have to login!';

Tanax is offline  
Reply With Quote
Old 09-21-2007, 10:13 AM   #7 (permalink)
Moderateur
RegEx Guru PHP Guru Top Contributor Advanced Programmer 
 
Salathe's Avatar
 
Join Date: Apr 2007
Posts: 1,393
Thanks: 5
Salathe is on a distinguished road
Default

The session_regenerate_id function replaces the current session id with a new one, whilst keeping all of the session data intact. It is that part which is helping to prevent the problem of "session hijacking".

Your auth (authorisation and authentication combined) code, Tanax, will work just fine. Personally I'd go for the negative check with a redirect to a login page.
PHP Code:
if ( ! $auth->check())
{
    
header('Location: full_url_to_login_page');
    exit;
}


... 
rest of page's code ... 
Salathe is offline  
Reply With Quote
Old 09-21-2007, 10:21 AM   #8 (permalink)
The Prestige
Upcoming Programmer Inquisitive 
 
Tanax's Avatar
 
Join Date: Sep 2007
Location: Sweden, Stockholm
Posts: 1,080
Thanks: 115
Tanax is on a distinguished road
Default

Ahh, so basicly it's just changing the name of the session?

Awesome :D Thanks
Tanax is offline  
Reply With Quote
Old 09-21-2007, 02:02 PM   #9 (permalink)
The Frequenter
Prolific Welcomer Upcoming Programmer 
 
Join Date: Sep 2007
Posts: 360
Thanks: 24
Haris is on a distinguished road
Default

Quote:
Originally Posted by Tanax View Post
Ahh, so basicly it's just changing the name of the session?

Awesome :D Thanks
You missed a very important WildHoney's article.

Understanding the Life of a Session
Haris is offline  
Reply With Quote
Old 09-21-2007, 02:39 PM   #10 (permalink)
La Vida es Sueño
Advanced Programmer Top Contributor 
 
Wildhoney's Avatar
 
Join Date: Sep 2007
Location: Oldham
Posts: 2,280
Thanks: 90
Wildhoney is on a distinguished road
Default

Quote:
Originally Posted by Tanax View Post
Ahh, so basicly it's just changing the name of the session?

Awesome :D Thanks
The ID of the session. The session name will also stay the same as the name stored in session_name unless you explicitly alter it. Prevents session fixation as well. I uploaded a document on session fixation on TalkPHP somewhere. Use the search feature and you'll be able to find it, no problems.
__________________
The man who comes back through the Door in the Wall will never be quite the same as the man who went out.
Send a message via AIM to Wildhoney Send a message via MSN to Wildhoney Send a message via Yahoo to Wildhoney
Wildhoney is offline  
Reply With Quote
Old 09-21-2007, 07:42 PM   #11 (permalink)
The Prestige
Upcoming Programmer Inquisitive 
 
Tanax's Avatar
 
Join Date: Sep 2007
Location: Sweden, Stockholm
Posts: 1,080
Thanks: 115
Tanax is on a distinguished road
Default

I got it now! I read your article, and though it didn't mention session regenerate... but I found this: http://www.talkphp.com/showthread.php?p=1813#post1813

It was the thing I looked for, great.. thanks! :)
Tanax is offline  
Reply With Quote
Reply



Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


All times are GMT. The time now is 04:02 AM.

 
     

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0
Inactive Reminders By Icora Web Design