Second-Order SQL Injection
A team fixes SQL injection by parameterising every query that takes request data. A tester registers a new account with the user name admin'--, the registration query stores it safely, and nothing happens. A week later the same tester changes their password, and the administrator's password changes instead. The payload was stored harmlessly, then read back from the application's own database by a different feature, which trusted it because "it came from our database, not from the user". That is second-order (stored) SQL injection: the input and the injection happen in different requests, often in different code written by different people. Scanners that send a payload and look at the immediate response miss it, which is why it survives in otherwise careful code bases.
Definitions
- First-order injection: the payload is used in a query in the same request that delivered it.
- Second-order injection: the payload is stored (user name, address, file name, a setting, a log line) and later concatenated into a query by another code path: a password change, a report, a batch job, an admin screen, a search index rebuild.
- Trusted-source fallacy: treating data from your own database, files or internal services as safe. Data is only as trustworthy as the least trusted thing that ever wrote it.
The attack, on a toy user database
Registration is parameterised. The password-change feature looks up the current user's name by session and then builds an UPDATE with it, because the developer thought the name was clean.
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT UNIQUE, pw_hash TEXT)")
db.execute("INSERT INTO users (name, pw_hash) VALUES ('admin', 'h$admin-original')")
def register(name, pw_hash): # first order: safe
db.execute("INSERT INTO users (name, pw_hash) VALUES (?, ?)", (name, pw_hash))
return db.execute("SELECT id FROM users WHERE name = ?", (name,)).fetchone()[0]
def change_password_vulnerable(user_id, new_hash):
name = db.execute("SELECT name FROM users WHERE id = ?", (user_id,)).fetchone()[0]
sql = f"UPDATE users SET pw_hash = '{new_hash}' WHERE name = '{name}'" # second order: unsafe
print(" SQL:", sql)
db.execute(sql)
def change_password_fixed(user_id, new_hash):
db.execute("UPDATE users SET pw_hash = ? WHERE id = ?", (new_hash, user_id)) # key by id, bind values
def show():
for row in db.execute("SELECT id, name, pw_hash FROM users ORDER BY id"):
print(" ", row)
attacker_id = register("admin'--", "h$attacker-1")
print("after registration (stored safely, byte for byte):")
show()
print("attacker changes 'their own' password with the vulnerable code:")
change_password_vulnerable(attacker_id, "h$attacker-chosen")
show()
db.execute("UPDATE users SET pw_hash = 'h$admin-original' WHERE name = 'admin'")
print("same request with the fixed code:")
change_password_fixed(attacker_id, "h$attacker-chosen")
show()after registration (stored safely, byte for byte):
(1, 'admin', 'h$admin-original')
(2, "admin'--", 'h$attacker-1')
attacker changes 'their own' password with the vulnerable code:
SQL: UPDATE users SET pw_hash = 'h$attacker-chosen' WHERE name = 'admin'--'
(1, 'admin', 'h$attacker-chosen')
(2, "admin'--", 'h$attacker-1')
same request with the fixed code:
(1, 'admin', 'h$admin-original')
(2, "admin'--", 'h$attacker-chosen')
The stored name admin'-- closed the string in the later query, and -- commented out the closing quote, so the WHERE clause became name = 'admin'. The attacker's own row didn't change; the administrator's did. The fixed version does two things, either of which would have been enough: it binds every value, and it identifies the row by the numeric id from the session instead of by a name.
Where second-order bugs hide
| Stored where | Used later by |
|---|---|
| user name, display name | password change, admin user search, audit reports |
| uploaded file name | a batch job that builds INSERT … VALUES ('{filename}'), or a shell command (that is command injection) |
| shipping address, notes | an export to CSV, a reporting query built from saved filters |
| saved search, dashboard filter | a "run this report" feature that pastes the filter into WHERE |
log lines, User-Agent |
a log viewer that queries by them, a SIEM rule builder |
The same pattern carries other injections: stored XSS (a stored name rendered without encoding), stored command injection, stored template injection.
How second-order injection is detected
- Code review: search for queries built with string formatting anywhere, not only in request handlers: background jobs, migrations, admin tools, report builders. A value read from the database and pasted into SQL is as bad as one read from the request. SAST tools with taint tracking from database reads (CodeQL can model this) help; simple grep for f-strings and
+in SQL helps more. - Testing: store payloads in every field you can (
x'--,x' OR '1'='1, a quote alone), then exercise every other feature that uses them: profile pages, password change, exports, admin screens, e-mails. Watch for errors and unexpected changes elsewhere. Use unique markers per field (tst-a1'--) so you can tell which stored value triggered which effect. - Logs: database errors from batch jobs or admin features that coincide with recently stored unusual values; audit logs showing a row changed by a request belonging to another user.
How it is fixed
- Parameterise every query, whatever the source of the value. "Is this value trusted?" is the wrong question; "is this value data?" always has the answer yes.
- Key writes by stable ids from the session, not by names or other user-controlled attributes.
- Validate at input too (a user name allow-list such as
^[a-z0-9_.-]{3,30}$) as defence in depth: it would have refusedadmin'--at registration, but it is not the fix, because other fields can't be restricted like that. - Audit trails on sensitive tables (who changed which row from which request) turn a silent takeover into a detectable event.
Pitfalls
- Escaping on input ("we store names with quotes doubled") breaks the data and fails as soon as one code path un-escapes or a new consumer reads it raw. Store the raw value; make every consumer safe.
- Testing only the response of the storing request: the effect appears elsewhere, later.
- Trusting "internal" data from other services, message queues and partner feeds. They are input.
Practice
1. A nightly job runs f"DELETE FROM carts WHERE coupon = '{row.coupon}'" for every expired coupon code entered by users. What could a stored code do?
A code like x' OR '1'='1 would delete every cart. Bind the value: db.execute("DELETE FROM carts WHERE coupon = ?", (row.coupon,)).
2. Why is a strict user-name allow-list not enough as the only fix?
It protects one field. Addresses, notes, file names and imported data can't be restricted the same way, and a later change to the allow-list (or an import that bypasses registration) reopens the hole. Every query must still bind its values.
Test yourself
What distinguishes second-order SQL injection?
- It needs two quotes
- The payload is stored safely, then pasted into a query later by another code path
- It only affects INSERT
- It requires admin rights
In the example, whose password changed with the vulnerable code?
- The attacker's
- The admin's
- Nobody's
- Everyone's
Why do automated scanners often miss second-order injection?
- It is rare
- The effect appears in a different feature or later, not in the response to the request that delivered the payload
- It needs JavaScript
- Scanners don't send quotes