6.SQL Injection and Prevention in C#
6.SQL Injection and Prevention in C#
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.
Points to Remember:
SQL Injection is a SQL Code Injection mechanism that might destroy your database.
SQL Injection is the process of Injecting malicious code in SQL statements, via web page input.
Note: First, we will see an example of SQL Injection, and then we will see how we can prevent
SQL Injection in C#.
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.
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:
Now, assume that the user enters the following string instead of Mobile.
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:
1st SQL Statement: SELECT * FROM Products WHERE NAME LIKE ‘Mobile’;
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.
If there is nothing to prevent a user from entering "wrong" input, the user can enter some
"smart" input like this:
UserId: 105 OR 1=1
The SQL above is valid and will return ALL rows from the "Users" table, since OR 1=1 is always
TRUE.
SELECT UserId, Name, Password FROM Users WHERE UserId = 105 or 1=1;
A hacker might get access to all the user names and passwords in a database, by simply
inserting 105 OR 1=1 into the input field.
Parameters cannot be set using SQL alone – parameterized queries only work when other
programming languages (PHP, ASP.NET, etc.) are involved and as such, require a couple lines of
code to be executed successfully.
We can prevent SQL Injection using parameterized queries o. To prevent SQL Injection Attacks
in C#, we need to follow the below points.
In C#, while preparing a SQL Statement, please use SqlParameter to define the Parameter Name,
type, and value instead of making a straight SQL command as we did in our previous example.
While executing the query, please specify the CommandType property value either as Text or
Stored Procedure.
If you are using Parameters Collection, then please mention the type and size of the parameters.
Another way to avoid SQL injection attacks is to filter the user input for SQL characters. Please
check if the user input contains some special characters like %,–, ; and if contains please take
the necessary action.
SAFE CODE
string query = "SELECT * FROM users WHERE id = @userId";
command.Parameters.AddWithValue("@userId", userId);
In this code:
• The query uses a placeholder (@userId) instead of directly including the user input.
• This means the input is treated strictly as a value, not as part of the SQL command, so
even if the input is malicious (like 1 OR 1=1), it will be treated as a string value and not
alter the query logic.
UNSAFE CODE
Here's the C# code snippet demonstrating a query that is prone to SQL injection:
In this snippet:
• The user input userId is directly concatenated into the SQL query string, making it
vulnerable to SQL injection attacks if the input is malicious.
• The user input (userId) could be something like 1 OR 1=1, which changes the query to:
• This query will always be true because 1=1 is always true. It can lead to retrieving all
records from the users table or worse, executing unwanted commands.
Key Differences:
• Unsafe Query: Directly inserts user input into the query string, making it vulnerable to
SQL injection.
• Safe Query: Uses placeholders and parameter binding, ensuring user input is treated as
a value, not executable code.
By using parameterized queries, you ensure that user inputs are safely handled and cannot
alter the structure of the SQL command, protecting your application from SQL injection attacks.