Monday, 16 September 2013

Complete Reference Guide to SQLi-How Attack Happens and How to Prevent SQL Injection

What is SQL Injection ?

[Image: e1Bp9.jpg]

SQL injection has evolved from two major words - SQL & Injection.

SQL is the Structured Query Language that stores the data .
Injection is form of an attack to inject or insert any malicious or non-malicious data without authorisation.

Now, Why it's so famous, Well, There used to be lot many application and Website which were and still are vulnerable to this attack.
It has been ranked no.1 attacking method for websites since 2010 by OWASP. Google Search Results for: OWASP

Now, If you Are Web Developer than, this is must Read Page for you, this will tell you what stuff makes it vulnerable, and how can you fix them :)

What makes Websites or Web-Application Vulnerable to SQL Injection

First thing first, Any non-sanitised Input taken by user or to be applied from Client side to the Database makes it Vulnerable.
What is meaning of sanitised, In Simple term it means, To clean the Undesired inputs, Now to make it more easy, Read Below :--

Every Developer Should assume there may be 3 types of users or visitors who will be visiting his website :-

1. Illiterate User or Alien.
2. Literate User.
3. Hacker.

So, Whenever there is anything that is to be asked from their part [i.e, user or client side part ] => Never Ever Trust them.

Here are Reasons :- 

1. Illiterate User or Alien :- Such user has no idea what you are asking and if you ask them, whats your username, please use
keyboard to input , There are possibility, that they will type something like below in code :-

Now, you were expecting something only alphabets or at max some spaces. But than you notice, your database throwing some error.

Ah! you got some Problem for your Database ?

Yes, But Not Nightmare still, Right ?
Keep Reading Below , you will see them in 3rd type of userType.

2. Literate User :- These users are already aware of what to type, so when you ask username, they will give their good name like mine :-

Any problem from Them for Database ?
NO! Not at all, Actually for them only you made your website, so Thank to them.

Below comes your night killing Creatures - Called Hackers :)

3. Hackers :- Hackers is basically Mixture of Illiterate and Very Highly Literate users for your Website, Now if you think How is that ?
They behave like Illiterate but in very High Literate Manner - Note them Down

When you ask your Username to them, they will feed something like :-
F_CK_U" or "1" = "1

Now, what is the problem with that, Right ? :-

See, You run below query in your database to see, if given user is Available.
PHP Code:
SELECT usernamepassword FROM `member_tablewhere `username`=" INPUT_BY_USER_WILL_BE_HERE " and
password`=" INPUT_BY_USER_HERE " 

So, Focus on "INPUT_BY_USER_HERE" Including Double Quote.

When hacker said his username is 
F_CK_U" or "1" = "1

than your Database will run Below Query :-
SELECT username, password FROM `member_table` where `username`=" F_CK_U" or "1" = "1 " and `password`="anything"
In the Above Statement , 

`username`=" F_CK_U" will be considered as 1 part i.e, F_CK_U will be considered as username 
and If that username is not Available than hacker also said in typing "1" = "1 , now this was crucial.

To the Database, it means, Either Username is F_CK_U or 1 = 1 [ 1 is equal to 1] , And we know, 1 is always equal to 1.

So, if that username doesnot exist, which in 99.99% cases is than sql will go to or 1 = 1 part which is always true. Don't ask me Why ?
[1 is always equal to 1  ]

SO, Query will be run as Succesful query, Now, Once query will be considered as Successful Query, He or she shall be followed to the page, where you take them on Successful Query.

If you think how that was successful query than read here 
That query means, Either user is F_CK_U , and if that user is not F_CK_U than take "1" = "1" , so in database, Application sees that F_CK_U is not stored
as any username but i know 1=1 so, when i know 1=1 than that means, there is nothing wrong.

If i ask, Tell me your siblings name or your name. There would be 2 scenario :-

1. Either you have Siblings and their name is A, B, C and your name is D
2. You have no siblings and your name is D.

So, You reply would be for 1st scenario => A, B, C
And if you have no sibling than you reply will be D.

Right ? => that means there would be something positive reply without any error, SAME Happens when Hacker say username is F_CK_U or 1=1 :) Hope this was clear.

Well, that was for login part, If you think, How the heck in this earth it works for URL type :-
Than Read them Below :-

Whenever you see any URL like :-
or any similar URL , few more below [They are just example ]:-

than tidfidid values are fetched [taken] from Database, So Again 
there has to be some Database Query, See how it may be :-
PHP Code:
SELECT titlecontentdate from `postwhere `id`="1"orSELECT titlecontentdate from `postwhere `postID`="1" 

Now, Again HOW hacker will Modify the URL See this :-

Now, Once he does like that and press enter, Below query will be Run :-
SELECT title, content, date from `post` where `id`=" 1" "
SELECT title, content, date from `post` where `postID`=' 1' '

