SHAHEE MIRZA

Sooner or later you have to wake up.

SQL injection: attacks and defenses.

December 29, 2009Shahee MirzaSecurity20
Share

***Introduction:

This is awesome that attackers are using several methods to get into some restricted part of web applications. They are discovering new methods day by day.

But SQL injection is now widely spreading method to hack your web sites or web apps.

So here is the question, what is SQL injection?

## SQL injection is a code injection technique that helps attacker to get some vulnerable information from your database. Actually it happens on database layer. This vulnerability occurs on PHP and ASP scripts for mistake of its coder.

***Where and why this vulnerability happens:

## Your coder may forget or lazy to handle SQL query errors.

## Where malicious users can insert SQL syntax on form requests.

## Forget to filter SQL syntax.

## Can not determine type of SQL query string.

## This attack can be perform on anywhere of your application, even attacker don’t have to get a privileged account.

## Attack can be performing via cookie.

## Those dynamic pages which only pulls data from database directly.

## This vulnerability may be causes by your database server also.

***Types of SQL injection:

There are two types of SQL injection.

1.Injection into the variables that contain strings.

2.Injection into numeric variables.

Both are different than each other. I will describe about both and also how to avoid them.

*** 1. Injection into the variables that contain strings.

## Vulnerable code:

OK, just imagine that you wrote an application that have a page that fetches member’s credits according to his login name. The username will gone one page to another via URL, actually method of $_ GET [‘variable’];


$cred = $_GET['name'];

$result = mysql_query("SELECT credit FROM user WHERE username='$cred'");

This script has SQL injection vulnerability. An attacker can abuse it, just putting a SQL query beside the username in URL.

‘ UNION SELECT password FROM admin WHERE id=1

This will pull password of an admin user who has id number 1 as an example.

## Solution:

To avoid this type of attack is very simple. So many times it has been described by so many security experts. You have to use a function mysql_real_escape_string().What does it do? mysql_real_escape_string() function adds “\”  to following characters:


NULL, \ x00, \ n, \ r, \, ', " and \ X1A

So, look out that vulnerable code with mysql_real_escape_string() .


//

$cred = mysql_real_escape_string( $_GET['name']);

$result = mysql_query("SELECT credit FROM user WHERE username='$cred'");

This page is completely secure now.

## Attack again:

Now an attacker will attack on it like before.

‘ UNION SELECT password FROM admin WHERE id=1

But after using  mysql_real_escape_string() funtion, this query looks like this.

\’ UNION SELECT password FROM admin WHERE  id=1

There is “\” character just added because of mysql_real_escape_string().

Somebody will advice you to use addslashes() function. But this function has some limitations.

##Please read these topics from PHP manual:

http://www.php.net/manual/en/function.addslashes.php

and

http://www.php.net/manual/en/mysqli.real-escape-string.php

and also.

http://www.php.net/manual/en/function.pg-escape-string.php

*** 2. Injection into numeric variables.

These types of SQL attacks are less know than first one. And not so well described by security experts. But it also comes with same disaster on your web applications.

## Vulnerable code:

Now time to describe this attack. Imagine again, you wrote a page that will display user’s credit according to his user id. The user id will gone one page to another via form posting, actually method of $_ POST [‘variable’];


$id = $_POST['id'];

$result = mysql_query("SELECT credit FROM user WHERE id=$id");

On this situation mysql_real_escape_string() will not protect you from SQL injection attack. Because now the $id variable is not quoted. This variable is containing numerical value. Now an attacker will use this type of SQL query.

2 UNION SELECT password FROM admin WHERE id=1

So, how could you protect web application from this attack? There are two things you can do.

1. You can change content to number, so that your variable will hold only numerical content.

2. You can check if the content is numerical then it may proceed to make a query.

## Solution:

To avoid this type of attack you can use these functions.

A. intval() function.

B. is_numeric() function.

Here I am describing about the benefit of intval() function.


//

//

$var='7ack3r'; //variable contain alphanumerical content

$var2=intval($var); // filtered by intval()

print $var2; // this will print only 7

Now you can change your code as like below.


$id = intval($_POST['id']);

$result = mysql_query("SELECT credit FROM user WHERE id=$id");

Yap, you have done your job. This will secure your web applications more than enough.

Now, I am going to describe the function name is_numeric().This function will check, is your variable contains a numerical content?


$id = $_POST['id'];

if (is_numeric($id))

{

$result = mysql_query("SELECT credit FROM user WHERE id=$id");

}

else

{

log_the_attack(); //this function will log all the information eg: ip, browser, time, date etc

echo "Ha ha ha, trying do something with me dude? You are logged honey";

}

function log_the_attack()

{

// bla bla bla

}

Here a question will arise that “What can I do now, what will use…. Intval() or is_numeric() ?”

Answer will be “Its up to you, intval() is easy and saves the coding time but is_numeric() may kills some time. But this will help you to keep all the attack logs”.

