0

Example:

Database Connect and Filter

//Initialize MySQLi connection
$db = new mysqli($_CONFIG['mysql']['hostname'], $_CONFIG['mysql']['username'], $_CONFIG['mysql']['password'], $_CONFIG['mysql']['database']);
if ($db->connect_errno) {
    die("MySQLi error: ".$db->connect_error);
}

//filter injections
function filter($var)
{
    global $db;
    return $db->real_escape_string(stripslashes(htmlspecialchars($var)));
}

Set cookie after a successful login, check cookie and re-update each time

if(login) {
// after successful login
$cookiehash = md5(sha1($_SESSION['user_id'] . $recentIP));
$db->query('UPDATE users SET loginHash = "'.filter($cookiehash).'" WHERE id = '.filter($_SESSION['user_id']).'') or die(mysqli_error($db));
setcookie("customCookie",$cookiehash,time()+3600*24*365,'/','.'.$_SERVER['HTTP_HOST'].'');

}


// if the cookie is set, update expiration and set session id
    CheckCookieLogin() {
            global $db;
            if (!empty($_COOKIE['customCookie'])) {
            $cookie = $_COOKIE['customCookie']; 
            $query = $db->query('SELECT * FROM users WHERE loginHash = "'.filter($cookie).'"');

            if($query->num_rows > 0) {
            $_SESSION['user_id'] = 1;
            // reset expiry date
            setcookie("customCookie",$cookie,time()+3600*24*365,'/','.'.$_SERVER['HTTP_HOST'].'');
            }

        }
    }

Would this still be vulnerable to any sort of injection attack?

Koala
  • 5,253
  • 4
  • 25
  • 34
  • possible duplicate of [How can I prevent SQL-injection in PHP?](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – Clément Malet Sep 01 '14 at 06:16

1 Answers1

1

The cookie is stored on the client's computer, and thus vurnerable to attack. So called 'Cookie Poisoning attacks'. So treat the content with care. This is what you seem to do with your filter() routine.

It can still be improved however. What if you could check whether the cookie has been modified, without having to access your database? This might seem more difficult than it is.

A simple method is adding some sort of checksum to the content of the cookie, something you can check but is not obvious to the hacker. The hacker would first have to figure out what you're doing, before he, or she, can even start to change the data that enters your SQL statement. It is the difference between accepting any content from the cookie and put it in an SQL statement, or only accepting content which you can verify not to have been modified.

KIKO Software
  • 15,283
  • 3
  • 18
  • 33