UNION attack, determining the number of columns returned by the query
Last updated
Last updated
Lab #3 by PortSwigger Web Security Academy:
For a UNION
query to work, two key requirements must be met:
The individual queries must return the same number of columns.
The data types in each column must be compatible between the individual queries.
This lab contains a SQL injection vulnerability in the product category filter. The results from the query are returned in the applicationβs response, so you can use a UNION attack to retrieve data from other tables. The first step of such an attack is to determine the number of columns that are being returned by the query. You will then use this technique in subsequent labs to construct the full attack.
First, we need to determine the number of columns returned by the query. Letβs intercept the HTTP request when we filter on Gifts
category and attempt a union SQL injection.
Checking with a single quote ('
) reveals that the application is vulnerable.
Order by 1, 2, and 3 doesnβt fail, but order by 4 fails, indicating that the query has only 3 columns.
Knowing that we have 3 columns, letβs replace the ORDER BY 3 with ' UNION SELECT NULL,NULL,NULL
in order to solve the lab.
Now, letβs automate the attack using a Python script.
Executing the above script returns an answer of 3 columns, consistent with what we observed in the manual test. Great!
And we can confirm from Burp HTTP History that the SQL error no longer appears when we have 3 columns.
On Oracle, every SELECT
query must use the FROM
keyword and specify a valid table. There is a built-in table on Oracle called dual
which can be used for this purpose. So the injected queries on Oracle would need to look like: ' UNION SELECT NULL FROM DUAL--
The payloads described use the double-dash comment sequence --
to comment out the remainder of the original query following the injection point. On MySQL, the double-dash sequence must be followed by a space. Alternatively, the hash character #
can be used to identify a comment
To solve the lab, determine the number of columns returned by the query by performing a attack that returns an additional row containing null values.