阅读这篇关于 EF Core 中 SQL 注入预防的有趣文章,我发现现在插值字符串可能会导致FormattableString
.
在 .NET Core 2.2 中运行此测试代码:
public static void Main()
{
var filter = "Mark'; DROP TABLE tbl; --";
Console.WriteLine(FromSql("SELECT * FROM tbl WHERE fld = '" + filter + "'"));
Console.WriteLine(FromSql($"SELECT * FROM tbl WHERE fld = {filter}"));
Console.WriteLine(FromSql(FormattableStringFactory.Create(
"SELECT * FROM tbl WHERE fld = {0}", filter)));
}
private static string FromSql(string sql) => sql;
private static string FromSql(FormattableString sql)
{
var formatArgs = sql.GetArguments();
for (var paramIndex = 0; paramIndex < sql.ArgumentCount; ++paramIndex)
formatArgs[paramIndex] = "@p" + paramIndex;
return sql.ToString();
}
没有达到我的预期:
SELECT * FROM tbl WHERE fld = 'Mark'; DROP TABLE tbl; --'
SELECT * FROM tbl WHERE fld = Mark'; DROP TABLE tbl; --
SELECT * FROM tbl WHERE fld = @p0
第二个打印应该像最后一个一样输出。
试试这是小提琴。
我错过了什么?