是否可以在使用 Entity Framework 的应用程序上执行 SQL 注入?

Is it possible to perform a SQL Injection on a application that uses Entity Framework?

Entity Framework 可以被黑客入侵吗?

Is it possible to perform a SQL Injection on a application that uses EF?

如果是这样,有人可以提供一个完整的例子来说明如何做到这一点吗?我在 C# 中找不到任何特定于 EF 的内容。

取决于它的用途。 如果你使用 LINQ yes,它可以安全地防止 SQL 注入,因为它通过 SQL 参数将所有数据传递到数据库。 LINQ 查询不是通过使用字符串操作或连接组成的,这就是它们不易受到传统 SQL 注入攻击的原因。

注意这个:

It is quite easily possible if the developer uses EF as a wrapper around ADO.NET and uses FromSQL. Of course, this is not the intended nor normal use of EF, but I have seen it – Camilo Terevinto

REF:Raw SQL Queries


此外,虽然不是真的 "sql injection",但由于这样做的目的之一是通过改变原始数据 sql 来稍微改变您的数据以产生一些意想不到的结果,您还应该注意ASP.NET - Overposting/Mass Assignment Model Binding Security

样本直接取自 link:

你model/class:

public class Person
{
    public int ID { get; set; }
    public string First { get; set; }
    public string Last { get; set; }
    public bool IsAdmin { get; set; }
}

在你的某处 Controller:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Person person)
{
    if (ModelState.IsValid)
    {
        _context.Add(person);
        await _context.SaveChangesAsync();
        return RedirectToAction("Index");
    }
    return View(person);
}

If a theoretical EvilUser found out that Person had an "IsAdmin" property, they could "overpost" and add a field to the HTTP POST and set IsAdmin=true. There's nothing in the code here to prevent that.

所以 "evil user" 甚至不需要弄清楚 sql injection 来做一些意想不到的结果。阅读有关预防方法的文章(例如 BindAttribute,查看模型)。

Hth.