Skip to content

Union-Based SQL Injection

Union-based SQLi is an in-band injection technique that leverages the UNION SQL operator to combine the results of a malicious query with the results of the original, legitimate query. This allows an attacker to extract data from other tables within the database.

Conditions for a Successful Attack

For a UNION query to work, two key conditions must be met: 1. The malicious query must return the same number of columns as the original query. 2. The data types in each corresponding column must be compatible between the original and the malicious queries.

Exploitation Methodology

The process is a step-by-step enumeration of the database.

Vulnerable URL: http://example.com/items.php?id=1

1. Determine the Number of Columns

Use the ORDER BY clause and increment the column index until the query fails (which usually results in an error or a change in the page).

' ORDER BY 1-- (Works)
' ORDER BY 2-- (Works)
' ORDER BY 3-- (Fails)
This indicates that the original query is selecting 2 columns.

2. Find Columns with a Compatible Data Type

Now, use a UNION SELECT payload with NULL values for each column, then replace them one by one with a test string to see where it is reflected in the application's response.

' UNION SELECT 'a', NULL--
' UNION SELECT NULL, 'b'--
If the page displays the string 'b' when the second payload is used, it means the second column is compatible with string data and is being displayed.

3. Enumerate the Database

Once you have a working UNION SELECT payload, you can replace the test string with database introspection queries.

Get Database Version and User:

' UNION SELECT @@version, user()--

List Tables from information_schema (MySQL/MariaDB):

' UNION SELECT table_name, table_schema FROM information_schema.tables--

List Columns from a Specific Table:

' UNION SELECT column_name, NULL FROM information_schema.columns WHERE table_name = 'users'--

Dump Data from a Table:

' UNION SELECT username, password FROM users--