中的类型名称处理注意事项

中的类型名称处理注意事项

本文介绍了Newtonsoft Json 中的类型名称处理注意事项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个链接上,在备注部分提到:

On this link, in remarks section it's mentioned that:

TypeNameHandling.使用 TypeNameHandling.None 以外的值反序列化时,应使用自定义 SerializationBinder 验证传入类型.

在什么情况下,使用 TypeNameHandling.All 序列化/反序列化来自外部源的 JSON 会有害?一个工作示例将不胜感激.

In what cases JSON from external source would be harmful if serialized/deserialized with TypeNameHandling.All? A working example would be appreciated.

推荐答案

当使用 TypeNameHandling.All 反序列化并且没有 SerializationBinder 检查时,json.net 将尝试创建一个类型为JSON 中的元数据.

When deserialize with TypeNameHandling.All and without a SerializationBinder checks json.net will try to create a instace of the type that comes as metadata in the JSON.

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

但是攻击者可能会向您发送存在于您的代码或框架中的危险类型.

But an attacker could send you dangerous types that exist in your code or in the framework.

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

i.e. from here System.CodeDom.Compiler.TempFileCollection is a serializable class whose purpose is to maintain a list of temporary files which resulted from a compilation process and delete them when they are no longer needed. To ensure that the files are deleted the class implements a finalizer that will be called when the object is being cleaned up by the Garbage Collector. An attacker would be able to construct a serialized version of this class which pointed its internal file collection to any file on a victims system. This will be deleted at some point after deserialization without any interaction from the deserializing application.

    [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

这篇关于Newtonsoft Json 中的类型名称处理注意事项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 02:20