SQL UNION Injection
2 min readJun 26, 2023
SQL UNION Injection makes use of UNION command in SQL.
How UNION command is used in normal situations:
UNION command is used to execute two commands at once.
SELECT name, age FROM random_table UNION SELECT name, number_of_participants FROM random_table_2
-- name is a string variable (varchar)
-- age and number_of_participants contain integer variables
This command will return a table containing information from random_table
and random_table_2
. This table will contain two columns.
Important note when using UNION command:
- Both commands must return the same number of columns.
- A column must contain the same data type.
Steps in a UNION Injection attack:
- Identify whether the query is vulnerable to a SQL injection attack. Add
'--
to the end of the query. - If yes, Identify how many columns the query returns with each query. Add
' ORDER BY 1--
to the end of the query. Increment the number until an error is received. - Identify which columns return a string. Let’s say a query returns 3 columns. Add
' UNION SELECT 'a', NULL, NULL--
to the end of the query. Then, add ‘a’ to second column followed by the third column. If a 200 response code is received, this confirms that the column returns a string. - (Optional) Learn more about the database. Add
' UNION SELECT table_name, NULL, NULL FROM information_schema.table--
to list all tables in the database. Add' UNION SELECT column_name FROM information_schema.columns WHERE table_schema = 'your_db'--
to know the number of columns in a table - Extract data from SQL server with UNION.