我有一个SQL请求,我需要将数据连接到请求中:
if (dataChoosen != "randomValue")
{
sCondition = " WHERE RandomField = '" + dataChoosen + "' ";
}
cd.CommandText = "SELECT xData FROM table " + sCondition + "GROUP BY xxx";
由于我需要连接条件,我认为我不能使用准备好的请求吗?
另外,我已经尝试使用'dataChoosed'值,因为它来自文本框,我需要一个整数。那么tryparse足以阻止SQL注入吗?
答案 0 :(得分:2)
我只是使用参数,没有理由不这样做。
if (dataChoosed != "randomValue")
{
sCondition = " WHERE RandomField = @dataChoosed ";
}
cd.CommandText = "SELECT xData FROM table " + sCondition + "GROUP BY xxx";
cd.Parameters.Add("@dataChoosed", SqlDbType.VarChar).Value = dateChoosed;
答案 1 :(得分:1)
不,您在安全方面不。即使dataChoosed
是一个无辜的整数值,坏男孩也会伤害你,比如负值格式:
// It's good old "-1", with a bit strange format
// (let use "delete from table commit;" as an injection)
string dataChoosed = "1'; delete from table commit; --1";
// A little hack: let "-" sign be...
CultureInfo hacked = new CultureInfo("en-US");
hacked.NumberFormat.NegativeSign = "1'; delete from table commit; --";
Thread.CurrentThread.CurrentCulture = hacked;
if (dataChoosed != "randomValue")
{
int v;
// since "1'; delete from table commit; --1" is of correct fotmat it will be parsed
if (int.TryParse(dataChoosed, out v))
sCondition = " WHERE RandomField = '" + dataChoosed + "' ";
}
cd.CommandText = "SELECT xData FROM table " + sCondition + "GROUP BY xxx";
而且,有点儿!我的桌子在哪里?命令文本将是
SELECT xData FROM table = '1'; delete from table commit; --1'GROUP BY xxx
这是两个查询:
SELECT xData FROM table = '1'; -- the innocent one
delete from table commit; -- an arbitrary query from the attacker
(我已删除注释掉 --1'GROUP BY xxx
片段)
请使用参数,不要诱惑我们。请注意,您不想更改代码:您只需更改Windows中的区域设置即可。
答案 2 :(得分:-2)
[BLANK]
是否可以防止sql注入?
除非[BLANK]
是'参数',否则答案始终为否。