views:

1503

answers:

2

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!

+13  A: 

Well, here's the article you want.

chaos
How about magic quotes? I have seen site who just puts $POST['password'] into the SQL query, and it does not fail for them. Can you explain why does it work?
elcuco
Magic quotes are a whole 'nother topic; see http://stackoverflow.com/questions/220437/magic-quotes-in-php. Presumably the example you give 'works' because magic quotes are on. Among the many reasons not to use magic quotes is that magic quotes uses the same logic as addslashes(), so has the same vulnerability described here.
chaos
+4  A: 

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.

Rook