【问题标题】:Query causing sql injection issue导致sql注入问题的查询
【发布时间】:2023-02-03 21:27:13
【问题描述】:
Type entryEntityType = entry.Entity.GetType();
                string tableName = GetTableName(entryEntityType);
                string primaryKeyName = GetPrimaryKeyName(entryEntityType);
                string deletequery = string.Format("UPDATE {0} SET IsDeleted = 1 WHERE {1} = @id", tableName, primaryKeyName);         

Database.ExecuteSqlCommand(deletequery, new SqlParameter("@id", entry.OriginalValues[primaryKeyName]));

在运行上述查询的声纳扫描后,为 sql 注入提供了一个安全热点。如何处理?

【问题讨论】:

标签: c# sql entity-framework sqlcommand format-string


【解决方案1】:

看起来表名和主键名并不依赖于用户输入,所以我会抑制这段代码周围的声纳错误。如果你坚持要修复它,你可以这样做(伪代码):

Do once:
for all entity types
    generate SQL statement with right table name and primary key
    Add to dictionary with EntityType as key

When updating:
pick the right SQL from the dictionary using the EntityType.

正如我所说,我只会抑制错误。

【讨论】:

    【解决方案2】:

    您将未过滤的 tableName 和 primaryKeyName 放入 SQL 查询中。 如果其中一个字符串中有分号,则可以注入与您认为的不同的查询。虽然我不知道你从哪里拿走这些字符串。 修复 deletequery 的创建。

    string deletequery "UPDATE @tableName SET IsDeleted = 1 WHERE @primaryKeyname = @id"
    SqlCommand command = new SqlComand(deletequery);
    command.Parameters.Add("@tableName", SqlDbType.String);
    command.Parameters["@tableName"].Value = tableName;
    
    command.Parameters.Add("@primaryKeyname", SqlDbType.String);
    command.Parameters["@primaryKeyname"].Value = primaryKeyname;
    
    command.Parameters.Add("@id", SqlDbType.String);
    command.Parameters["@id"].Value = entry.OriginalValues[primaryKeyName];
    

    希望这可以帮助。

    【讨论】:

    • 我在执行 command.ExecuteNonQuery(); 时修改了与此类似的代码; ,它显示我错误声明@tablename 变量,虽然我已经如上所述声明它。请检查附上的屏幕截图
    • 您不能参数化表名和列名。难怪这不起作用。
    • 那么这样做的替代解决方案是什么?
    猜你喜欢
    • 2018-03-29
    • 2013-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-14
    • 1970-01-01
    • 2017-04-06
    • 2022-11-18
    相关资源
    最近更新 更多