Course contentsShow
← Security
Lesson 581 of 3,05213. Web Security - Injection AttacksFree lesson

Second-Order SQL Injection

Exploiting stored malicious input that triggers SQLi when retrieved and used in a different query.

Second-Order SQL Injection

What you'll learn: How attackers exploit applications by storing malicious SQL code that triggers only when the application later retrieves and uses that data in a different query.

The Delayed Threat

Unlike the SQL injection attacks you've learned so far where malicious input executes immediately, second-order SQL injection is a two-stage attack. The attacker first stores malicious SQL code in the database through one operation (like user registration), and the injection only triggers when the application retrieves that stored data and uses it in a different SQL query later—without proper sanitization.

Think of it like planting a time bomb: you place the explosive (malicious SQL) in one location, but it doesn't detonate until someone moves it to a different context (another query) where security checks are absent.

How It Works

  1. Stage 1 - Storage: An attacker submits malicious input through a form that does sanitize input before inserting into the database. The malicious payload is stored as plain data.

  2. Stage 2 - Exploitation: Later, when the application retrieves this "safe" stored data and incorporates it into a new SQL query without sanitization (assuming it's already safe because it came from the database), the injection executes.

Example scenario:

  • User registers with username: admin'--
  • Application sanitizes this during registration, stores it safely
  • Later, user updates their profile, and the application retrieves the username from the database
  • Application uses the retrieved username directly in an UPDATE query: UPDATE profiles SET email='...' WHERE username='admin'--'
  • The injected SQL executes in this second query

Key Takeaway: Second-order SQL injection exploits the false assumption that data retrieved from your own database is inherently safe—malicious payloads can lie dormant until reused in vulnerable queries downstream.