https://www.owasp.org/index.php/SQL_Injection
Overview
A SQL injection attack consists of insertion or "injection" of a SQL query via the input data from the client to the application. A successful SQL injection exploit can read sensitive data from the database, modify database data (Insert/Update/Delete), execute administration operations on the database (such as shutdown the DBMS), recover the content of a given file present on the DBMS file system and in some cases issue commands to the operating system. SQL injection attacks are a type of injection attack, in which SQL commands are injected into data-plane input in order to effect the execution of predefined SQL commands.
SQL注入攻击指包含有输入数据插入或者注入的SQL查询,这些输入数据由客户端传至应用程序。成功的SQL注入能够从数据库读取敏感数据、修改(插入/更新/删除)数据库数据、在数据库上执行管理员操作(如关闭DBMS),恢复DBMS文件系统上的指定文件的内容甚至有时向操作系统发送命令。SQL注入攻击是一种注入攻击,为了影响已定义的SQL命令的执行,SQL注入攻击时,SQL命令常常插入输入数据中。
Threat Modeling
- SQL injection attacks allow attackers to spoof identity, tamper with existing data, cause repudiation issues such as voiding transactions or changing balances, allow the complete disclosure of all data on the system, destroy the data or make it otherwise unavailable, and become administrators of the database server.
- SQL注入攻击可以使攻击者伪造身份,篡改已有数据,造成抵赖问题(如交易的有效性或者公平性),泄露系统上所有的数据,毁坏数据或使其失效不可用,甚至使攻击者成为数据库服务器的管理员。
- SQL Injection is very common with PHP and ASP applications due to the prevalence of older functional interfaces. Due to the nature of programmatic interfaces available, J2EE and ASP.NET applications are less likely to have easily exploited SQL injections.
- SQL注入攻击常见于PHP和ASP应用程序中,因为具有问题的旧版函数接口的存在。因为编程式接口的特点,J2EE和ASP.NET应用程序很难被用于SQL注入攻击。
- The severity of SQL Injection attacks is limited by the attacker’s skill and imagination, and to a lesser extent, defense in depth countermeasures, such as low privilege connections to the database server and so on. In general, consider SQL Injection a high impact severity.
- SQL注入攻击的严重程度受限于攻击者的技能和想象力,并在很小的程度上受限于深度防御策略(如使用低权限连接数据库等)。一般,认为SQL注入是一种影响程度严重的攻击方式。
Related Security Activities
How to Avoid SQL Injection Vulnerabilities
See the OWASP Guide article on how to Avoid SQL Injection Vulnerabilities.
See the OWASP SQL Injection Prevention Cheat Sheet.
See the OWASP Query Parameterization Cheat Sheet.
How to Review Code for SQL Injection Vulnerabilities
See the OWASP Code Review Guide article on how to Review Code for SQL Injection Vulnerabilities.
How to Test for SQL Injection Vulnerabilities
See the OWASP Testing Guide article on how to Test for SQL Injection Vulnerabilities.
Description
SQL injection errors occur when:
- Data enters a program from an untrusted source.
- The data used to dynamically construct a SQL query
SQL注入错误发生在:1)程序的输入数据来自不可信的数据源 2)输入数据用于构造SQl查询语句
The main consequences are:
主要影响有:
- Confidentiality: Since SQL databases generally hold sensitive data, loss of confidentiality is a frequent problem with SQL Injection vulnerabilities.
- 机密性:因为SQL数据库常常存储敏感数据,所以因SQL注入漏洞使机密性受损常常发生。
- Authentication: If poor SQL commands are used to check user names and passwords, it may be possible to connect to a system as another user with no previous knowledge of the password.
- 身份验证:如果使用低劣的SQL语句对用户名和密码进行验证,可能会导致没有密码的其他用户(如注册用户使用别人的账户或者非注册用户等等)连接系统。
- Authorization: If authorization information is held in a SQL database, it may be possible to change this information through the successful exploitation of a SQL Injection vulnerability.
- 授权:如果授权信息存储在SQl数据库中,可能出现通过SQL注入漏洞改变授权信息的问题。
- Integrity: Just as it may be possible to read sensitive information, it is also possible to make changes or even delete this information with a SQL Injection attack.
- 完整性:正如可能会读取敏感信息一样,通过SQL注入攻击可以改变或者删除信息。
Risk Factors
The platform affected can be:
可能影响的平台:
- Language: SQL
- SQL语言
- Platform: Any (requires interaction with a SQL database)
- 与一个SQL数据库交互的任何平台
SQL Injection has become a common issue with database-driven web sites. The flaw is easily detected, and easily exploited, and as such, any site or software package with even a minimal user base is likely to be subject to an attempted attack of this kind.
SQL注入已经成为基于数据库的网站的一个普遍问题。因为该问题容易被检测和利用,所以任何即使拥有很小的用户群的网站或者软件都可能遭受SQL注入的尝试攻击。
Essentially, the attack is accomplished by placing a meta character into data input to then place SQL commands in the control plane, which did not exist there before. This flaw depends on the fact that SQL makes no real distinction between the control and data planes.
从根本上说,该攻击在数据输入时输入一个SQL命令中不存在的元字符并传输至SQL命令中来实现的。该问题依赖于SQL没有区分控制面和数据面。
Examples
Example 1
当用户输入中含有单引号时的处理。
In SQL:
select id, firstname, lastname from authors
If one provided:
Firstname: evil'ex Lastname: Newman
the query string becomes:
select id, firstname, lastname from authors where forename = 'evil'ex' and surname ='newman'
which the database attempts to run as:
Incorrect syntax near il' as the database tried to execute evil.
A safe version of the above SQL statement could be coded in Java as:
String firstname = req.getParameter("firstname"); String lastname = req.getParameter("lastname"); // FIXME: do your own validation to detect attacks String query = "SELECT id, firstname, lastname FROM authors WHERE forename = ? and surname = ?"; PreparedStatement pstmt = connection.prepareStatement( query ); pstmt.setString( 1, firstname ); pstmt.setString( 2, lastname ); try { ResultSet results = pstmt.execute( ); }
Example 2
The following C# code dynamically constructs and executes a SQL query that searches for items matching a specified name. The query restricts the items displayed to those where owner matches the user name of the currently-authenticated user.
下面的C#动态构造并执行SQL查询语句以实现对某个特定名字的搜索。该查询显示属于当前授权用户的信息。
... string userName = ctx.getAuthenticatedUserName(); string query = "SELECT * FROM items WHERE owner = "'" + userName + "' AND itemname = '" + ItemName.Text + "'"; sda = new SqlDataAdapter(query, conn); DataTable dt = new DataTable(); sda.Fill(dt); ...
The query that this code intends to execute follows:
SELECT * FROM items WHERE owner = AND itemname = ;
However, because the query is constructed dynamically by concatenating a constant base query string and a user input string, the query only behaves correctly if itemName does not contain a single-quote character. If an attacker with the user name wiley enters the string "name' OR 'a'='a" for itemName, then the query becomes the following:
但是,由于将一个查询字符串和一个用户输入字符串连接起来构成查询语句,该查询只有当itemName中没有单引号时才能准确执行。如果攻击者使用owner为wiley和itemName为"name' OR 'a'='a",那么查询语句就会变为:
SELECT * FROM items WHERE owner = 'wiley' AND itemname = 'name' OR 'a'='a';
The addition of the OR 'a'='a' condition causes the where clause to always evaluate to true, so the query becomes logically equivalent to the much simpler query:
由于OR 'a'='a'的存在使where条件始终为true,所以该查询等价于:
SELECT * FROM items;
This simplification of the query allows the attacker to bypass the requirement that the query only return items owned by the authenticated user; the query now returns all entries stored in the items table, regardless of their specified owner.
那么该查询就使攻击者绕过了查询仅返回授权用户拥有的信息的限制,返回items表中的所有信息。
Example 3
This example examines the effects of a different malicious value passed to the query constructed and executed in Example 1. If an attacker with the user name hacker enters the string "hacker'); DELETE FROM items; --" for itemName, then the query becomes the following two queries:
在第二个例子的基础上,如果攻击者使用ower为hacker itemname为"name';delete from items;",那么查询语句就会成为下面两个查询语句:
SELECT * FROM items WHERE owner = 'hacker' AND itemname = 'name'; DELETE FROM items; --'
Many database servers, including Microsoft® SQL Server 2000, allow multiple SQL statements separated by semicolons to be executed at once. While this attack string results in an error in Oracle and other database servers that do not allow the batch-execution of statements separated by semicolons, in databases that do allow batch execution, this type of attack allows the attacker to execute arbitrary commands against the database.
包括Microsoft® SQL Server 2000在内的很多数据库服务器允许一次执行使用分号分隔的多个SQL语句。Oracle和其他不允许以分号分隔进行批量执行的数据库服务器会返回错误,在这些不允许批量执行的数据库中,攻击者可以使用任意的字符攻击数据库。
Notice the trailing pair of hyphens (--), which specifies to most database servers that the remainder of the statement is to be treated as a comment and not executed. In this case the comment character serves to remove the trailing single-quote left over from the modified query. In a database where comments are not allowed to be used in this way, the general attack could still be made effective using a trick similar to the one shown in Example 1. If an attacker enters the string "name'); DELETE FROM items; SELECT * FROM items WHERE 'a'='a", the following three valid statements will be created:
注意上面例子中的双连字符(--),在大多数数据库中被当做注释,不会被执行。在这个例子中注释符可以移除SQL语句中的单引号,如果用户输入"name';delete from items;select * from items where 'a'='a',就会创建下面三个有效的sql语句:
SELECT * FROM items WHERE owner = 'hacker' AND itemname = 'name'; DELETE FROM items; SELECT * FROM items WHERE 'a'='a';
One traditional approach to preventing SQL injection attacks is to handle them as an input validation problem and either accept only characters from a whitelist of safe values or identify and escape a blacklist of potentially malicious values. Whitelisting can be a very effective means of enforcing strict input validation rules, but parameterized SQL statements require less maintenance and can offer more guarantees with respect to security. As is almost always the case, blacklisting is riddled with loopholes that make it ineffective at preventing SQL injection attacks. For example, attackers can:
传统的防止SQL注入攻击的方法是进行输入验证或者仅接受安全值列表中的数据并且根据黑名单过滤可能的恶意值。通过严格的强制性的输入验证规则白名单可以起到较好的效果,但是参数化的SQL语句应该需要较小的维护并可以提供安全保障。黑名单常常存在漏洞使其不能有效的阻止SQL注入攻击。例如,攻击者可以:
- Target fields that are not quoted
- 目标域不被引用(??)
- Find ways to bypass the need for certain escaped meta-characters
- 寻找绕过某些过滤字符的方法
- Use stored procedures to hide the injected meta-characters
- 使用存储程序隐藏注入的元字符
Manually escaping characters in input to SQL queries can help, but it will not make your application secure from SQL injection attacks.
人工的过滤一些输入至sql查询的字符可以帮助减少可能的SQL注入攻击,但是不能保证绝对的安全。
Another solution commonly proposed for dealing with SQL injection attacks is to use stored procedures. Although stored procedures prevent some types of SQL injection attacks, they fail to protect against many others. For example, the following PL/SQL procedure is vulnerable to the same SQL injection attack shown in the first example.
一个较为常见的应对SQL注入攻击的方法是使用存储程序。虽然存储程序可以防止一些类型的SQL注入攻击,但是它也有很多不能应对的情况,如下面的PL/SQL程序就不能应付第二个例子中的SQL注入攻击:
procedure get_item ( itm_cv IN OUT ItmCurTyp, usr in varchar2, itm in varchar2) is open itm_cv for ' SELECT * FROM items WHERE ' || 'owner = '''|| usr || ' AND itemname = ''' || itm || ''''; end get_item;
Stored procedures typically help prevent SQL injection attacks by limiting the types of statements that can be passed to their parameters. However, there are many ways around the limitations and many interesting statements that can still be passed to stored procedures. Again, stored procedures can prevent some exploits, but they will not make your application secure against SQL injection attacks.
存储式程序常常通过限制可以传入的参数的数据类型来防止SQL注入攻击。但是,存在很多方法可以绕过这些限制,并将一些SQL语句传至存储式程序。再次强调,存储式程序可以防止一些利用,但是不能保证你的程序免受SQL注入攻击。
Related Threat Agents
Related Attacks
Related Vulnerabilities
Related Controls
References
- SQL Injection Knowledge Base - A reference guide for MySQL, MSSQL and Oracle SQL Injection attacks.
- GreenSQL Open Source SQL Injection Filter - An Open Source database firewall used to protect databases from SQL injection attacks.
- An Introduction to SQL Injection Attacks for Oracle Developers - This also includes recommended defenses.
- OWASP SQLiX Project - An SQL Injection Scanner.
- Pangolin - Closed source SQL Injection Scanner.