Please read details from here:

1. http://www.php.net/manual/en/function.is-numeric.php

2. http://www.php.net/manual/en/function.intval.php

*** Conclusions:

Finally I am going finish this article. If you follow these steps, your application will be secure.

## Verify data types of all non-string user inputs.

## Escape all string inputs.

## Keep track of security violation attempts.

## Limit SQL user rights.

## Take database backups.

## Double check your codes.

## Always keep updated your database server.

###################

I AM CONFESSING THAT, I AM BAD IN ENGLISH.

IF I WROTE ANY WRONG INFORMATION IN MY ARTICLE, PLEASE INFORM ME .

###################

You can follow any responses to this entry through the RSS feed. You can leave a response, or trackback from your own site.

Tagged , , , ,

20 Comments

  1. maSnunDecember 30, 2009 at 2:57 pm

    Nice post! SQL Injection is perhaps one of the most widely discussed topics in the php – asp world! It’s a total bliss that we don’t have to worry much about this in Python.

    But I do believe most programmers even the novice php coders are aware of these basic attacks. But there are even nastier mysql attacks available out there in the wild. I somewhere read an article describing an attack that involves using hexadecimal chars to pass through the sanitation related php functions.

    From my point of view, security is all about constant vigilance and keeping yourself always up to date with the latest technologies. Malicious codes are like dark magic, they transform every now and then. You have to be prepared for everything :)

    Thanks again for the post! Nice to see you starting your own dot com blog :) Welcome to the club!

    Happy blogging!

  2. M. R. SOHELDecember 30, 2009 at 3:03 pm

    As i know nothing about SQL (heard about SQL injection),I cant figure out anything about your post but I like to comment on.

  3. Shahee MirzaDecember 30, 2009 at 3:32 pmAuthor

    I somewhere read an article describing an attack that involves using hexadecimal chars.

    Thanks a lot man :) ,

    yap i have made a video tutorial on hexadecimal chars in sqli ( October 2009 ). but it will publish within few days. happy sqli :)

  4. giferDecember 30, 2009 at 10:59 pm

    nice post bro…onek ojana jinish janlam..thanks

  5. Shahee MirzaDecember 31, 2009 at 12:59 amAuthor

    gifer vai ,thank u, thank u, ken je shorom den???????

  6. LeninDecember 31, 2009 at 1:12 am

    Nice writeup. Though its well known to people what gumbler worm does. How most of our govt websites got hacked/cracked. But I still find programmers who didn’t even hear about the vulnerabilities.
    Some even spend time configuring some CMS over the years.

    Programmers must be updated by following others blogs, tweets. And they should keep an eye on the security researches going on. I always believe this murphy’s law: “What may go wrong, it will”. Its easier to break than to build. And its always true that prevention is better than cure.

  7. r1n3mJanuary 13, 2010 at 4:04 am

    vaia php opensource deke mayb hack korte pare naki?cz source toh alrdy peye jai :!

  8. dublin web designJanuary 25, 2010 at 5:25 am

    Good article…I will use some of these interesting principles myself…more great info please…

  9. Shahee MirzaJanuary 25, 2010 at 11:41 amAuthor

    thank u….

  10. flackmanMarch 10, 2010 at 7:29 pm

    Not bad article, but I really miss that you didn’t express your opinion, but ok you just have different approach

  11. kapselMarch 13, 2010 at 3:09 pm

    I read a article under the same title some time ago, but this articles quality is much, much better. How you do this?

  12. AhmadSayedApril 3, 2010 at 3:25 pm

    good job.

  13. SteveCApril 8, 2010 at 4:45 am

    One of my friends already told me about this place and I do not regret that I found this article.

  14. Ila HananApril 30, 2010 at 6:09 am

    This is a outstanding summary, I located your blog site checking bing for a related topic and arrived to this. I couldnt get to much other information on this piece of writing, so it was awesome to locate this one. I probably will end up being returning to look at some other posts that you have another time.

  15. Rueben EildersMay 15, 2010 at 9:53 pm

    Thanks I really needed this.

  16. Fumiko McgheheyMay 19, 2010 at 11:25 am

    Good site, where did you come up with the info in this piece of content? I’m happy I found it though, ill be checking back soon to see what other articles you have.

  17. BruceMay 21, 2010 at 10:47 pm

    thank u….

  18. locksmithMay 28, 2010 at 7:10 am

    Nice to be visiting your blog again, it has been months for me. Well this article that i’ve been waited for so long. I need this article to complete my assignment in the college, and it has same topic with your article. Thanks, great share.

  19. imran_csJuly 27, 2010 at 3:14 am

    Shahee Mirza bro, plz ekta video tutorial banan / amader bujhte aro sohoj hoto ….. apnar post all time e kora hoy really________

  20. Maruf AlamAugust 1, 2011 at 12:17 am

    Nice Tutorial. Carry on dude

Leave a reply

Your email address will not be published. Required fields are marked *

*