Skip to content

.NET Deserialization: BinaryFormatter, Json.NET and TypeNameHandling

On .NET, the type information lives inside the payload. BinaryFormatter and a Json.NET $type directive will happily instantiate whatever class an attacker names — including gadgets that reach a process start. Here is how it leads to RCE, and the binder allowlist that stops it.

SelfSec Team 5 min read

Part 2 of 5From the Insecure Deserialization series

On .NET the danger is that the serialized payload carries its own type information, and several built-in serializers will faithfully instantiate whatever type the bytes name. BinaryFormatter and friends reconstruct an object graph by reading the assembly-qualified type out of the stream; Json.NET does the same when TypeNameHandling is anything other than None. In both cases the attacker, not your code, chooses which classes get built — and the .NET ecosystem ships gadget types that turn "build this object" into "start this process."

This is a direct route to remote code execution, and the tooling to exploit it (ysoserial.net) is mature. This post shows how an untrusted blob instantiates an attacker-chosen gadget during deserialization, where these sinks hide in real apps, and how a strict serialization binder closes them.

How it happens

The root cause is a serializer that resolves types from the payload itself. BinaryFormatter is the textbook case — it reads the type, the assembly and the fields straight from the stream:

public object Load(byte[] body)
{
    using var ms = new MemoryStream(body);
    var formatter = new BinaryFormatter();
    return formatter.Deserialize(ms);
}

Nothing here constrains what Deserialize will build. The same hazard applies to SoapFormatter, LosFormatter and NetDataContractSerializer, all of which embed type identity in their output. Json.NET is safe by default, but a single opt-in reopens the door:

var settings = new JsonSerializerSettings
{
    TypeNameHandling = TypeNameHandling.All
};
var model = JsonConvert.DeserializeObject<Model>(json, settings);

With TypeNameHandling.All, Json.NET honors a $type field in the JSON and instantiates whatever assembly-qualified type it names — exactly the control an attacker wants.

A concrete attack

The attacker supplies a $type that points at a known gadget. ObjectDataProvider is the favorite: it is a WPF helper that invokes an arbitrary method on an arbitrary object when its properties are set, which deserialization does during reconstruction:

POST /api/import HTTP/1.1
Content-Type: application/json

{
  "$type": "System.Windows.Data.ObjectDataProvider, PresentationFramework",
  "MethodName": "Start",
  "ObjectInstance": {
    "$type": "System.Diagnostics.Process, System",
    "StartInfo": {
      "$type": "System.Diagnostics.ProcessStartInfo, System",
      "FileName": "cmd.exe",
      "Arguments": "/c calc.exe"
    }
  }
}

When DeserializeObject rebuilds this graph, setting ObjectInstance and MethodName causes ObjectDataProvider to call Process.Start with the attacker's command line — RCE during deserialization, no vulnerable code of yours required. The same gadget rides inside a BinaryFormatter stream when that formatter is the sink instead.

The most common real-world entry point is ASP.NET Web Forms __VIEWSTATE. ViewState is a LosFormatter blob; if MAC validation is disabled or the machineKey leaks, an attacker forges a valid ViewState carrying the gadget above:

POST /page.aspx HTTP/1.1
Content-Type: application/x-www-form-urlencoded

__VIEWSTATE=/wEy...AAEAAAD/////AQAAAAAAAAAMAgAAAF9T...

The $type hint was never metadata you could trust — it is a constructor call signed by the attacker. The serializer is behaving exactly as documented, on input that should never have reached it.

Why it matters

Because the gadget runs inside the worker process during the deserialize call, the impact is severe:

  • Remote code execution — arbitrary process start under the app pool identity.
  • Forged ViewState — a leaked machineKey turns every Web Forms page into an RCE sink.
  • Privilege and trust abuse — gadgets run with the application's permissions and database access.
  • Full server compromise — RCE leads to credential theft, persistence and lateral movement.

The fix: kill the dangerous formatters, lock the type resolver

The first rule is simple: do not use BinaryFormatter. It is obsolete and removed from modern .NET precisely because it cannot be made safe on untrusted input; the same goes for SoapFormatter, LosFormatter and NetDataContractSerializer. Move to a data-only contract and keep Json.NET at its safe default:

var settings = new JsonSerializerSettings
{
    TypeNameHandling = TypeNameHandling.None
};
var model = JsonConvert.DeserializeObject<Model>(json, settings);

If polymorphism is genuinely required, do not loosen TypeNameHandling blindly — pin a strict SerializationBinder that allows only the exact types you expect and rejects everything else:

public sealed class AllowListBinder : ISerializationBinder
{
    private static readonly HashSet<string> Allowed = new()
    {
        "MyApp.Models.Invoice", "MyApp.Models.LineItem"
    };

    public Type BindToType(string assemblyName, string typeName)
    {
        if (!Allowed.Contains(typeName))
            throw new SerializationException($"Type not allowed: {typeName}");
        return Type.GetType($"{typeName}, {assemblyName}");
    }

    public void BindToName(Type t, out string? asm, out string? name)
        => (asm, name) = (null, t.FullName);
}

For Web Forms, keep ViewState MAC validation enabled, encrypt it (ViewStateEncryptionMode.Always), and rotate any machineKey that may have leaked. Every type you admit through the binder is a type an attacker will try to chain — keep the list as small as the feature allows.

How SelfSec finds it

When an out-of-band service is available, SelfSec sends a Json.NET $type payload built on the ObjectDataProvider gadget, which runs nslookup against a unique callback host, as the value of the query parameters, form fields, JSON fields and WebSocket messages its crawler finds; a callback that arrives marks the finding confirmed. Error text naming Newtonsoft.Json, JsonSerializationException, BinaryFormatter, LosFormatter or ObjectStateFormatter that a probe provokes, but the baseline response and, when one gets through, a harmless control value do not, is reported as a possible finding. SelfSec sends no BinaryFormatter or ViewState gadget streams and does not inject into cookies, so search your code for those formatters and for TypeNameHandling set to anything but None, and check web.config to confirm ViewState MAC validation is on and the machineKey has never been exposed. When recon recognizes Telerik or Sitefinity components, separate CVE probes also check those products' known deserialization endpoints. Each Insecure Deserialization finding records the request and response that triggered it. Core scan processing runs locally on 127.0.0.1.

SelfSec scanner

Find Insecure Deserialization in your own app

Reading about the class is one thing. SelfSec tests for it against an application you are authorized to assess, and only calls it real when independent evidence agrees.

Join the launch list