Thursday, 29 December 2011

How to secure yourself from SQL injection attack


After long long tutorials on basic and advance SQLi, I think about securing ourselves from this harmful attack called SQL Injection Attack.
There is a number of things you can do… I will show you a few here…

Lets say this is your code:

$result = mysql_query(‘SELECT text FROM pages WHERE id=’ . $_GET['id']);
echo($result);

?>
This means that you are selecting the page content which is ‘text’ from ‘pages’ in the SQL database, and you are sorting out the right page content with $_GET['id'] and $_GET['id'] is the thing in the url… Example;
http://google.com/index.php?id=123
This code is easily injectable… But if you do this:

$result = mysql_query(‘SELECT text FROM pages WHERE id=’ . mysql_real_escape_string($_GET['id']));
echo($result);

?>
You are 100% secure
Alternative two
This one is not as good as the first one… But still works
Again we say this is your php code:

$result = mysql_query(‘SELECT text FROM pages WHERE id=’ . $_GET['id']);
echo($result);

?>
Again this is very simple to inject… But if you check $_GET['id'] for “illegal” characters! Like this:

$pos = strrpos(strtolower($_GET['id']), “union”);
if ($pos === false){}else
{
die;
}

$pos = strrpos(strtolower($_GET['id']), “select”);
if ($pos === false){}else
{
die;
}

$pos = strrpos(strtolower($_GET['id']), “information_”);
if ($pos === false){}else
{
die;
}

$result = mysql_query(‘SELECT text FROM pages WHERE id=’ . $_GET['id']);
echo($result);

?>

0 comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...