c# – 扩展类型安全性以防止脏数据被用于需要“干净”数据的函数

前端之家收集整理的这篇文章主要介绍了c# – 扩展类型安全性以防止脏数据被用于需要“干净”数据的函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
.NET或其中一种语言是否可以强制清除不受信任的数据……或防止在错误的位置意外变量使用?

其中一个例子是在sql事务中使用用户POST的数据和“原始”响应.这可能会导致从客户端脚本漏洞到整个服务器受到攻击的任何问题.

另一个例子是我必须将数据传递给COM对象以进行进一步处理.

作为C#,ASP.net和sql开发人员,我有什么选择来确保我的用户的脏位在清理之前不会触及任何内部的东西?我可以利用运行时(或编译器)的功能吗?

如果没有语言实际执行它,也许我只能在我的传入变量中添加_dirty的后缀.这是你推荐的最佳做法吗?

专业人士如何解决这个问题?

更新

这是我要去的概念方向

根据目前给出的答案(特别是SteveCzetty和Erlend),这有点启发

例如:

  1. public Interface ICleanForJavascript { bool IsCleanForJavascript(); }
  2.  
  3. public Interface ICleanForXSS { bool IsCleanForJavascript(); }
  4.  
  5. public class DirtyData
  6. {
  7. string Name {get; set;}
  8. }
  9.  
  10. public class CleanData
  11. {
  12. private CleanData() {}
  13. string Name {get; private set;}
  14.  
  15.  
  16. // Perhaps use casting to support the conversion from Dirty to Clean data
  17. // Might use this in an option explicit DirtyData CleanData(object o); command
  18. public static CleanData Validate(DirtyData d)
  19. {
  20. CleanData data = new CleanData();
  21. if (ValidateString(d.Name))
  22. {
  23. data.Name = d.Name
  24. }
  25. else
  26. {
  27. throw new ValidationException();
  28. }
  29. return CleanData;
  30. }
  31. }
  32.  
  33. [RequiresCleanedDataAttribute(ICleanForJavascript )]
  34. public void DoSomething(CleanData data)
  35. {
  36. //...
  37. }
  38.  
  39. Attribute RequiresCleanedDataAttribute(object arrayOfCleanings[])
  40. {
  41. // do some reflection on the method signature and see if the object supports the required interfaces
  42. }

有了上述,那么:

  1. DoSomething(new DirtyData()); // Compiler Error,or runtime error if Attribute validation fails
  2. DoSomething(CleanData.Validate(new DirtyData())); // Compiles

解决方法

Can .NET or one of it’s many languages enforce the cleaning of untrusted data

是的它可以,但不是你问的方式.相反,您可以通过正确参数化来确保干净的sql.例如:

  1. string sql = "SELECT * FROM [table] WHERE [column] = @value";
  2. using (var cn = new sqlConnection("connection string here"))
  3. using (var cmd = new sqlCommand(sql,cn)
  4. {
  5. cmd.Parameters.Add("@value").Value = "'';DROP Table Users;--";
  6. cn.Open();
  7. SomeControl.DataSource = cmd.ExecuteReader();
  8. SomeControl.DataBind();
  9. }

代码运行起来非常安全,即使有明显的注入尝试.原因是sqlCommand对象的参数集合永远不会直接在查询中替换.数据被发送到服务器并完全独立于代码处理,因此无论用户输入什么内容,一切都是安全的.

你做的其他任何试图“消毒”请求的东西都将是与破解者的军备竞赛.这样,正确的方式,将数据和代码分开.

猜你在找的C#相关文章