Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this SQL injection succeed even though the SQL statement produces a syntax error?

In this question and some of the comments, this input:

$input = '; DELETE FROM table_name ; #';

was suggested as an example of an SQL injection into this PHP statement:

$input = $_POST['input'];
'SELECT '.$input.' FROM table_name'

I cut into the chase and used an example in MySQL directly, although I used * in place of #. The result is the same.

CREATE TABLE a_table (
 id INT NOT NULL);

INSERT INTO a_table (id) VALUES (1), (2), (3), (4), (5);
SELECT * FROM a_table;
SELECT ; DELETE FROM a_table; * FROM a_table;
SELECT COUNT(*) FROM a_table;

This outputs:

mysql> SELECT * FROM a_table;
+----+
| id |
+----+
|  1 |
|  2 |
|  3 |
|  4 |
|  5 |
+----+
5 rows in set (0.00 sec)

mysql> SELECT ; DELETE FROM a_table; * FROM a_table;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
Query OK, 5 rows affected (0.03 sec)

mysql> SELECT * FROM a_table;
Empty set (0.00 sec)

Why does this SQL injection succeed despite the syntax error? Is this because MySQL parses and runs the DELETE query before the surrounding SELECT query? I don't plan to rely on such weak PHP code or MySQL syntax errors to guard against SQL injection, of course; this example just intrigued me.

like image 681
Ricardo Altamirano Avatar asked Aug 05 '26 17:08

Ricardo Altamirano


1 Answers

The queries are still run because mysql uses ; to delimit each query and it will continue running the queries even when there is a syntax error if you allow it to do so. Running the queries in SequelPro I get a message about the syntax error and it prompts me if I want to continue running all queries or stop. However, running them straight in MySQL commandline the queries continue running and MySQL just gives an error message and continues to the next query as expected (same thing that happens with the PHP code).

like image 142
Chris McKnight Avatar answered Aug 08 '26 12:08

Chris McKnight



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!