为什么这个 SQL 注入会成功,即使 SQL 语句产生了语法错误? [英] Why does this SQL injection succeed even though the SQL statement produces a syntax error?

查看:47
本文介绍了为什么这个 SQL 注入会成功,即使 SQL 语句产生了语法错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题和一些评论中,这个输入:

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

$input = ';从表名中删除;#';

被建议作为一个 SQL 注入到这个 PHP 语句的例子:

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

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

我切入正题,直接用MySQL中的一个例子,虽然我用*代替#.结果是一样的.

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;

输出:

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)

为什么这个 SQL 注入会在语法错误的情况下成功?这是因为 MySQL 在周围的 SELECT 查询之前解析并运行 DELETE 查询吗?当然,我不打算依靠这种薄弱的 PHP 代码或 MySQL 语法错误来防范 SQL 注入;这个例子让我很感兴趣.

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.

推荐答案

查询仍在运行,因为 mysql 使用 ; 来分隔每个查询,即使有语法,它也会继续运行查询如果您允许它这样做,则会出错.在 SequelPro 中运行查询我收到一条关于语法错误的消息,它会提示我是继续运行所有查询还是停止.但是,直接在 MySQL 命令行中运行它们,查询会继续运行,而 MySQL 只会给出一条错误消息并按预期继续下一个查询(与 PHP 代码发生的情况相同).

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).

这篇关于为什么这个 SQL 注入会成功,即使 SQL 语句产生了语法错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