Section 4 of 6

SQL Injection

🎯 What You'll Learn

  • What is SQL injection
  • How SQL injection works
  • Vulnerable code examples
  • Parameterized queries
  • Entity Framework Core protection

What is SQL Injection?

SQL Injection is an attack where malicious SQL code is inserted into queries, allowing attackers to read, modify, or delete database data.

How SQL Injection Works

Vulnerable Code (DON'T DO THIS!) C#
// VULNERABLE!
var query = $"SELECT * FROM Users WHERE Email = '{email}' AND Password = '{password}'";
var user = _context.Users.FromSqlRaw(query).FirstOrDefault();
Attack Example SQL
-- Attacker enters:
email = "admin@example.com"
password = "' OR '1'='1"

-- Resulting query:
SELECT * FROM Users 
WHERE Email = 'admin@example.com' 
AND Password = '' OR '1'='1'

-- Always true! Bypasses authentication!

Prevention: Parameterized Queries

Safe (Parameterized) C#
var user = _context.Users
    .FromSqlRaw("SELECT * FROM Users WHERE Email = {0} AND Password = {1}", email, password)
    .FirstOrDefault();

// Or with named parameters:
var user = _context.Users
    .FromSqlRaw("SELECT * FROM Users WHERE Email = @email AND Password = @password",
        new SqlParameter("@email", email),
        new SqlParameter("@password", password))
    .FirstOrDefault();

Entity Framework Core Protection

EF Core LINQ queries are automatically parameterized - safe by default!

Safe (LINQ) C#
// Automatically parameterized - SAFE!
var user = await _context.Users
    .Where(u => u.Email == email && u.Password == password)
    .FirstOrDefaultAsync();

InvenTrack Example

Vulnerable Search (DON'T DO THIS!) C#
// VULNERABLE!
var query = $"SELECT * FROM Products WHERE Name LIKE '%{searchTerm}%'";
var products = _context.Products.FromSqlRaw(query).ToList();
Safe Search (LINQ) C#
// SAFE!
var products = await _context.Products
    .Where(p => p.Name.Contains(searchTerm))
    .ToListAsync();

Best Practices

  • Use LINQ: Automatically parameterized
  • Never concatenate: Don't build queries with string concatenation
  • Use parameters: If using raw SQL, always use parameters
  • Validate input: Reject suspicious input
  • Least privilege: Database user should have minimal permissions

Key Takeaways

  • SQL Injection: Malicious SQL in queries
  • String concatenation: NEVER build queries this way
  • Parameterized queries: Use parameters, not concatenation
  • EF Core LINQ: Safe by default
  • FromSqlRaw: Use with parameters only