0% found this document useful (0 votes)
17 views5 pages

6.SQL Injection and Prevention in C#

Uploaded by

safia sadaf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views5 pages

6.SQL Injection and Prevention in C#

Uploaded by

safia sadaf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

SQL Injection and Prevention in C#

SQL Injection Attack in C#:


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.

Points to Remember:
SQL Injection is a SQL Code Injection mechanism that might destroy your database.

SQL Injection is one of the most common web hacking techniques.

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#.

How does SQL Injection work 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:

1st SQL Statement: SELECT * FROM Products WHERE NAME LIKE ‘Mobile’;

2nd SQL Statement: DELETE FROM Products

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.

SQL Injection Based on 1=1 is Always True


Look at the example above again. The original purpose of the code was to create an SQL
statement to select a user, with a given user id.

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

Then, the SQL statement will look like this:

SELECT * FROM Users WHERE 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.

What if the "Users" table contains names and passwords?

The SQL statement above is much the same as this:

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.

How to Prevent SQL Injection in C# using ADO.NET?


The purpose of parameterized queries is to provide parameters, then connect values to those
parameters, and then execute the query. Queries executed in such a way will not be susceptible
to injection attacks because the query and the parameters will be sent over for execution
separately.

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";

SqlCommand command = new SqlCommand(query, connection);

command.Parameters.AddWithValue("@userId", userId);

In this code:

• The query uses a placeholder (@userId) instead of directly including the user input.

• The user input is added as a parameter using


command.Parameters.AddWithValue("@userId", userId);.

• 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:

string query = $"SELECT * FROM users WHERE id = {userId}";

SqlCommand command = new SqlCommand(query, connection);

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:

SELECT * FROM users WHERE id = 1 OR 1=1

• 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.

You might also like