Please note the Single quote [ ' ] and Double quote [ " ] in the code section, they are very crucial to understand the SQL injection scenario.

Did, you see the 3 quotes for id or postID , Now, that is an error.. Because in SQL programming we put the 
value inside Quotes any extra special-character will throw error.

So, How You can Attack Such SQL Injectable Scenario

[Image: simple-sql-injection-flow.png]

For that, I will ask you to go these Links posted by few members here, and they are pretty clear, Here, I will only make you understand whats happening there :-
1. and you will get many in those tutorial, you you mus be asking what are these than :-

2. -- 
3. union all
4. information_schema, etc...

HERE is some sample code I am pasting them :-
1. order by 9--
2. union all select
3. union all select 1,2,3,4 from users--
4. union all select 1,user, pass, 4 from users--
5. union all select 1, concat(user,0x3a, pass), 3, 4 from users--
6. union all select user from users limit 0,1--
7. union all select pass from users where user="admin"--
8. union all select load_file('/etc/passwd')--

There is also one very dangerous function called "load_file" for mysql which if available can open system file via SQL commands, see no.8 URL in above code.

than trust me, I would recommend to atleast understand some function of database from here =>

They will add great advantage to understand, If you know such language which are coke easy, than you already know most of thing. Still after reading those 
tutorial, you are not sure, or could not understand what was happening, than ask there refering to your step, where you could not understand what was 
happening, i will be there to reply you :) and help you.

Now, When SQL Injection Attack was Found, Being a Security Focused Developer or Being Hacker to notify Vendor about the vulnerability, What Suggestion 
or Code would you Recommend to Prevent them, for that read below :-

[Image: sql-injection-ig.jpg]

How to Prevent SQL Injection

Well, to Prevent SQL injection , We need to think only 1 thing, i.e, How to not allow those input by user , For that there are 2 ways :-

1. Untrustable & Complex > Javascript function to eliminate such input. [ You must have thought, Why do i even need to mention, if 
this is no trustable, IT's because some developer are still using it, without knowing it is untrustable.

Simple noscript addon can will bypass all javascript function and all code will start getting executed again, Therefore SERVER-Side Validation is MUST.

How in SERVER side ?

I will show the code in PHP, as this is what i master in.

For PHP < 4.3
Simple Check if magic_quotes_gpc is enabled or not, if it is not enabled than simple use :-
PHP Code:
addslash($input)  // function name is addslash 
Google Search Results for: addslash function in PHP

But, trust me this is also not trustable For that read , this => how even this can be bypassed :-

And I recommend to Update PHP Immediately if you in case use PHP < 4.3

If you have PHP > 4.3 than check whether " mysql_real_escape_string " function exist, in almost 99.999999% cases, it will exist. :)

And if that exist, than here is your code :-

PHP Code:
SELECT userpassword from `memberwhere `username`='".mysql_real_escape_string('INPUT_BY_USER_HERE')."' and

Well, for more security point of view, you should also use salt, but for now, in simple form md5 is OK.

What these functions are doing and that makes SQL injection go useless. Well, these functions actually add "backslash" to all special characters and 
interpret them as simple character and SQL injection inputs it as normal as other alphabets and does not let any harmful execution.
For example , the code in actual will get passed like :-
PHP Code:
SELECT usernamepassword from `memberwhere `username`=" 1\" or \"1\" = \"1" and

What "\" means is, It says , " or this ' are normal character like other input and do not consider as any quote.

Perfect SQLInjection less function

function cleanQuery($string)
  if(get_magic_quotes_gpc())  // prevents duplicate backslashes
    $string = stripslashes($string);
  if (phpversion() >= '4.3.0')
    $string = mysql_real_escape_string($string);
    $string = mysql_escape_string($string);
  return $string;

While using =>
$query = "SELECT * from user where username='".cleanQuery($_POST['user'])."' and pass='".cleanQuery($_POST['pass'])."'"

you may also use simple custom function using str_replace function, which i dont recommend still, Always Follow KISS principle while coding ~ Keep it Simple Stupid.

Anyways how str_replace function could do here is SAMPLE :-
Note: it's just SAMPLE and is not completly reliable for production use :-

PHP Code:
function validate_input($input)
$input str_replace("'""\'"$input);$input str_replace('"''\"'$input);$input str_replace("-""\-"$input);$input str_replace("\\""\\\", $input);
.... // and other special character in similar passion.

You cannot even trust "mysql_real_escape_string" as this can be exploited too in 1 scenario =>

And also now PHP prefers to use either mysqli or PDO methods, Start adopting them as soon as possible.

If you have any Question, Let them come below :-

Parts of the content are Copyright with Common Creative License, So when you share them, please note you provide this page URL.

Thank you KroKite. Copyright  © 2010-2013

Reference :-

World of Hacker © 2011 Creative Commons License
World of Hacker by KroKite is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
Based on a work at
Permissions beyond the scope of this license may be available at!newtopic/hackerforum.