TypeNameHandling.All
: Security Risks When Deserializing Untrusted DataThe TypeNameHandling
property in Newtonsoft.Json dictates how polymorphic objects are deserialized. Setting it to TypeNameHandling.All
enables Newtonsoft.Json to instantiate types based on the $type
property within the incoming JSON. However, this presents significant security vulnerabilities when handling untrusted data.
Security Implications
Malicious actors can exploit TypeNameHandling.All
by injecting a $type
property specifying a harmful type within the JSON. This allows them to execute arbitrary code or perform unwanted actions on the target system.
Consider a seemingly harmless class:
<code class="language-csharp">public class Vehicle { public string Make { get; set; } public string Model { get; set; } }</code>
A malicious JSON payload could look like this:
<code class="language-json">{ "$type": "System.Diagnostics.Process", "Make": "Attack", "Model": "DeleteC:\ImportantFiles" }</code>
While the Make
and Model
properties are benign, the $type
property forces the creation of a System.Diagnostics.Process
object, potentially initiating harmful processes on the system. This bypasses normal type checking and opens the door to various attacks.
Mitigating the Risk
To prevent such attacks, avoid using TypeNameHandling.All
when deserializing JSON from external, untrusted sources. Instead, employ TypeNameHandling.None
to disable type name handling. Alternatively, implement a custom SerializationBinder
to meticulously control which types are allowed during deserialization, effectively whitelisting safe types. This provides a more granular and secure approach to handling polymorphic deserialization.
The above is the detailed content of Is Using `TypeNameHandling.All` in Newtonsoft.Json Safe for Deserializing Untrusted Data?. For more information, please follow other related articles on the PHP Chinese website!