In this article, I am going to discuss SQL Injection and Prevention in C# using ADO.NET with Examples. Please read our previous article where we discussed How to Load XML Data to a Data Table using ADO.NET with Examples.
According to MSDN, SQL Injection is an attack in which malicious code is inserted into strings that are later passed to SQL Server Database for execution. Any procedure or mechanism that constructs SQL statements should be reviewed for injection vulnerabilities. This is because SQL Server will execute all syntactically valid queries that it receives. Even parameterized data can be manipulated by a skilled and determined attacker.
It is the application layer attack which means a front-end attack that takes benefit of inappropriate coding of our applications that allows hackers to insert SQL commands into our application code that is SQL statements. So, as a developer or programmers, we should check and prevent SQL Injection in our application code.
Note: First, we will see an example of SQL Injection, and then we will see how we can prevent SQL Injection in C#.
The Primary form of SQL injection consists of the direct insertion of SQL Statements into user-input variables that are used to prepare the SQL commands dynamically and executed them on the database.
SQL Injection in C# usually occurs when we ask a user for input, like their username/user id, or ask to input some information, along with the name/id, or some information, or instead of name/id, or some information, the user entered an SQL statement and that SQL Statement run on your database.
The following C# code shows a simple SQL Injection Attack. The following C# code builds an SQL query by concatenating hard-coded strings together with a string value entered by the user.
string ProductName = Console.ReadLine();
var SQLQuerey = “SELECT * FROM Products WHERE NAME LIKE ‘” + ProductName + “%'”;
Here, we are asking the user to enter the name of the product to search in the database. If the user entered Mobile, then the SQL query generated by the C# code is as follows:
SELECT * FROM Products WHERE NAME LIKE ‘Mobile%’
Now, assume that the user enters the following string instead of Mobile.
Mobile’; DELETE FROM Products —
In this case, the following SQL query is going to be generated by the C# code.
SELECT * FROM Products WHERE NAME LIKE ‘Mobile’; DELETE FROM Products –%’
The point that you need to remember while working with SQL Server, the semicolon (;) in the SQL Queries denotes the end of one query and the start of another SQL query. The double hyphen (–) in SQL Statement in SQL Server Database indicates that the rest of the current line is a comment and should be ignored while executing the SQL Statement. If the modified code is syntactically correct, then it is going to be executed by the server.
In the above example, the SQL Server will execute two SQL Statements. They are as follows:
So, in this case, first, it will select all the records from the Product table where the Product Name starts with the word Mobile and then it is going to delete all the records from the Product Table. This is called SQL Injection.
Note: If the Injected SQL Queries are syntactically correct, they are going to be executed by the databases. Therefore, as a programmer and as a good programming practice we must validate all user input and carefully review code that prepares SQL Statements dynamically.
We are going to use the following Products table to understand SQL Injection in C# using ADO.NET.
Please use the below SQL Script to create the database and populate the Products table with the required sample data.
Now, create a console application and then copy and paste the following code into it. In the below example, we are creating the SQL Query dynamically by concatenating the hard-coded string with the string value input by the user from the console. This is very dangerous, as it is vulnerable to SQL injection attacks.
Now, run the above code and entered the search string as Mobile and you will get the result as expected as shown in the below image.
Now, again run the above application and this time entered the search string as Mobile’; DELETE FROM Products — as shown in the below image.
Now, you will not get the result. To verify why, please check the Products database table and you will see that there is no record. That the DELETE query that we input is executed in the database and deletes all the records from the Products table. This is an SQL Injection attack. As a user, we are injecting SQL Statements and that gets executed in the database.
I have seen a lot of new developers building queries dynamically by concatenating the hardcoded strings with user-entered input values. Just imagine the damage that can happen as a result of SQL Injection. However, SQL Injection can be easily avoided, by using parameterized queries or stored procedures. Let us see both approaches.
We can prevent SQL Injection using parameterized queries or by using stored procedures. To prevent SQL Injection Attacks in C#, we need to follow the below points.
Before proceeding further and seeing how we can prevent the SQL Injection, let us first insert records into the Products table by executing the below INSERT SQL Statements as in the previous example we have deleted all the records from the Product table using SQL Injection Attack.
In the following example, we are Preventing SQL Injection Attacks using Parameterized Queries. Now, you can see that the query uses the parameter – @Name. The value for this query parameter is then provided by using the AddWithValue() method. The parameter is associated with the command object using the Parameters collection property.
Now, run the above code and entered the search string as Mobile and you will get the result as expected as shown in the below image.
Now, again run the above application and this time entered the search string as Mobile’; DELETE FROM Products — as shown in the below image.
Now, the data is not going to be deleted from the database table and the reason for this is the below SQL Statement. As you can see whatever value we have entered that is going to use as the value for the Name parameter. As this value does not match in the Products table and hence you can see it is not returning any record. You can find the below SQL statement which is generated and run by the SQL Server by using the SQL Profiler tool.
exec sp_executesql N’SELECT * FROM Products WHERE NAME LIKE @Name’,N’@Name nvarchar(33)’,@Name=N’Mobile”; DELETE FROM Products –%’
Let us see how we can prevent SQL Injection Attacks in ADO.NET using Stored Procedures. So, let us first create a stored procedure that returns the list of products by executing the below SQL Scripts. This stored procedure takes an input parameter @Name. And based on that input parameter it is going to return the results.
Now, let us rewrite the previous example to use the stored procedure as follows. The following example code is self-explained, so please go through the comment lines.
Now, with the above changes run the application and it should work as expected by Preventing SQL Injection Attacks. So, these are the two ways by using which you can prevent the SQL Injection Attack in ADO.NET C#.
Note: So, the conclusion is that always used parameterized queries or stored procedures when interacting with the database to perform CRUD Operations, to avoid SQL Injection Attacks.
In the next article, I am going to discuss SqlCommandBuilder in C# with Examples. Here, in this article, I try to explain SQL Injection and Prevention in C# with Examples. I hope you enjoy this SQL Injection and Prevention in ADO.NET using C# Language with Examples article.