TypeName在Newtonsoft Json中谨慎操作

在这个链接上,在注释部分中提到, TypeNameHandling should be used with caution when your application deserializes JSON from an external source. Incoming types should be validated with a custom SerializationBinder when deserializing with a value other than TypeNameHandling.None.TypeNameHandling should be used with caution when your application deserializes JSON from an external source. Incoming types should be validated with a custom SerializationBinder when deserializing with a value other than TypeNameHandling.None. 。 如果使用TypeNameHandling.All序列化/反序列化,那么外部来源的JSON会有什么危害? 一个工作的例子,将不胜感激。

当使用TypeNameHandling.All反序列化时,如果没有使用SerializationBinder检查,json.net将尝试创build一个在JSON中作为元数据的types的实例。

 public class Car { public string Maker { get; set; } public string Model { get; set; } } { "$type": "Car", "Maker": "Ford", "Model": "Explorer" } //create a Car and set property values 

但是攻击者可能会向您发送危险的types,这些types存在于您的代码或框架中。

即从这里 System.CodeDom.Compiler.TempFileCollection是一个可序列化的类,其目的是维护编译过程中产生的临时文件列表,并在不再需要时删除它们。 为了确保文件被删除,类实现了一个终止器,当垃圾收集器正在清理对象时,该终止器将被调用。 攻击者将能够构build这个类的序列化版本,将其内部文件集合指向受害者系统上的任何文件。 这将在反序列化之后的某个点被删除,而没有任何反序列化应用程序的交互。

  [Serializable] public class TempFileCollection { private Hashtable files; // Other stuff... ~TempFileCollection() { if (KeepFiles) {return} foreach (string file in files.Keys) { File.Delete(file); } } } { "$type": "System.CodeDom.Compiler.TempFileCollection", "BasePath": "%SYSTEMDRIVE", "KeepFiles": "False", "TempDir": "%SYSTEMROOT%" } // or something like this, I just guessing but you got the idea