我想知道 fromSqlRaw 方法有多安全。我在代码中执行以下操作,其中人员 ID 是方法本身的参数:
string sql = String.Format("SELECT * FROM [users].[user] WHERE Id LIKE {0}", id)
var list = this.context.Person.FromSqlRaw<Person>(sql).ToList();
此代码对于 SQL 注入(inject)安全吗?使用此功能时我还应该了解其他安全漏洞吗?
最佳答案
对您的输入使用适当的参数化。
经过评论澄清,看来你的参数是用户输入的字符串,这为注入(inject)攻击打开了大门。
通常,您可以创建一个SqlCommand
,并提供一些SqlParameter
就在其中。
在 EFCore 中,FromSqlRaw
和 FromSqlInterpolated
(在 3.0 中,替换 EFCore < 3.0 中的 FromSql
)允许您缩短此语法,请参阅documentation .
string sql = "SELECT * FROM [users].[user] WHERE Id LIKE {0}"
var list = this.context.Person.FromSqlRaw<Person>(sql, "42")
请注意,这看起来与您在问题中所做的非常相似...但文档中清楚地强调了差异:
Warning
Always use parameterization for raw SQL queries
When introducing any user-provided values into a raw SQL query, care must be taken to avoid SQL injection attacks. In addition to validating that such values don't contain invalid characters, always use parameterization which sends the values separate from the SQL text.
In particular, never pass a concatenated or interpolated string ($"") with non-validated user-provided values into FromSqlRaw or ExecuteSqlRaw. The FromSqlInterpolated and ExecuteSqlInterpolated methods allow using string interpolation syntax in a way that protects against SQL injection attacks.
事实上,在您的情况下,字符串首先被插入为字符串(没有任何健全性检查),然后按原样执行。
FromSqlRaw
不知道“Id”部分来自参数。
关于sql - FromSqlRaw注入(inject)EF Core 3.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63226271/