Monday, April 23, 2012

SQL injection that gets around mysql_real_escape_string()


Is there an SQL injection possibility even when using mysql_real_escape_string() function?



Consider this sample situation. SQL is constructed in PHP like this:




$login = mysql_real_escape_string(GetFromPost('login'));
$password = mysql_real_escape_string(GetFromPost('password'));

$sql = "SELECT * FROM table WHERE login='$login' AND password='$password'";



I have heard numerous people say to me that a code like that is still dangerous and possible to hack even with mysql_real_escape_string() function used. But I cannot think of any possible exploit?



Classic injections like this:




aaa' OR 1=1 --



do not work.



Do you know of any possible injection that would get through the PHP code above?


Source: Tips4all

4 comments:

  1. Concider the following query:

    $iId = mysql_real_escape_string("1; DROP table");
    $sSql = "SELECT * FROM table WHERE id = $iId";


    mysql_real_escape_string will not protect you against this.
    The fact that you use single quotes '' around your variables inside your query is what protects you against this. The following is also an option:

    $iId = (int)mysql_real_escape_string("1; DROP table");
    $sSql = "SELECT * FROM table WHERE id = $iId";

    ReplyDelete
  2. Well, there's nothing really that can pass through that, other than % wildcard. It could be dangerous if you were using LIKE statement as attacker could put just % as login if you don't filter that out, and would have to just bruteforce a password of any of your users.
    People often suggest using prepared statements to make it 100% safe, as data can't interfere with the query itself that way.
    But for such simple queries it probably would be more efficient to do something like $login = preg_replace('/[^a-zA-Z0-9_]/', '', $login);

    ReplyDelete
  3. Consider using PDO prepared statements for your queries. This keeps you safe from SQL injections:

    http://www.php.net/manual/en/pdo.prepared-statements.php

    ReplyDelete
  4. No.

    Perhaps you shouldn't listen to those numerous people :)

    However you are storing a plain password in your database which is a no-go. Please use a hash algorithm (with a salt ofcourse). This has nothing to do with security, only with the privacy of your users.

    ReplyDelete