How to prevent your website from SQL Injection vulnerability

post-parameter-injection
MySQL Injection is a type of attack where an end user may hack your database from his browser itself. Comprehending this article might require advanced IT knowledge. Here my main attempt will sql injection prevention.

What will be your SQL statement to retrieve a username and a password when we login to your website?

In most cases this will be like

SELECT 1 FROM user WHERE username=’ABC’ AND password=’1234’;

Now think if a user fills data something like this:
username= ABCD
password= ‘ or ’1′=’1

Now check your SQL query. It has changed now.

SELECT 1 FROM user WHERE username=’ABCD’ AND password= ’’ OR ‘1’ = ’1’ ;

Now with this query a user with an invalid username and without a password can make an unusual entrance to your private areas.

Before 2005 almost 50% website’s admin panel were hacked with this approach.
Even in 2012 it is still active and lots of websites are hacked. This is a simple example of SQL injections. There are lots of predefined SQL injection codes readily available online. You can create your own.

Even a normal internet surfer can break down your security with such a code.

To get rid of this issue we can make our Login QUERY statement something like this.
You need to make another function which will escape all the special characters form the user data if you are using PHP then you can use mysql_real_escape_string function which adds a backslashe to the following characters: \x00, \n, \r, \, ‘, ” and \x1a.

$query = sprintf(“SELECT 1 FROM users WHERE user=’%s’ AND

password=’%s'”,mysql_real_escape_string($user),mysql_real_escape_string($password));

However this will only save you from incorrect login but what if an authorized user is doing some trick to get additional things from your website.
I will suggest making a function which works globally throughout the website.
Like this one. The following codes let you discover the ways to get rid of every possible SQL Injection attack
.

Now we need to call check_form_submission in each form submission. Please try to understand the logic behind the code. It will check for all the GET and POST variables. You can modify the code accordingly to variable types. But this is OK at all. Let me know if you have discovered something or want to share your experience with me.

Here is a list of SQL Injection Strings you can try to test:
“1 OR 1=1″
“1\’ OR \’1\’=\’1″
“1\’1″
“1 EXEC XP_”
“1 AND 1=1″
“1\’ AND 1=(SELECT COUNT(*) FROM tablenames); –”
“1 AND USER_NAME() = \’dbo\’”
“\\\’; DESC users; –”
“1\\\’1″
“1\’ AND non_existant_table = \’1″
“\’ OR username IS NOT NULL OR username = \’”
“1 AND ASCII(LOWER(SUBSTRING((SELECT TOP 1 name FROM sysobjects WHERE xtype=\’U\’), 1, 1))) > 116″
“1 UNION ALL SELECT 1,2,3,4,5,6,name FROM sysObjects WHERE xtype = \’U\’ –”
“1 UNI/**/ON SELECT ALL FROM WHERE”
“%31%27%20%4F%52%20%27%31%27%3D%27%31″
“1′ OR ’1′=’1″

Comments

comments