In PHP, I know that mysql_real_escape in much safer than using addslashes. However, I could not find an example of a situation where addslashes would let an SQL Injection happen. Can anyone give some examples?
Thanks!
In PHP, I know that mysql_real_escape in much safer than using addslashes. However, I could not find an example of a situation where addslashes would let an SQL Injection happen. Can anyone give some examples?
Thanks!
Here is an example of SQL Injection that bypasses both addslashes() and magic_quotes_gpc:
<?php
mysql_connect("localhost","root","");
if(get_magic_quotes_gpc()){
$max=$_GET['max'];
}else{
$max=addslashes($_GET['max']);
}
print "select * from mysql.user where max_connections=".$max;
$q=mysql_query("select * from mysql.user where max_connections=".$max);
$a=mysql_fetch_array($q);
print_r($a);
?>
PoC Exploit:
http://localhost/escape_test.php?max=0+and+sleep(10)
The result is that it will force the database to sleep for 10 seconds, thus delaying the query and the load of the entire page.
There are 2 patches for this vulnerability.
The strongest patch is to force the value to be an integer. Integer values don't require quote marks in most languages.
$q=mysql_query("select * from mysql.user where max_connections=".intval($max));
This is another patch that is considered to be weaker. There are cases when this maybe vulnerable to sql injection due to language encoding.
$q=mysql_query("select * from mysql.user where max_connections='".$max."'"));
Quote marks are used to encase a variable, sql injection is about breaking out and executing code on the database. If you don't put quotes around a variable that the attacker controls, then the attacker doesn't have to "break out".
You should use parametrized queries with either PDO or ADODB. This is the most fool proof method that I know of.