Search code examples
phpmysqlsql-injection

How to prevent MySQL sleep injections?


Recently one hacker tried to slow my website using sleep injection. Although we are using precautions like mysql_real_escape_string() to cover most of vulnerable inputs. We are passing id of the product through query string and it makes the command as:

$id = mysql_real_escape_string($_REQUEST['id']);
$qry = "Select * from products where id = ".$id;

but hacker tried to provide input as

?id=3 and sleep(4)

and query becomes

Select * from products where id = 3 and sleep(4);

Although there are some possible solutions like

  1. Check if the product id is numeric or not
  2. Remove word sleep from input using some customized function

Is there any other method to stop this? What is the best method to prevent sleep injections?


Solution

  • You are not escaping correctly. mysql_real_escape_string is for escaping SQL string syntax correctly, but you are simply embedding the value as bare value, not as SQL string. You need:

    $qry = "SELECT * FROM products WHERE id = '$id'";
    

    Note the quotes around the id in the query.

    If the id is numeric though, casting to a number would be more sensible:

    $id = (int)$_GET['id'];