Insecure Deserialization

Difficulty: Advanced

Question

What is insecure deserialization, why can it lead to remote code execution, and how do you prevent it?

Answer

Insecure deserialization happens when an application takes untrusted bytes, such as a cookie, request body, or message queue payload, and turns them back into live objects using a native serialization format like Java serialization, Python pickle, PHP unserialize or .NET BinaryFormatter. Because these formats can describe arbitrary classes and trigger code during object reconstruction, an attacker can craft a payload that runs commands on the server. The fix is to never deserialize untrusted data with native object formats and to use data-only formats like JSON with strict schemas instead.

Why rebuilding objects can run code

Native serializers do more than fill in fields. During deserialization they may:

  • Instantiate any class named in the payload that exists on the classpath.
  • Call magic methods automatically: readObject in Java, __reduce__ in Python pickle, __wakeup and __destruct in PHP, OnDeserialized callbacks in .NET.
  • Invoke setters, comparators or hashCode while rebuilding collections.

An attacker chains these existing, legitimate methods together into a gadget chain that ends in something dangerous, such as Runtime.exec(). They do not need to upload new code; they reuse classes already in your dependencies. Tools like ysoserial generate ready-made chains for common Java libraries, and the Apache Commons Collections gadgets caused widespread RCE across Java app servers such as WebLogic, JBoss and Jenkins.

Where it appears

  • Session or "remember me" cookies that are a base64 serialized object.
  • Java RMI, JMX and older binary protocols.
  • Message queues and caches that store pickled Python objects (Celery with pickle serializer, Redis caches).
  • ML model files: loading an untrusted .pkl or older PyTorch checkpoint can execute code. PyTorch 2.6 changed torch.load to default to weights_only=True for this reason, and formats like safetensors avoid it entirely.
  • YAML: yaml.load with an unsafe loader in PyYAML can construct arbitrary Python objects. Use yaml.safe_load.
  • Node.js: the node-serialize package allowed RCE via serialized functions (CVE-2017-5941).

Even without RCE, deserialization bugs can enable privilege escalation (changing role in a serialized object) or DoS through deeply nested or huge object graphs.

How to prevent it

  1. Do not deserialize untrusted data with native formats. Use JSON, Protocol Buffers or similar, which map to plain data, and validate with a schema.
  2. If you must accept serialized objects, sign them (HMAC) and verify the signature before deserializing, so attackers cannot forge payloads.
  3. In Java, use deserialization filters (ObjectInputFilter, JEP 290) with an allowlist of expected classes, and remove unused gadget libraries.
  4. In .NET, do not use BinaryFormatter; it is obsolete and was removed from .NET 9. Use System.Text.Json.
  5. Run services with least privilege and keep dependencies patched so known gadget chains disappear.

In the OWASP Top 10 this falls under A08 Software and Data Integrity Failures; it was a standalone category (A8) in the 2017 edition.

How a deserialization exploit unfolds. The attacker never uploads code; they chain classes you already ship.
  1. Find a deserialization point: A cookie or body holding a serialized object.
  2. Pick a gadget chain: Classes present in the app's dependencies.
  3. Craft the payload: Tools like ysoserial generate the bytes.
  4. Server deserializes it: Magic methods fire during reconstruction.
  5. Chain reaches exec(): Command runs with the app's privileges.

Code examples

Why pickle.loads on untrusted data is RCE (Python)

import pickle, os, json

class Exploit:
    # pickle calls __reduce__ to learn how to rebuild the object
    def __reduce__(self):
        return (os.system, ("echo pwned: $(whoami)",))

payload = pickle.dumps(Exploit())  # attacker sends these bytes

# VULNERABLE: server 'restores' a cart from a cookie
pickle.loads(payload)  # runs the shell command

# SAFE: data-only format plus validation
cart = json.loads('{"items": [{"sku": "A12", "qty": 2}]}')
assert isinstance(cart["items"], list)

Unpickling calls os.system with attacker-chosen arguments. JSON only produces dicts, lists, strings and numbers, so there is nothing to execute.

Allowlisting classes with a Java deserialization filter

import java.io.*;

public class SafeRead {
    public static Object read(byte[] data) throws Exception {
        ObjectInputFilter filter = ObjectInputFilter.Config.createFilter(
            "com.example.cart.Cart;com.example.cart.Item;java.util.ArrayList;"
            + "maxdepth=5;maxrefs=1000;maxbytes=65536;!*"
        );
        try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(data))) {
            in.setObjectInputFilter(filter); // reject everything not listed
            return in.readObject();
        }
    }
}

The trailing !* rejects any class not explicitly allowed, which blocks gadget classes. Limits on depth, references and size also prevent DoS payloads.

Key points

  • Native object serializers can instantiate arbitrary classes and trigger code during reconstruction
  • Gadget chains reuse existing library classes to reach dangerous calls like Runtime.exec
  • Dangerous APIs: Java ObjectInputStream, Python pickle and unsafe yaml.load, PHP unserialize, .NET BinaryFormatter
  • Use JSON or Protobuf with schema validation for untrusted input
  • If unavoidable, sign payloads and apply class allowlists (Java ObjectInputFilter)

Common follow-up questions

  • What is a gadget chain and why does removing an unused library help?
  • Why is loading an untrusted ML model file a security risk?
  • How would signing a serialized cookie help, and what are its limits?
  • Is JSON.parse in JavaScript vulnerable to the same class of attacks?

Interview tips

  • Explain the mechanism (magic methods plus gadget chains), not just 'it can cause RCE'
  • Give one language-specific example you know well, such as pickle __reduce__ or Java readObject
  • Mention modern examples like ML model loading or yaml.load to show the issue is still current

Concepts covered

Insecure Deserialization, Gadget Chains, Remote Code Execution, Java Serialization, Python pickle

More Web Security (OWASP, JWT, XSS, CSRF) questions