Java PreparedStatement 是否避免了 SQL 注入?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4333015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Does the preparedStatement avoid SQL injection?
提问by Mohamed Saligh
I have read and tried to inject vulnerable sql queries to my application. It is not safe enough. I am simply using the Statement Connection for database validations and other insertion operations.
我已阅读并尝试将易受攻击的 sql 查询注入到我的应用程序中。它不够安全。我只是将语句连接用于数据库验证和其他插入操作。
Is the preparedStatements safe? and moreover will there be any problem with this statement too?
PreparedStatement 安全吗?而且这个说法也会有问题吗?
采纳答案by darioo
Using string concatenation for constructing your query from arbitrary input will not make PreparedStatement
safe. Take a look at this example:
使用字符串连接从任意输入构造查询不会PreparedStatement
安全。看看这个例子:
preparedStatement = "SELECT * FROM users WHERE name = '" + userName + "';";
If somebody puts
如果有人放
' or '1'='1
as userName
, your PreparedStatement
will be vulnerable to SQL injection, since that query will be executed on database as
因为userName
,您PreparedStatement
将容易受到 SQL 注入的影响,因为该查询将在数据库上执行
SELECT * FROM users WHERE name = '' OR '1'='1';
So, if you use
所以,如果你使用
preparedStatement = "SELECT * FROM users WHERE name = ?";
preparedStatement.setString(1, userName);
you will be safe.
你会安全的。
Some of this code taken from this Wikipedia article.
部分代码取自这篇 Wikipedia 文章。
回答by pts
The prepared statement, if used properly, does protect against SQL injection. But please post a code example to your question, so we can see if you are using it properly.
如果使用得当,准备好的语句确实可以防止 SQL 注入。但是请针对您的问题发布代码示例,以便我们查看您是否正确使用它。
回答by Petar Minchev
回答by Vlad Mihalcea
As explained in this article, the PreparedStatement
alone does not help you if you are still concatenating Strings.
如本文所述,PreparedStatement
如果您仍在连接字符串,则单独使用它对您没有帮助。
For instance, one rogue attacker can still do the following:
例如,一个流氓攻击者仍然可以执行以下操作:
- call a sleep function so that all your database connections will be busy, therefore making your application unavailable
- extracting sensitive data from the DB
- bypassing the user authentication
- 调用 sleep 函数,以便您的所有数据库连接都处于忙碌状态,从而使您的应用程序不可用
- 从数据库中提取敏感数据
- 绕过用户认证
And it's not just SQL that can b affected. Even JPQL can be compromised if you are not using bind parameters.
不仅仅是 SQL 会受到影响。如果您不使用绑定参数,甚至 JPQL 也会受到损害。
Bottom line, you should never use string concatenation when building SQL statements. Use a dedicated API for that purpose:
最重要的是,在构建 SQL 语句时,永远不要使用字符串连接。为此使用专用 API: