Introduction

I have found that the most reliable way to achieve a higher rate of successfully identified vulnerabilities is to review the source code when possible. Source code review is a far more effective way than the black-box testing if you know the tactics and methods. In addition, by mapping each case you find and prepare a solution to identify vulnerabilities. This can then be used in creating a methodology for black box testing.

In this post we will discuss how to find for SQL Injections in .NET applications by walking through the source code.

This blog post is based on the research made by Yurii Sanin

SQL Injections in a .NET application

Basically, SQL Injection occurs when a user-controlled parameter can change the execution flow of an SQL query. This happens when data sent to the server side is concatenated with an actual SQL query. Most people know what SQL injection is, but fewer people know why and where exactly it appears in code.

SQL Injection within the ORM models

Most web applications that work with databases and use ORMs (entity framework , NpgSql) are mitigated against SQL Injection attacks. The usage of these models implies a first-code approach, where the application does not work directly with the SQL syntax, but uses already defined models.

The following examples do the same thing, in the first case with the help of ORM:

student = Student("shabarkin","23","[email protected]")
_context.Students.Add(student)

while the second one is a simple SQL Query:

INSERT INTO STUDENT_TABLE (name, age, email) VALUES ('shabarkin', 23, '[email protected]')

Below is a brief description of what an ORM is:

Identify Object-Relational Mapping (ORM) Tools for .NET

We could not achieve a traditional SQL injection, where the application does not work directly with SQL syntax. However, we can try if the application works with raw SQL query in the FromSqlRaw or FromSqlInterpolated method of the ORM object.

If the tableName is a user-controllable parameter and user input is not properly sanitized, an attacker can perform an SQL Injection attack:

_context.Students.FromSqlRaw($"SELECT * FROM [{tableName}]")