使用参数化 SqlCommand 是否可以使我的程序免受 SQL 注入的影响?
我知道SQL 注入相当危险。现在,在我的 C# 代码中,我使用 编写参数化查询SqlCommand
类:
SqlCommand command = ...;
command.CommandText = "SELECT * FROM Jobs WHERE JobId = @JobId;";
command.Parameters.Add("@JobId", SqlDbType.UniqueIdentifier ).Value = actualGuid;
command.ExecuteNonQuery();
这会自动使我的代码免受 SQL 注入的影响吗?我需要做一些额外的事情吗?
I'm aware that SQL injection is rather dangerous. Now in my C# code I compose parameterized queries with SqlCommand
class:
SqlCommand command = ...;
command.CommandText = "SELECT * FROM Jobs WHERE JobId = @JobId;";
command.Parameters.Add("@JobId", SqlDbType.UniqueIdentifier ).Value = actualGuid;
command.ExecuteNonQuery();
Will this automatically make my code immune to SQL injection? Do I have to do something extra?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我想说,对于参数化查询的特定且可能规范的示例,是的,这已经足够了。
然而,人们有时会编写这样的代码,
因为根本没有办法将表名本身作为参数传递,并且有时存在这样做的愿望 - 无论是否被误导。似乎经常被忽视的是,tableName(除非可能只从一组不从任何输入派生的静态/常量值中读取)确实允许 SQL 注入。
I'd say for your particular, and probably canonical, example for parametrized queries, yes it is sufficient.
However, people sometimes write code like this
because there is simply no way to pass the tablename itself as a parameter and the desire to do exists sometimes - misguided or not. It seems it is then often overlooked, that tableName (unless maybe only read from a set of static/constant values that do not derive from any input) indeed allows for SQL injection.
根据这篇 MSDN 文章的注释,“特殊输入字符仅对动态 SQL 构成威胁,而在使用参数化 SQL 时则不会。”
所以我相信你可以安全地抵御 SQL 注入。在 URL 中使用标识符(例如身份值)时可能会存在一些逻辑风险,但这是另一回事了。
According to the Note on this MSDN Article, "Special input characters pose a threat only with dynamic SQL and not when using parameterized SQL."
So I believe you are safe against SQL Injection. There might be some logical risks when using Identifiers like Idendity Values in your URLs but this is another story.
SQL注入主要依赖于动态SQL的执行。换句话说,SQL 语句是由 SQL 与用户输入的值串联而成的。
为了完全避免 SQL 注入,
来自 MSDN
SQL Injection is mostly dependent on execution of dynamic SQL. In other words, SQL statements constructed by the concatenation of SQL with user-entered values.
To avoid SQL Injection completely,
From MSDN
使用 SqlCommand 是一个非常好的实践,只要您不在任何地方连接 SQL 字符串(包括在您调用的任何存储过程中——即避免动态 SQL),您就可以免受 SQL 注入攻击。
Using SqlCommand a very good practice and as long as you don't concatenate SQL strings anywhere (including inside any stored procedures you call -- i.e. avoid dynamic SQL), you will be immune from SQL injection attacks.
如果您使用动态 SQL,即使您通过参数传递它,也无法免受 SQL 注入的影响。可惜 SQL Server 没有内置函数来清理参数
You are not immune to SQL injection if you use dynamic sql, even if you are passing it through parameters. Too bad SQL Server doesn't have a built in function to sanitize parameters