简体   繁体   English

使用SQL注入的存储过程

[英]Stored Procedure with SQL Injection

I want to create a Stored Procedure that takes the IDs as inputs, and depending on the list of IDs will behave accordingly. 我想创建一个将ID作为输入的存储过程,并且根据ID的列表将相应地执行操作。

Example: 例:

DROP PROCEDURE IF EXISTS sp_G;
DELIMITER ;;
CREATE PROCEDURE sp_G (
    IN  IDs VARCHAR(20) -- Example: '1, 2, 3'
    )
BEGIN
    SET @Query='SELECT * FROM table_users as t';

    IF IDs!=NULL
    THEN
        SET @Query=CONCAT(@Query, ' WHERE t.ID in(', IDs, ')'); -- SQL Injection problem
    END IF;

    PREPARE stmt FROM @Query;
    EXECUTE stmt;

END ;;
DELIMITER ;

It happens that I have SQL injection in the 'CONCAT', because I can't use the ' EXECUTE stmt USING ' IDs as is indicated on the following link: http://dev.mysql.com/doc/refman/5.7/en/sql-syntax-prepared-statements.html 碰巧我在'CONCAT'中进行了SQL注入,因为我不能按照以下链接所示使用' EXECUTE stmt USING'IDhttp : //dev.mysql.com/doc/refman/5.7/ zh / sql-syntax-prepared-statements.html

As the IDs parameter is optional, it will only influence the query when is not NULL. 由于IDs参数是可选的,因此仅当非NULL时,它将影响查询。 However, according to the documentation we assume that this ID parameter will always exist. 但是,根据文档,我们假定此ID参数将始终存在。 If IDs parameter has SQL injection, will be executed. 如果IDs参数具有SQL注入,将被执行。 Can someone help me? 有人能帮我吗? Thanks in advance. 提前致谢。

You can use a regular expression match to check that the parameter only contains allowed characters. 您可以使用正则表达式匹配来检查参数是否仅包含允许的字符。

IF IDs IS NOT NULL AND IDs RLIKE '^[0-9, ]+$'
THEN
    SET @Query=CONCAT(@Query, ' WHERE t.ID in(', IDs, ')');
END IF

This works for a simple parameter like a list of IDs. 这适用于简单的参数,例如ID列表。 It doesn't generalize to more complicated situations, though. 但是,它不能推广到更复杂的情况。 The best solution is to design your application so you don't need to substitute user-provided input into the queries in the first place. 最好的解决方案是设计您的应用程序,这样一来,您就无需在一开始就将用户提供的输入替换为查询。

For instance, instead of a procedure that takes a comma-separated list of values to match against, the caller could put the information in a temporary table. 例如,调用程序可以将信息放在临时表中,而不是使用逗号分隔的值列表进行匹配的过程。 Then the query would be 然后查询将是

SELECT u.* FROM table_users AS u
JOIN temp_table AS t ON u.id = t.id

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

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