Wednesday, February 2, 2011

Prevention against SQL Injection

Hello Friends these days i have hacked many sites using SQL Injection . So i thought about writing how to prevent our web page against this attack. There are many methods to prevent SQLI but i am writing few of them.
Lets say our code is

<?php
$display = mysql_query(‘SELECT text FROM pages WHERE id=’ . $_GET['id']);
echo($display);
?>
This means that we are selecting the page content ‘text’ from ‘pages’ in the SQL database, and we are selecting the right page content with $_GET['id'] and $_GET['id'] is the thing in the url , for example
                       http://target.com/index.php?id=21
The above code is easily injectable and is enough for an attacker to enter your site without proper authentication.
But if we replace above code with the code written below then i guess we are 99.9% secure :P

<?php
$display = mysql_query(‘SELECT text FROM pages WHERE id=’ . mysql_real_escape_string($_GET['id']));
echo($display);
?>
In above code mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which prepends backslashes to the following characters: \x00, \n, \r, \, ', " . This function must always be used to make data safe before sending a query to MySQL.
Alternatively we can check $_GET['id'] for illegal and unwanted characters like this :


<?php
$inject = strrpos(strtolower($_GET['id']), “union”);
if ($inject === false){}else
{
die;
}
$inject = strrpos(strtolower($_GET['id']), “select”);
if ($inject === false){}else
{
die;
}
 $display = mysql_query(‘SELECT text FROM pages WHERE id=’ . $_GET['id']);
echo($display);
?>
Similarly we can block Information_ ,_schema, admin ,order , and other such keywords . :)
If we want we can use javascript to block and filter characters . This would be also useful to get rid of basic SQL string injection which is done at login forms.

I hope you like this post :=))

2 comments:

  1. hey now dats wat Oriental and other colleges (whose sites you have hacked) need to fight against Sql injection !!!

    ReplyDelete
  2. bhaiya where u hav gone i am waiting for yours new post

    ReplyDelete