📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is insecure deserialisation, and why is it dangerous in .NET? Explain why BinaryFormatter was removed, why Newtonsoft.Json's TypeNameHandling is risky, how to do polymorphic JSON safely with System.Text.Json, and what other deserialisation risks remain (XML external entities, oversized payloads).

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.

Mid-Level Security Intermediate binaryformatter deserialisation newtonsoft-json owasp security system-text-json

🎯 Key points

  • The danger is formats where the payload chooses the type to instantiate: gadget chains run code during deserialisation
  • BinaryFormatter: obsolete since .NET 5, implementation removed in .NET 9 (throws); the unsupported compatibility package is for migration only, never untrusted input
  • Also unsafe with untrusted data: NetDataContractSerializer, SoapFormatter, LosFormatter, ObjectStateFormatter
  • Newtonsoft TypeNameHandling other than None lets JSON choose $type; if unavoidable, restrict with an ISerializationBinder allow-list
  • System.Text.Json has no type-name handling; polymorphism is opt-in via [JsonPolymorphic]/[JsonDerivedType], and unknown discriminators throw unless you choose a base-type fallback
  • Validate after deserialising into narrow DTOs (FluentValidation/data annotations); signing adds integrity but doesn't make an unsafe serialiser safe
  • XML: .NET Core's XmlReader prohibits DTDs by default; don't re-enable DTD processing or set an XmlResolver for untrusted XML
  • Limit size and depth: Kestrel MaxRequestBodySize, STJ MaxDepth 64 by default

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"The problem isn't parsing data, it's letting the data decide which .NET types get instantiated. Formatters like BinaryFormatter, NetDataContractSerializer or SoapFormatter write 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 throws PlatformNotSupportedException unless 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 with TypeNameHandling.All or Auto, usually added to make polymorphic DTOs work. That lets a $type property 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."


Vulnerable, exploit, fixed

  • Vulnerable: JsonConvert.DeserializeObject<Message>(body, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto }) on data from a queue or API.
  • Exploit (one line): the attacker sends JSON whose $type names a gadget type from a referenced assembly, with property values that trigger code execution when set.
  • Fixed: System.Text.Json with [JsonPolymorphic] and an explicit list of [JsonDerivedType] discriminators; unknown discriminators fail.

Serialisers and risk

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

Replacing BinaryFormatter

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

Production example

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.

🔍 What the interviewer is checking

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

  • Explains gadget chains and that the payload choosing types is the root cause
  • Knows BinaryFormatter's removal in .NET 9 and how to migrate
  • Flags Newtonsoft TypeNameHandling and uses STJ discriminators
  • Mentions XXE defaults and size/depth limits

Red flags

  • 'JSON is always safe'
  • Re-enables BinaryFormatter to finish an upgrade
  • Trusts internal queues by default

📚 Learn in depth

1. Why type-controlled formats are dangerous

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.

2. BinaryFormatter's end of life

  • .NET 5: BinaryFormatter.Serialize/Deserialize marked obsolete (SYSLIB0011), disabled by default in ASP.NET Core apps.
  • .NET 8: obsolete as error for most project types.
  • .NET 9: the implementation was removed from the runtime; calls throw 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.

3. Newtonsoft.Json TypeNameHandling

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.

4. System.Text.Json polymorphism

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.

5. XML: external entities and expansion

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.

6. Denial of service by payload shape

  • Kestrel's default MaxRequestBodySize is about 28.6 MB (30,000,000 bytes); lower it per endpoint with [RequestSizeLimit] or IHttpMaxRequestBodySizeFeature.
  • System.Text.Json MaxDepth defaults to 64; huge arrays still allocate, so validate counts.
  • Form limits (FormOptions) cap value counts and lengths.

Try it yourself

  1. Upgrade a small app using BinaryFormatter to .NET 9/10 and read the exception; replace it with System.Text.Json.
  2. Write a polymorphic Payment hierarchy with [JsonDerivedType] and test that an unknown discriminator fails.
  3. Grep your solution and packages for TypeNameHandling, BinaryFormatter, NetDataContractSerializer, LosFormatter.
  4. Parse an XML document with a DTD using default XmlReaderSettings and observe the exception.
  5. Post a 50 MB JSON body to an endpoint with [RequestSizeLimit(1_000_000)] and confirm a 413.

💻 Code

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" }

⚠ Common mistakes

  • Mistake: Turning on 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.
  • Mistake: Re-enabling 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.
  • Mistake: Treating internal queues, caches or files as trusted. Why it is wrong: anything another system or a compromised component can write is untrusted. Instead: use safe serialisers for every boundary.
  • Mistake: Using 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.
  • Mistake: Enabling DTD processing or setting an XmlUrlResolver for untrusted XML. Why it is wrong: it enables XXE file reads and SSRF. Instead: keep DtdProcessing.Prohibit (the default).
  • Mistake: Ignoring payload size and depth. Why it is wrong: large or deeply nested inputs exhaust memory and CPU. Instead: set RequestSizeLimit, MaxDepth and validate collection counts.
  • Mistake: Thinking signing the payload makes any serialiser safe. Why it is wrong: it helps only if the key never leaks and every producer is trusted. Instead: sign for integrity and use a serialiser that doesn't let data choose types.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions polymorphic DTOs with System.Text.Json Why: Checks they can make polymorphic contracts show up correctly in OpenAPI
    How to answer

    I treat the document as output of metadata plus the System.Text.Json contract, and check each symptom against its source:

    • Missing endpoints: is it in API Explorer? Common causes are ExcludeFromDescription, conventional MVC routes, no AddEndpointsApiExplorer with Swashbuckle, or a document's ShouldInclude filter.
    • No response schema: the handler returns IResult; switch to TypedResults with Results<...>.
    • Polymorphism: add [JsonPolymorphic] / [JsonDerivedType] to get oneOf with a discriminator.
    • Enums as integers: register JsonStringEnumConverter for the API.
    • Nullability: enable nullable reference types and use 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.

  2. When: Candidate mentions denial of service via large payloads Why: Checks practical knowledge of Kestrel, form and JSON limits
    How to answer

    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).

🛠 Real-world problems: how you handle them

TypeNameHandling.Auto on a shared Service Bus topic
Situation
An order-processing worker in [a retail / fintech] platform consumes messages from an Azure Service Bus topic that [three] other teams can publish to. It uses Newtonsoft.Json with `TypeNameHandling.Auto` so polymorphic events deserialise. Found during [a .NET 9 upgrade / security review].
Signals
Security analyser warning CA2326/CA2327 suppressed in the project; code review comment during the upgrade; no incidents observed, but the topic's send permissions are broad.
Investigation
Grepped all services for `TypeNameHandling`, `BinaryFormatter` and `NetDataContractSerializer`; found [number] usages. Reviewed which identities had Send rights on the topic in Azure RBAC. Checked message samples for `$type` values and enumerated the subtypes actually used. Confirmed with a local test that a crafted `$type` instantiated an unexpected type.
Resolution
Immediate: added an `ISerializationBinder` allow-listing the [six] event types and tightened Send permissions on the topic. Long term: migrated producers and consumers to System.Text.Json with `[JsonPolymorphic]` discriminators via a shared contracts package, versioned so old and new messages coexisted during rollout.
Prevention
CA2326/CA2327/CA2328 and SYSLIB0011 as errors; a CI grep for unsafe serialisers; contract tests for every message type; a team guideline that every queue is a trust boundary.

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].

More in Web Security

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me