SQL Injection/UNION Attack
From charlesreid1
This page covers UNION attacks, a type of SQL Injection attack.
For coverage of how to carry out this type of attack with Burpsuite, see Burpsuite/SQL Injection#UNION Attacks
Overview
A UNION attack is a type of SQL Injection attack that exploits the ability to run SQL code on a remote server by running cross-table queries to fetch (for example) username/password data from a product page, or to extract information about the database schema.
Example: Retrieving Data from Other Tables
Suppose a web application allows a user to list products by category, and uses the user-provided "category" field to run the following SQL query:
SELECT name, description FROM products WHERE category = 'Gifts'
Now, if the attacker can pass this as a category:
' UNION SELECT username, password FROM users--
and the user input is not sanitized, the query will return all usernames and passwords along with product listings.
Determining Number of Columns for an Attack
When performing a UNION attack, you may need to know how many columns are returned from the original query.
There are two ways to do it.
The first way is to submit a series of ORDER BY clauses (order by field 1, order by field 2, etc), increment which field/column index until you get an error:
' ORDER BY 1-- ' ORDER BY 2-- ' ORDER BY 3-- ...
Once the field/column index is too big, the application will return an error. The SQL error may be shown, or may return an error code, or may return no results.
The second way is to submit a series of UNION SELECT payloads, specifying a different number of null values:
' UNION SELECT NULL-- ' UNION SELECT NULL,NULL-- ' UNION SELECT NULL,NULL,NULL-- ...
Same as above - once there are more NULLs than fields, the application will return an error. This method could trigger a different error (null pointer error) than above.
References
Burp suite: https://portswigger.net/web-security/sql-injection/union-attacks