为什么使用参数化查询或实体框架可以防止SQL注入? [英] Why does using parameterized queries or entity framework prevent sql injection?
问题描述
我对SQL注入有很好的了解。就是这样的SQL查询,应该是这样的:
SELECT名,姓
来自客户
WHERE CustomerId = @valueFromApplication
变成查询
从客户
中选择名字,姓氏
WHERE CustomerId =''; DROP DATABASE Foo-
当用户在您的应用程序,网站,客户端等中插入恶意值时..我也知道,攻击者不仅可以删除数据库,还可以尝试发现表的名称并从中获取信息。
我也知道一些防止这种情况发生的方法是:
- 使用带有参数的存储过程(SQL Server)
- 使用参数化的SQL查询
- 对实体使用Entity Framework / LINQ(C#,也许是F#?)
<这些事情实际上如何阻止SQL注入的发生?为什么攻击者不能仅仅将相同的恶意值传递给他或她已经在使用的任何输入,并获得相同的结果。
您的第一个示例已参数化,并且不容易受到SQL注入的攻击。</ p>
服务器并不会简单地将参数化查询替换为值(就像您可能会手动替换 @var
的值为
)。使用 @valueFromApplication
发送和接收它们。
服务器将解析查询..当到达变量时,它将查找提供的值。如果该值为'’; DROP DATABASE Foo-
..然后成为它使用的值。它不会解析它..它只是将其用作文本/数字/无论其类型是什么。
要添加有关Entity Framework的信息,它内部使用了参数化查询,因此还是SQL注入安全的。
I've got a good grasp on SQL injection. It's when a SQL query that is supposed to be something like
SELECT FirstName, LastName
FROM Customers
WHERE CustomerId = @valueFromApplication
Gets turned into a query like
SELECT FirstName, LastName
FROM Customers
WHERE CustomerId = '' ; DROP DATABASE Foo --
When the user inserts a malicious value into your app, website, client, whatever.. I'm also aware that instead of just dropping the DB the attacker can try to discover the names of tables and get info out of them.
I also know some things that help prevent this are:
- Using stored procedures which take parameters (SQL Server)
- Using parametrized SQL queries
- Using Entity Framework / LINQ to Entities (C#, maybe F#?)
How do these things actually prevent SQL injection from occurring? Why can't the attacker just pass the same malicious value into whatever input he or she is already using and have the same result.
Your first example is parameterised and is not vulnerable to SQL injection.
Parameterised queries aren't simply replaced by the server with values (like you might do manually replacing @var
with value
). They are sent and received exactly as you sent it.. with @valueFromApplication
.
The server will parse the query.. and when it gets to a variable it will look up the value supplied. If that value is '' ; DROP DATABASE Foo --
.. then that becomes the value it uses. It doesn't parse that.. it just uses it as text/number/whatever type it is.
To add about Entity Framework, it internally uses Parameterised query so it is also SQL injection safe.
这篇关于为什么使用参数化查询或实体框架可以防止SQL注入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!