简体   繁体   English

动态创建表时如何避免SQL注入风险?

[英]How to avoid SQL injection risk when creating table dynamically?

Here is simple procedure that creates table from user provided input: 这是从用户提供的输入创建表的简单过程:

PROCEDURE `hackProcedure`(
IN tab_name VARCHAR(63))
BEGIN

IF (tab_name REGEXP '^[A-Za-z0-9 ]+$')
THEN
    SET @StB = CONCAT('CREATE TABLE tab_name
                      (id INT(10) PRIMARY KEY NOT NULL UNIQUE AUTO_INCREMENT,
                      name VARCHAR(45),
                      guid VARCHAR(36));');
    PREPARE statementB FROM @StB;
    EXECUTE statementB;
    DEALLOCATE PREPARE statementB;
ELSE
    -- SIGNAL some error;
END IF;
#END

Before creating table I check that user input contains only alfa-numeric values, so to my understanding bad person trying to do an SQL injection on this procedure can not succeed because it is not possible to comment out the rest of the query nor add other columns. 在创建表之前,我检查用户输入是否仅包含字母数字值,因此据我所知,尝试对此过程进行SQL注入的坏人无法成功,因为无法注释掉其余查询或添加其他列。 Is this safe or I am missing someting? 这是安全的还是我缺少东西?

Its not vulnerable because the code you've shown us uses a literal value for the table name - not the parameter. 它不容易受到攻击,因为您显示给我们的代码对表名使用文字值-而不是参数。 I think you wanted to do this: 我认为您想这样做:

CONCAT('CREATE TABLE ',  tab_name, '
                  (id INT(10) PRIMARY KEY NOT NULL UNIQUE AUTO_INCREMENT,
                  name VARCHAR(45),
                  guid VARCHAR(36));');

Now, what if I call your function with... 现在,如果我用...调用函数呢?

dummy (id INT NOT NULL); DROP TABLE mysql.users; CREATE TABLE dummy2

?

It will fail because the semi-colon and brackets wull be rejected by the regex, but this is far from a robust solution. 由于分号和方括号将被正则表达式拒绝,因此它将失败,但这远不是一个可靠的解决方案。

Adding backtick quotes around the table name (as long as they are disallowed by the regex) is a slight improvement. 在表名周围添加反引号(只要正则表达式不允许),这是一个小改进。

 CONCAT('CREATE TABLE `',  tab_name, '`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM