Union based SQL injection

Obtain flag from table flag field flag in Sqlite DBMS.

ID Name Age Weight Secret
1 Tim Jones 26 33 487535671
2 Michael Graves 76 62 492408112
3 Kathleen Moon 12 59 266885245

Solution

1. Enter ', send request and observe the error.

Since we know that flag is in the flag table and we have query output, we can do UNION-based attack. To do so we need to find a number of columns in current table first.

2. Enter ' order by 1 --

We can see the error "No matches", but the query executed successfully. Lets increase order by one by one untill we will get different response.

3. Enter ' order by 2 --

...

4. Enter ' order by 6 --

We can observe another error: "...ORDER BY term out of range...", we can guess that there is 5 columns in the capybaras table.

To craft a valid UNION query we need to match types and number of columns in both tables. Since we know the number of columns in the first table and we need only one column from the second table, we can fill other columns with null values, since it has "all" types, and we dont need to do extra guess. And we will put flag column at the end, since we can see that last column of capybaras table "secret" is definetely a text type.

5. Enter ' UNION select null,null,null,null,flag from flag --

Explanation: in query SELECT * FROM capybaras WHERE name ='' UNION select null,null,null,null,flag from flag -- :

  • injected quote ' closes the name value
  • UNION add a new command to concatenate results of SELECTs
  • null,null,null,null,flag - list of columns to concate
  • from flag tells from where to select content
  • -- is a comment symbol in SQLite syntax. Everything after the comment symbol is meaningless to SQL parser
So we have created such query that returns 5 empty columns from the first table and concatenates the content of second table to these empty columns.