Second-order SQL injection occurs when malicious input is stored in the database and executed later when retrieved and used in a query. Unlike first-order injection where input is immediately executed, second-order injection exploits the trust applications place in data from their own database.
Having explored various in-band and out-of-band techniques, we now examine a more subtle attack vector where the injection point and execution point are separated in time.
In second-order injection, the payload is stored safely (often properly escaped) during initial input. The vulnerability occurs when this stored data is later retrieved and used in a query without proper sanitization.
Second-order injection is harder to detect because the injection and execution happen at different times. Look for user input that is stored and later used in database queries.
The attack involves two steps: first, store the payload; second, trigger its execution by causing the application to use the stored data in a query.
# Step 1: Register with malicious username
username: admin'--
password: anything
# Step 2: Trigger execution by changing password
# The application executes:
# UPDATE users SET password='newpass' WHERE username='admin'--'
# This changes admin's password instead of the attacker'sMore sophisticated attacks can extract data or escalate privileges by carefully crafting payloads that execute when specific application functions are triggered.
# Extract data through second-order injection
# Store payload in profile field
profile_name: '+(SELECT password FROM users WHERE username='admin')+'
# When application displays profile, it might execute:
# SELECT * FROM profiles WHERE name=''+(SELECT password FROM users WHERE username='admin')+''
# This could cause an error revealing the password💡 Second-order injection often bypasses WAFs because the payload passes through input validation but executes later when retrieved from the database.
⚠️ Second-order injection can be particularly dangerous because it may allow privilege escalation or data extraction even when input validation appears robust.
Testing requires understanding the application's data flow. Map where user input is stored and where it's later used in queries.
# Testing methodology
# 1. Identify all input points that store data
# 2. Store test payloads (e.g., single quotes, SQL keywords)
# 3. Navigate to pages that might use stored data
# 4. Look for SQL errors or unexpected behavior
# 5. Craft specific payloads based on observed behavior
# Test payloads to store
'
";
' OR '1'='1
1; SELECT 1
admin'--Verify exercises to earn ★ 200 XP and unlock next lab level.