Course contentsShow
← Security
Lesson 1242 of 3,05225. Application Security - Secure CodingFree lesson

Second-Order SQL Injection in ORMs

Detect and prevent second-order injection where stored data becomes part of queries in later operations through ORMs.

Second-Order SQL Injection in ORMs

You'll learn how attackers exploit stored data to inject SQL later, even when using ORMs.

What Is Second-Order SQL Injection?

Unlike direct SQL injection where malicious input attacks immediately, second-order injection is a delayed attack. An attacker stores malicious data in your database (first order), then that data becomes part of a SQL query during a later operation (second order) — triggering the attack.

This is particularly tricky with ORMs because developers assume the ORM handles all safety. However, when you retrieve data and later use it to build queries — especially raw queries or dynamic filters — that stored data can become an injection vector.

The Attack Flow

Think of it like a time bomb:

  1. Step 1 (Storage): Attacker submits username admin'-- which gets safely stored in the database
  2. Step 2 (Retrieval): Your code fetches that username: user = User.find(123)
  3. Step 3 (Injection): You use that data unsafely: db.raw("SELECT * FROM logs WHERE username = '#{user.username}'")

The ORM protected you during storage, but the danger emerges when you treat stored data as trusted.

Prevention Strategy

Never trust data from your own database when building queries. Even data you stored can be malicious:

  • Use parameterized queries even for stored values
  • Avoid concatenating database values into raw SQL
  • Validate/escape data before using it in query construction
  • Prefer ORM query builders over raw SQL with interpolated stored data
  • Apply output encoding principles to database data, not just user input

Key Takeaway: Second-order SQL injection exploits stored data that becomes part of later queries; defend by treating all data — even from your database — as potentially untrusted when constructing SQL operations.