Page 1 of 1

SQLi prevention is not working

Posted: Sat Oct 24, 2009 9:19 am
by synical21
Hello gurus i have come into a security problem i believe with preventing people from useing SQL injection on my site. When an ID is generatated i use a piece of code to clean the data to prevent things such as "ID='1". This has worked on all my other pages except one which is where i need your help, here is the code.

Code: Select all

 
<?php 
# connect to the database
mysql_connect('7-----1','-------','---------');
mysql_select_db('-----------');
 
session_start(); 
 
$my_id = trim (' ' . @$_GET['ID']) ; // will always return a result -- uses '
// sanitize/ clean data value: check for integer value, generate the corresponding string
if ('' < $my_id) { $my_id= (int) $my_id; // extract integer value -- uses '
                           if ( 0 == $my_id) { $my_id= ''; //handle as empty -- uses '
                                                       } else $my_id = "$my_id"; // uses "
                        }
if ('' == $my_id) { //handle the case where no ?ID= present
 
} else { //we have a ID=some integer >0
 
$result = mysql_query("SELECT * FROM `fulldata` WHERE job_id = '$my_id'")   // This will return one result
or die(mysql_error()); 
 
 
 
}
 
if(mysql_num_rows($result) == 1) { // Checks only 1 row was returned
 
$row = mysql_fetch_array($result);
 
?>
 
Now from what i understand from injection little kids will use
'
to get an exploitation and recieve an error message which is what happens when typed "jobinfo.php?ID='1"

the error message is:

Code: Select all

Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/fhlinux130/m/mysite.com/user/htdocs/jobinfo.php on line 29
I can understand why the error message is there but i thought my code would prevent it. Is this a real exploit or am i being over sensitive?

Re: SQLi prevention is not working

Posted: Sun Oct 25, 2009 4:34 am
by kaisellgren
No need for making it overly complex.

Code: Select all

$my_id = mysql_real_escape_string($my_id,$link);
$result = mysql_query("SELECT * FROM `fulldata` WHERE job_id = '$my_id'");
The error occurred because the query was never executed (the if -clause in line 15 succeeded).

Re: SQLi prevention is not working

Posted: Mon Oct 26, 2009 11:01 am
by Iainzor
If you want to be able to catch a non-numeric id, use the following:

Code: Select all

 
$my_id = isset($_GET['ID']) ? $_GET['ID'] : null;
 
if(!is_numeric($my_id)) {
    // No valid ID is provided
 
} else {
    $result = mysql_query("SELECT * FROM `fulldata` WHERE job_id = '$my_id'");
    // ...
}
 
This way, there is no need to escape the string as it's impossible to pass anything but a number to the ID variable.

Re: SQLi prevention is not working

Posted: Mon Oct 26, 2009 1:40 pm
by John Cartwright
It is always a good idea to pass your input through mysql_real_escape_string() .. you just never know :wink: