In my previous tutorials, I’d explained about sql defination and how to get connection string in asp.net, insert update and delete on asp.net gridview and other more cracking tutorials on GridView, Asp.net, SQL Server here.
Now here in this tutorial, I’ll explain what is sql injection and how prevent it from sql hackers with simple login test example in asp.net, c#, vb.net.
What is SQL Injection Attack?
The SQL Injection Attack is a technique of “insertion” or “injection” of a SQL queries via webpage or webform input controls. SQL injection attacks are a type of injection attack, in which SQL commands are injected into data-plane input in order to effect the execution of predefined SQL commands. It means altering SQL commands into SQL statements, and modifies database tables or data with using SQL Statements like Insert, Update or Delete.
How SQL Injection Attack Works?
Let’s say you have one login form containing UserName input in that. Generally, we enter UserName as John, Mack etc as you can see in this example statement:
SELECT * FROM UserDetails WHERE UserName=’Mack’;
But some malicious users or hackers can inject SQL commands into an SQL statement, via webpage input. Now check the following statement:
SELECT * FROM UserDetails WHERE UserName=’Mack’ or ‘1’=’1′;
See below image, you’ll understand what I mean to say.
As you can see the WHERE clause, I’ve added UserName=’Mack’ or ‘1’=’1′, that means I added sql injection that can inject SQL command into an SQL statement.
Now question is what is ‘1’=’1′ in that statement?
I would have to say it’s a good question.
‘1’=’1′ is a Boolean condition added with sql statement, results your sql statement becomes always true. Check both statements; you’ll surely understand what it stands for. 😉
How to Prevent SQL Injection Attack?
For security reason we need to prevent website from SQL Injections.
But the question is how?
I would say, by using Parameterized SQL Statements..
Yes, we can use parameters in sql query like SELECT * FROM UserDetails WHERE [email protected]; and pass @UserName parameter value as cmd.Parameters.Add(“@UserName”, ‘aspneto’). I’ll show you an example for the same below.
Here is how your simple sql statement looks:
And following is the Parameterized sql query:
Don’t underestimate the power of the hackers. They can guess your usenames, passwords or even database table names and perform injections. So best practice is to use prefix before your database tables like “xyz_UserDetails” and most importantly use parameterized queries instead simple statement.
Now, it’s up to you, what you prefer most, that is your website security or sql injections? 😉