# Introduction - In the previous examples, we have been manipulating the original query to subvert the web application logic and bypass authentication, using the `OR` operator and comments - However, another type of SQL injection is injecting entire SQL queries executed along with the original query - This section will demonstrate this by using the MySQL `Union` clause to do `SQL Union Injection` # SQL Union Clauses - The [Union](https://dev.mysql.com/doc/refman/8.0/en/union.html) clause is used to combine results from multiple `SELECT` statements. - In other words, with a `UNION` injection, we will be able to `SELECT` and dump data from all across the DBMS, from multiple tables and databases - Individual `select` actions ```mysql mysql> SELECT * FROM ports; +----------+-----------+ | code | city | +----------+-----------+ | CN SHA | Shanghai | | SG SIN | Singapore | | ZZ-21 | Shenzhen | +----------+-----------+ 3 rows in set (0.00 sec) mysql> SELECT * FROM ships; +----------+-----------+ | Ship | city | +----------+-----------+ | Morrison | New York | +----------+-----------+ 1 rows in set (0.00 sec) ``` - Above `select` actions combined using a `union` clause ```mysql mysql> SELECT * FROM ports UNION SELECT * FROM ships; +----------+-----------+ | code | city | +----------+-----------+ | CN SHA | Shanghai | | SG SIN | Singapore | | Morrison | New York | | ZZ-21 | Shenzhen | +----------+-----------+ 4 rows in set (0.00 sec) ``` - A `UNION` statement can only operate on `SELECT` statements with an equal number of columns - Otherwise we may get an error ![[images/Pasted image 20251203201733.png]] - We can get around this by adding junk fields to the `UNION SELECT` portion of the query as this is where we are trying to coax out compromising data ```mysql mysql> SELECT * from products where product_id UNION SELECT username, 2, 3, 4 from passwords-- ' +-----------+-----------+-----------+-----------+ | product_1 | product_2 | product_3 | product_4 | +-----------+-----------+-----------+-----------+ | admin | 2 | 3 | 4 | +-----------+-----------+-----------+-----------+ ``` # Exercise - access `mysql` server with given creds ![[images/Pasted image 20251203202342.png]] - use `employees` db ![[images/Pasted image 20251203202547.png]] - Use `UNION` statement to determine number of records within `employees` and `departments` tables - Differing numbers of columns ![[images/Pasted image 20251203202700.png]] - As shown below using the `limit 1` statements, the `employees` table has 6 columns and the `departments` table has 2 columns ![[images/Pasted image 20251203203041.png]] - Provide junk for columns 2-6 with the `UNION SELECT` statement ![[images/Pasted image 20251203203440.png]]