Insecure deserialisation in .NET: type-controlled formatters and gadget chains, BinaryFormatter's removal in .NET 9, Newtonsoft TypeNameHandling, safe polymorphism with System.Text.Json, XXE and denial-of-service limits.
Insecure deserialisation is turning untrusted bytes into objects with a serialiser that lets the payload choose which types to create. Constructors, setters and callbacks on those types run during deserialisation, so attackers chain existing library classes (gadget chains) into remote code execution. That's why BinaryFormatter was removed in .NET 9 (it now always throws), and why Newtonsoft.Json's TypeNameHandling (anything but None) is dangerous: $type in the JSON picks the class.
System.Text.Json never reads type names; polymorphism is opt-in with [JsonPolymorphic]/[JsonDerivedType], an allow-list of discriminators mapped to known types. Remaining risks: XXE if you re-enable DTD processing for XML, and denial of service from huge or deeply nested payloads, so keep size and depth limits.
"The problem isn't parsing data, it's letting the data decide which .NET types get instantiated. Formatters like
BinaryFormatter,NetDataContractSerializerorSoapFormatterwrite the full type name into the payload and recreate whatever it says. Lots of types in the framework and in common libraries do work in constructors, property setters or deserialisation callbacks, and attackers chain those into what's called a gadget chain that ends in starting a process. Public tools generate these payloads, so it's not theoretical: it's remote code execution from one request.Microsoft's answer was to kill
BinaryFormatter: obsolete since .NET 5, and in .NET 9 the implementation was removed, so it throwsPlatformNotSupportedExceptionunless you pull in an unsupported compatibility package, which I wouldn't for untrusted input. The trap that still shows up in code is Newtonsoft.Json withTypeNameHandling.AllorAuto, usually added to make polymorphic DTOs work. That lets a$typeproperty pick the class. For example, at [company] I found [an internal message consumer using TypeNameHandling.Auto on queue messages]; we replaced it with System.Text.Json discriminators and [the change took about a day].System.Text.Json is safe by design: it never reads type names. If I need polymorphism, I put
[JsonPolymorphic]on the base type and[JsonDerivedType(typeof(CardPayment), "card")]for each subtype, so the discriminator is an allow-list. Beyond RCE, I still limit size and depth, and for XML I keep DTD processing off to avoid external entities. The mistake I see is 'it's only from our own queue, so it's trusted'. Anything that crosses a trust boundary, including a queue other systems can write to, is untrusted."
JsonConvert.DeserializeObject<Message>(body, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto }) on data from a queue or API.$type names a gadget type from a referenced assembly, with property values that trigger code execution when set.[JsonPolymorphic] and an explicit list of [JsonDerivedType] discriminators; unknown discriminators fail.| Serialiser | Type chosen by payload? | Safe for untrusted input? |
|---|---|---|
BinaryFormatter, SoapFormatter, NetDataContractSerializer, LosFormatter, ObjectStateFormatter |
Yes | No (BinaryFormatter removed in .NET 9) |
Newtonsoft.Json, TypeNameHandling.None (default) |
No | Yes |
Newtonsoft.Json, TypeNameHandling Auto/Objects/All |
Yes | No unless restricted with an ISerializationBinder allow-list |
| System.Text.Json | No (opt-in discriminators) | Yes |
DataContractSerializer with known types |
Limited to declared known types | Generally yes |
XmlSerializer |
No (type fixed by caller) | Yes, with safe XML reader settings |
| MessagePack, protobuf-net | Depends on options (typeless modes are unsafe) | Yes in contract/typed mode |
| Use | Replacement |
|---|---|
| Caching objects | System.Text.Json or MessagePack (typed) |
| Deep cloning | Records with with, or a copy method |
| Session/TempData | ASP.NET Core already uses JSON |
| Legacy files you must read | Migrate offline with the NRBF payload reader (System.Formats.Nrbf), not by deserialising |
Migrating a distributed cache from BinaryFormatter to System.Text.Json source-generated contexts during a .NET 8 to 9 upgrade removed the RCE risk and, as a side effect, cut serialised payload size by about 40% and serialisation time by more than half in BenchmarkDotNet runs.
Checks that the candidate understands why type-controlled deserialisation leads to RCE, knows the current .NET state (BinaryFormatter removed), and can implement safe polymorphism.
Green flags
TypeNameHandling and uses STJ discriminatorsRed flags
payload: { type: "Some.Gadget, SomeAssembly", props: {...} }
|
v
serialiser: Type.GetType(name) -> Activator/FormatterServices -> set props / call callbacks
|
v
gadget's setter or OnDeserialized runs -> chains into Process.Start / file write
The vulnerability lives in the combination: a serialiser that trusts type names plus any gadget type loadable in the process. You can't audit away every gadget in every dependency, so the fix is to never let input pick types.
BinaryFormatter.Serialize/Deserialize marked obsolete (SYSLIB0011), disabled by default in ASP.NET Core apps.PlatformNotSupportedException. An unsupported compatibility package exists only for migration scenarios.System.Formats.Nrbf (NrbfDecoder) can read legacy BinaryFormatter payloads as data without instantiating arbitrary types, which is how you migrate stored data safely.With TypeNameHandling set, Newtonsoft writes and honours $type. Auto only applies where the declared type doesn't match, but properties of type object, dynamic or interfaces make that easy to reach. If you can't remove it, set SerializationBinder to an ISerializationBinder that allows only specific types, and avoid object-typed members.
Since .NET 7, [JsonPolymorphic(TypeDiscriminatorPropertyName = "kind")] and [JsonDerivedType(typeof(T), "discriminator")] declare the closed set of subtypes. On read, the discriminator is mapped through that table; an unknown value throws (or falls back to the base type if configured with UnknownDerivedTypeHandling). Type names never appear in the JSON, so there is nothing to inject. With source generation (JsonSerializerContext), it's also trim- and Native AOT-friendly.
XXE uses a DTD to define an entity that reads a local file or makes a network call. In .NET Core and later, XmlReader.Create defaults to DtdProcessing.Prohibit and XmlDocument/XmlTextReader have no resolver by default, so you're safe unless you turn DTDs on or set an XmlUrlResolver. Also keep MaxCharactersFromEntities limits for 'billion laughs' expansion if DTDs must be parsed.
MaxRequestBodySize is about 28.6 MB (30,000,000 bytes); lower it per endpoint with [RequestSizeLimit] or IHttpMaxRequestBodySizeFeature.MaxDepth defaults to 64; huge arrays still allocate, so validate counts.FormOptions) cap value counts and lengths.BinaryFormatter to .NET 9/10 and read the exception; replace it with System.Text.Json.Payment hierarchy with [JsonDerivedType] and test that an unknown discriminator fails.TypeNameHandling, BinaryFormatter, NetDataContractSerializer, LosFormatter.XmlReaderSettings and observe the exception.[RequestSizeLimit(1_000_000)] and confirm a 413.Before and after: unsafe Newtonsoft type handling on queue messages replaced with an allow-listed System.Text.Json polymorphic contract, source-generated, plus request limits.
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Payments.Messages;
// BEFORE (vulnerable): the payload's $type decides which class is created
// var msg = Newtonsoft.Json.JsonConvert.DeserializeObject<PaymentMessage>(body,
// new Newtonsoft.Json.JsonSerializerSettings { TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Auto });
// AFTER: closed set of subtypes; the discriminator is data, not a type name
[JsonPolymorphic(TypeDiscriminatorPropertyName = "kind")]
[JsonDerivedType(typeof(CardPayment), "card")]
[JsonDerivedType(typeof(PayIdPayment), "payid")]
public abstract record PaymentMessage(Guid PaymentId, decimal Amount);
public sealed record CardPayment(Guid PaymentId, decimal Amount, string Last4) : PaymentMessage(PaymentId, Amount);
public sealed record PayIdPayment(Guid PaymentId, decimal Amount, string PayId) : PaymentMessage(PaymentId, Amount);
[JsonSerializable(typeof(PaymentMessage))]
[JsonSourceGenerationOptions(MaxDepth = 16)] // our messages are shallow
public sealed partial class PaymentJsonContext : JsonSerializerContext;
public static class PaymentMessageReader
{
public static PaymentMessage Read(ReadOnlySpan<byte> utf8Json)
{
if (utf8Json.Length > 64 * 1024)
throw new InvalidDataException("Message too large.");
// Unknown "kind" values throw NotSupportedException/JsonException: fail closed
return JsonSerializer.Deserialize(utf8Json, PaymentJsonContext.Default.PaymentMessage)
?? throw new InvalidDataException("Empty message.");
}
}
// API side: cap body size for endpoints that accept JSON from outside
app.MapPost("/payments", (PaymentMessage message) => Results.Accepted())
.WithMetadata(new Microsoft.AspNetCore.Mvc.RequestSizeLimitAttribute(256 * 1024));
{ "kind": "card", "paymentId": "0b7a...", "amount": 42.50, "last4": "4242" }
TypeNameHandling.Auto or All to make polymorphic DTOs work. Why it is wrong: the JSON chooses the type, enabling gadget-chain RCE. Instead: use System.Text.Json discriminators, or restrict Newtonsoft with an ISerializationBinder allow-list.BinaryFormatter with the compatibility package after upgrading to .NET 9. Why it is wrong: it reintroduces a known RCE class. Instead: migrate to a typed serialiser; read old data with System.Formats.Nrbf.object or dynamic properties in DTOs. Why it is wrong: they invite type-name handling and make contracts unclear. Instead: use concrete types and explicit polymorphism.XmlUrlResolver for untrusted XML. Why it is wrong: it enables XXE file reads and SSRF. Instead: keep DtdProcessing.Prohibit (the default).RequestSizeLimit, MaxDepth and validate collection counts.The senior rule: data must never choose code. Serialisers that embed type names are a design flaw for any boundary, and modern .NET has made the safe choice the default. What's left is legacy and convenience: old caches, Newtonsoft settings copied from a blog post, and 'trusted' internal channels. I audit for those during upgrades, because .NET 9's removal of BinaryFormatter is the moment the issue surfaces anyway.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| System.Text.Json + discriminators | APIs, messages, caches | Explicit subtype list | Formats requiring arbitrary types (avoid those) |
Newtonsoft + ISerializationBinder allow-list |
Legacy code you can't migrate yet | Maintaining the binder | New code |
| MessagePack / protobuf (typed contracts) | High-throughput internal messaging | Schema management | Typeless modes with untrusted data |
System.Formats.Nrbf reader |
Migrating stored BinaryFormatter data | One-off migration work | Ongoing serialisation |
Measure: zero hits for unsafe serialisers in a CI grep or analyser (SYSLIB0011, CA2326/CA2327 for TypeNameHandling), and payload size limits configured per endpoint.
I treat the document as output of metadata plus the System.Text.Json contract, and check each symptom against its source:
ExcludeFromDescription, conventional MVC routes, no AddEndpointsApiExplorer with Swashbuckle, or a document's ShouldInclude filter.IResult; switch to TypedResults with Results<...>.[JsonPolymorphic] / [JsonDerivedType] to get oneOf with a discriminator.JsonStringEnumConverter for the API.required.Then I add a snapshot test of the document. The trade-off: fixing the source (types, JSON options) is more work than patching with transformers, but keeps the docs and the wire format in step.
Set limits at every layer and fail fast with a clear status. Lower Kestrel's MaxRequestBodySize (default about 28.6 MB) globally, and per endpoint with [RequestSizeLimit]; requests over the limit get 413 Payload Too Large. Set FormOptions limits for multipart. Keep System.Text.Json's MaxDepth (64 by default; lower it for shallow contracts), so deeply nested JSON fails with 400. Validate collection counts in FluentValidation or data annotations and return a ValidationProblem. Stream large uploads instead of buffering, and add rate limiting (AddRateLimiter) so repeated large requests can't exhaust CPU and memory (a denial-of-service vector).
How to tell it (STAR)
**S:** At [company], while upgrading to .NET 9, I found our order worker deserialising Service Bus messages with Newtonsoft's `TypeNameHandling.Auto`, on a topic [three] teams could publish to. **T:** I needed to remove the RCE risk without breaking in-flight messages. **A:** I proved locally that a crafted `$type` created an unexpected class, added a binder allow-listing our [six] event types as a stopgap, and tightened who could send to the topic. Then I moved everyone to System.Text.Json discriminators in a shared contracts package, rolled out so old and new messages both worked. **R:** The risk was gone in [two sprints], the analysers now fail the build on unsafe settings, and message handling got [measurably faster].
Last updated 23 Nov 2026.