Mariadb 简明教程

MariaDB - SQL Injection Protection

接受用户输入这一简单的行为为利用者打开了方便之门。该问题主要源于对数据的逻辑管理,但幸运的是,避免这些主要缺陷相当容易。

The simple act of accepting user input opens the door to exploits. The problem stems primarily from the logical management of data, but luckily, it is fairly easy to avoid these major flaws.

SQL 注入的机会通常出现在用户输入名称等数据时,而代码逻辑无法分析此输入时。代码允许攻击者插入 MariaDB 语句,该语句将在数据库上运行。

Opportunities for SQL injection typically occur on users entering data like a name, and the code logic failing to analyze this input. The Code, instead, allows an attacker to insert a MariaDB statement, which will run on the database.

总是考虑由用户输入的数据,它们可能是可疑的,并且在任何处理之前都需要进行强有力的验证。通过模式匹配执行此验证。例如,如果期望的输入是用户名,请将输入的字符限制为字母数字字符和下划线以及一定的长度。查看下面给出的示例 -

Always consider data entered by users, suspect and are in need of strong validation prior to any processing. Perform this validation through pattern matching. For example, if the expected input is a username, restrict entered characters to alphanumeric chars and underscores, and to a certain length. Review an example given below −

if(check_match("/^\w{8,20}$/", $_GET['user_name'], $matches)) {
   $result = mysql_query("SELECT * FROM system_users WHERE user_name = $matches[0]");
} else {
   echo "Invalid username";
}

同样,在创建输入约束时利用 REGEXP 运算符和 LIKE 从句。

Also, utilize the REGEXP operator and LIKE clauses in creating input constraints.

考虑所有类型对输入的必要显性控制,例如 -

Consider all types of necessary explicit control of input such as −

  1. Control the escape characters used.

  2. Control the specific appropriate data types for input. Limit input to the necessary data type and size.

  3. Control the syntax of entered data. Do not allow anything outside of the needed pattern.

  4. Control the terms permitted. Blacklist SQL keywords.

您可能不知道注入攻击的危险,或者认为它们无关紧要,但它们位居安全问题之首。此外,考虑以下两个条目的效果 -

You may not know the dangers of injection attacks, or may consider them insignificant, but they top the list of security concerns. Furthermore, consider the effect of these two entries −

1=1
-or-
*

允许其中任何一个与正确命令一起输入的代码可能会导致揭示数据库上的所有用户数据或删除数据库上的所有数据,并且两种注入都不是特别聪明。在某些情况下,攻击者甚至不需要花时间检查漏洞;他们只需使用简单的输入执行盲目攻击。

Code allowing either of those to be entered along with the right command may result in revealing all user data on the database or deleting all data on the database, and neither injection is particularly clever. In some cases, attackers do not even spend time examining holes; they perform blind attacks with simple input.

同样,考虑任何编程/脚本语言(与 MariaDB 配对)提供的模式匹配和正则表达式工具,它们提供了更多的控制,有时会提供更好的控制。

Also, consider the pattern matching and regular expression tools provided by any programming/scripting language paired with MariaDB, which provide more control, and sometimes better control.