Search code examples
sqlmariadbsql-injection

Select info from deleted rows using DELETE ... RETURNING


I am studying SQL injections and I am currently struggling with the following. I have a query similar to this one:

SELECT first_name, last_name FROM users WHERE user_id = $id

and I am supposed to inject SQL code to delete a certain row on the $id parameter.

Since the server DBMS is MariaDB I have come up with the following:

1 
UNION 
SELECT first_name,null 
FROM (delete FROM users 
      WHERE user_id=7 RETURNING first_name)

My idea being to do an union between the selected part and the rows that where deleted using the returning option. The final query would look like this:

SELECT first_name, last_name FROM users WHERE user_id = $id 
UNION 
SELECT first_name,null FROM (DELETE FROM users WHERE user_id=7 
                            RETURNING first_name)

This is supposed to join the information deleted with the one originally queried, and allow the DELETE to be executed, which is the key idea here. I have not been able to inject the more obvious payload of

1; DELETE FROM users WHERE user_id=7

for some reason, I think the driver in use does not allow multi queries or something like that. As far as I can tell the RETURNING way should work, but it does not, and I have modified it several times, so I am not sure if there is a restriction about it that I don't know or what, can someone help with this?

Thanks in advance.


Solution

  • Whether DELETE...RETURNING returns a result set or not, it isn't permitted in a subquery.

    Likewise, some other statements that return a result set, like CALL or SHOW, are not permitted in a subquery.

    The only things you can put inside a subquery are:

    To use DELETE in an SQL injection, you would either have to have a connector interface that allowed multi-query, or else you'd have to manipulate the query so that the DELETE is first, then comment out the rest of the query.