P M A J E W S K I

Please Wait For Loading

A Comprehensive Guide to Preventing SQL Injection - Software Developer's Tour

    You Are Currently Here!
  • Home
  • ProgrammingA Comprehensive Guide to Preventing SQL Injection
Syringe

A Comprehensive Guide to Preventing SQL Injection

I recently wrote an article which is the first part about SQL Injection SQL Injection in C# Application: An Example.

Today, we will continue this topic answering the question asked in the previous post “How can we avoid SQL Injection?

Entity Framework

The first option is to use Entity Framework as ORM in our application. Entity Framework uses LINQ-to-Entities parametrized queries preventing SQL Injection attacks. 

I’m using here the same database form previous post created with Scaffolding (Reverse Engineering)

dotnet ef dbcontext scaffold "Data Source=localhost;Initial Catalog=TestSqlInjection;Trusted_Connection=yes;Integrated Security=true;TrustServerCertificate=True;" Microsoft.EntityFrameworkCore.SqlServer
query

As you can see, we have 3 users in database. Let’s try to select user wtih email “test@example.com“.

using Sql_Injection;

var context = new TestSqlInjectionContext();
var email = "test@example.com";
var password = "qwe";
var user = context.Users
    .Where(x => x.Email == email && x.Password == password)
    .FirstOrDefault();

Console.WriteLine($"User: {user?.Email}");

The result of this code will be

“User: test@example.com”

Let’s use it and try SQL Injection on this query

using Sql_Injection;

var context = new TestSqlInjectionContext();
var email = "test@example.com";
var password = "' or 1 =1--";
var userSqlInjection = context.Users
    .Where(x => x.Email == email && x.Password == password)
    .FirstOrDefault();

Console.WriteLine($"SqlInjectionUser: {userSqlInjection?.Email}");

The result:

SqlInjectionUser:

It’s because userSqlInjection has not been found. SQL injection won’t work when we use an ORM like Entity Framework because the inputs are automatically sanitized. Furthermore Entity Framework restricts direct SQL execution, developers are advised to use parametrized queries or LINQ in order to meet the security requirements.

Is this the only way to prevent SQL injection? Of course not, more methods will be presented on the blog soon.

leave a comment