【问题标题】:EntitySQL and SQL injectionEntitySQL 和 SQL 注入
【发布时间】:2012-01-31 07:48:34
【问题描述】:

我有以下查询字符串

"SELECT VALUE entity FROM Entities AS entity WHERE entity.Client_id
= 0 && entity.Name LIKE @searchvalue ORDER BY @sorting SKIP @skip LIMIT @limit"

使用以下参数替换

query.Parameters.Add(new ObjectParameter("skip", start));
query.Parameters.Add(new ObjectParameter("limit", limit));
query.Parameters.Add(new ObjectParameter("searchvalue", searchValue + "%"));
query.Parameters.Add(new ObjectParameter("sorting", sortField + " " + sortDirection.ToUpper()));

但我总是以异常告终:

键表达式“ORDER BY”必须至少有一个引用 立即输入范围。近 ORDER BY 子句项

我猜这是因为query.Parameters.Add(...) 全部用引号括起来?我还阅读了this,但是如果什么都没有发生,我需要query.Parameters.Add(...) 有什么好处?好吧,攻击者可能不会开始新的查询,但我猜他可以操纵当前?

【问题讨论】:

  • 不熟悉entity-sql,但我猜是的,它认为,例如fieldname asc 是您想要的字段的名称。您可以尝试使用... ORDER BY @sortfield @sortdir ... 并使用两个参数吗?

标签: c# entity-framework sql-injection entity-sql


【解决方案1】:

猜测: 我会尝试做这样的第一件事

SELECT VALUE entity FROM Entities AS entity WHERE entity.Client_id = 0 && entity.Name LIKE '@searchvalue' ORDER BY @sorting @sortorder SKIP @skip LIMIT @limit

query.Parameters.Add(new ObjectParameter("searchvalue", searchValue + "%"));
query.Parameters.Add(new ObjectParameter("sorting",   sortField ));
query.Parameters.Add(new ObjectParameter("sortorder", sortDirection));

换句话说:将排序顺序移动到单独的参数。

编辑

如果这不起作用,请使用Query Builder 构造查询。

例如看here

祝你好运。

【讨论】:

  • 那是我最初的...所以不,这会导致同样的错误
  • @sra:好的,所以当你不能这样做时,这可能是最坏的情况。但是应该可以使用 ObjectQuery builder。看here
  • 这就是答案!您应该将其复制到答案的底部。
【解决方案2】:

已尝试删除引号 @searchvalue,因为您使用的是参数化查询 IMO,因此不再需要引号。

代替:

"SELECT VALUE entity FROM Entities AS entity WHERE entity.Client_id
= 0 && entity.Name LIKE '@searchvalue' ORDER BY @sorting SKIP @skip LIMIT @limit"

试试这个:

"SELECT VALUE entity FROM Entities AS entity WHERE entity.Client_id
= 0 && entity.Name LIKE @searchvalue ORDER BY @sorting SKIP @skip LIMIT @limit"

【讨论】:

  • 我忘记了这些,你说得对。但尽管如此,这不是我的错误......我已经在我的帖子中解决了这个问题。但是参数化查询会自动报价吗?
  • 它会在必要时自动应用引号(例如在使用字符串时)。无需将参数括在引号中。
【解决方案3】:

您不能使用参数作为列名的替换。

【讨论】:

    猜你喜欢
    • 2021-06-06
    • 2012-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-02
    • 1970-01-01
    • 2017-07-26
    相关资源
    最近更新 更多