Home >Backend Development >C++ >Is Newtonsoft JSON's TypeNameHandling Safe for Deserializing External JSON Data?
Newtonsoft JSON's TypeNameHandling
: A Security Consideration for External JSON
Newtonsoft's JSON library offers TypeNameHandling
for deserializing JSON containing type information. However, using this with untrusted external JSON sources presents significant security risks.
Security Risks of Deserializing External JSON with TypeNameHandling.All
Without a SerializationBinder
, TypeNameHandling.All
allows the deserializer to create instances of any type specified in the JSON metadata. This opens a vulnerability to malicious actors who could send harmful types present in your application or the .NET framework.
Example Vulnerability:
Consider a simple Car
class:
<code class="language-csharp">public class Car { public string Maker { get; set; } public string Model { get; set; } }</code>
A seemingly harmless JSON payload:
<code class="language-json">{ "$type": "Car", "Maker": "Ford", "Model": "Explorer" }</code>
...would deserialize correctly. However, a malicious actor could craft a payload targeting a system class like System.CodeDom.Compiler.TempFileCollection
:
<code class="language-json">{ "$type": "System.CodeDom.Compiler.TempFileCollection", "BasePath": "%SYSTEMDRIVE%", "KeepFiles": "False", "TempDir": "%SYSTEMROOT%" }</code>
TempFileCollection
, a serializable class managing temporary files, has a finalizer that deletes files upon garbage collection. A malicious payload could point this finalizer to arbitrary files on the victim's system, resulting in unintended file deletion without user interaction. This is just one example; many other system classes could be exploited in similar ways.
Therefore, always use a SerializationBinder
when deserializing JSON from external sources with TypeNameHandling
enabled to mitigate these risks. Only allow deserialization of types you explicitly trust and control.
The above is the detailed content of Is Newtonsoft JSON's TypeNameHandling Safe for Deserializing External JSON Data?. For more information, please follow other related articles on the PHP Chinese website!