Rules / C#
SHIELD-CSHARP-003
SQL injection via ExecuteReader on interpolated string
What it detects
ExecuteReader or ExecuteScalar runs a command whose text was built with an interpolated string containing variables.
How to fix
Use parameterized commands rather than passing an interpolated SQL string to Execute methods.
Vulnerable — Shield flags thisOrderService.cs
using System.Data.SqlClient;
using Dapper;
public class OrderService
{
public object CountOrders(SqlConnection conn, string customerId)
{
return conn.ExecuteScalar($"SELECT COUNT(*) FROM Orders WHERE CustomerId = '{customerId}'");
}
}
Fixed — scans cleanOrderService.cs
using System.Data.SqlClient;
using Dapper;
public class OrderService
{
public object CountOrders(SqlConnection conn, string customerId)
{
return conn.ExecuteScalar(
"SELECT COUNT(*) FROM Orders WHERE CustomerId = @id",
new { id = customerId });
}
}
Both snippets are verified against the shipped scanner: the vulnerable one triggers SHIELD-CSHARP-003, the fixed one does not.