阅读这篇有趣的文章关于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
第二个打印应该像最后一个一样输出。
试试这个 fiddle。
我错过了什么吗?
$
开头的字符串字面量实际上并没有构造一个FormattableString
类型的字符串 - 我猜编译器还没有跟上库的步伐。 - 500 - Internal Server Error