sql 注入攻击是否仅对具有表单的页面构成威胁? [英] Are sql injection attacks only a threat on a page that has a form?
问题描述
我知道这是一个简单的问题,但在我阅读的所有内容中,我从未见过具体说明这一点.
I know it's a simple question, but in everything I've read, I've never seen this spelled out specifically.
如果在页面上进行查询,是否需要担心 SQL 注入攻击?还是只有当你要求用户输入时才出现问题?
If you do a query on a page, do you need to worry about SQL injection attacks? Or is it only a problem when you ask the user for input?
谢谢!
推荐答案
您不必拥有用户输入即可遭受 SQL 注入攻击.
You don't have to have user input to suffer a SQL injection attack.
假设您有一个使用如下 URL 调用的产品页面:
Let's say you have a product page that is called using a URL such as this:
product.aspx?ID=123
在你的代码中,你有一个这样构造的查询:
And in your code you have a query constructed such as this:
string sql = "SELECT * FROM Products WHERE ID = " + Request.Querystring["ID"];
有人可以使用此网址调用您的网页:
Someone could call your page with this url:
product.aspx?ID=123;DROP Table Students;
呸,你刚刚好.
除了可以通过用户、查询字符串、帖子、cookie、浏览器变量等传入的任何内容之外,我认为始终使用参数是一种很好的做法,即使您的代码中有文字也是如此.例如:
In addition to ANYTHING that can be passed in via a user, querystring, post, cookie, browser variable, etc. I think it is just good practice to always use parameters, even if you have the literals in your code. For example:
if(SomeCondition)
{
sql = "Select * from myTable where someCol = 'foo'";
}
else
{
sql = "Select * from myTable where someCol = 'bar'";
}
这可能是注入安全的,但您的 RDBMS 会将它们缓存为两个不同的查询.如果你修改它:
this may be injection safe, but your RDBMS will cache them as two different queries. if you modiy it to this:
sql = "Select * from myTable where someCol = @myParam";
if(SomeCondition)
{
myCommand.Parameters.Add("@myParam").value = "foo";
}
else
{
myCommand.Parameters.Add("@myParam").value = "bar";
}
您获得了相同的结果,但 RDBMS 只会将其缓存为一个查询,并在运行时替换参数.我使用它作为总是使用参数化查询的经验法则,只是为了保持一致,更不用说缓存的轻微改进.
You achieve the same result but the RDBMS will only cache it as one query, substituting the parameter at runtime. I use it as a rule of thumb to ALWAYS use parameterized queries, just to keep things consistent, not to mention a slight cache improvement.
这篇关于sql 注入攻击是否仅对具有表单的页面构成威胁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!