Skip to main content
Be Bitwise

Serialisation & Deserialisation Attacks

Web Application Exploitation (Low-Level Perspective) · Advanced Exploitation track

9 min read

In this module

Turning Data Back Into Objects

Applications constantly need to convert structured data into bytes for storage or transmission, then reconstruct it later. Every major language provides a mechanism for this: Java's ObjectInputStream, Python's pickle, PHP's unserialize(), Ruby's Marshal, Protocol Buffers, MessagePack.

The security problem surfaces when deserialisation processes untrusted data. If an attacker controls the serialised bytes, they control which objects get created, what their fields contain, and — in many languages — which code runs during reconstruction.

How Deserialisation Works

To understand the attack, you need to understand what serialisation actually stores. When an object is serialised, the output typically contains:

  • The class name or type identifier
  • The values of the object's fields
  • References to other objects (for nested structures)
  • Sometimes, metadata about the class version or schema

When the deserializer processes this data, it:

  1. Reads the type identifier
  2. Instantiates an object of that type
  3. Populates its fields with the provided values
  4. May call special lifecycle methods (constructors, readObject in Java, __wakeup in PHP)

The critical insight is that the attacker controls which type is instantiated and what values its fields contain. If the application deserializes attacker-controlled data without restricting which types are allowed, the attacker can instantiate any class available on the classpath.

Deserialisation

Deserialisation is the process of converting a byte sequence back into a live object in memory. When the byte sequence comes from an untrusted source, an attacker controls which objects are created and what state they contain. This is dangerous because object creation and field population can trigger code execution through constructors, finalisers, and property setters.

The Gadget Chain Concept

Simply creating an arbitrary object is not immediately useful unless that object does something dangerous upon creation. This is where gadget chains come in - a concept closely related to the ROP chains from Return-Oriented Programming, but applied to object-oriented programming.

A gadget chain is a sequence of objects where:

  1. The first object's deserialisation triggers a method call (like a lifecycle callback)
  2. That method interacts with a field that the attacker has set to reference a second object
  3. The second object's method does something that triggers a third object's method
  4. Eventually, the chain reaches an object that performs a dangerous operation (executing a command, writing a file, making a network request)

No single class in the chain is "vulnerable" by itself. Each performs a legitimate operation. But when chained together with attacker-controlled field values, they produce arbitrary code execution.

text
Deserialisation
→ Object A created (lifecycle method called)
→ Calls method on field X (attacker set X = Object B)
→ Object B's method calls method on field Y (attacker set Y = Object C)
→ Object C's method executes a system command

The same thing in miniature, in C: the "deserialiser" below reads a type name from the data and looks it up in a registry of every type the program knows, then runs that type's load hook. TempFile is a perfectly reasonable class whose job is to delete its scratch file once loaded. Nothing in the data format says the attacker can't pick it. Predict what happens to important.txt before you run it.

Try itRun it, then set ALLOWLIST to 1 so only Note and Config may be deserialised, and run it again.
C (GCC 9.2.0)

Java Deserialisation: The Apache Commons Watershed

Java deserialisation vulnerabilities became widely known in 2015 when researchers published a tool called ysoserial, which generated exploit payloads for common Java libraries. The most famous gadget chain used classes from Apache Commons Collections, a library bundled with a huge number of Java applications.

ysoserial ships several Commons Collections chains with different entry points. In one widely used variant (CommonsCollections6), a HashSet was deserialized, and rebuilding its backing HashMap called hashCode() on each element. One key was a specially crafted object whose hashCode() method triggered a chain of method calls through the Commons Collections library, eventually reaching a class that invoked Runtime.exec() with an attacker-controlled command string. The original CommonsCollections1 chain entered through a different door, the JDK's AnnotationInvocationHandler.readObject.

Click through the CommonsCollections6 chain below, then switch on a fix. Every one of them stops the attack while the stream is still being read, before a single gadget method runs.

CommonsCollections6

HashSet.readObject
TiedMapEntry.hashCode
LazyMap.get
ChainedTransformer
Runtime.exec

Hover over or tap each step to see details

The attack was devastating because:

  • Apache Commons Collections was on the classpath of almost every Java application
  • Java's default ObjectInputStream deserializes any class without restriction
  • The vulnerable pattern (accepting serialised Java objects from the network) was common in frameworks like JBoss, WebLogic, and Jenkins

The fix requires either switching to a format that does not reconstruct arbitrary objects (like plain JSON; JSON libraries with polymorphic typing switched on, such as Jackson's default typing or fastjson's autotype, have had gadget chains of their own), using an allowlist-based deserialisation filter to restrict which classes can be instantiated, or removing dangerous classes from the classpath.

PHP's unserialize()

PHP's unserialize() function reconstructs objects from a string format. When an object is deserialized, PHP calls its __wakeup() magic method. If the attacker can control the serialised string, they can instantiate any class the application has loaded and populate its properties with arbitrary values.

PHP gadget chains exploit magic methods like:

  • __wakeup(): Called during deserialisation
  • __destruct(): Called when the object is garbage collected
  • __toString(): Called when the object is used as a string
  • __call(): Called when a non-existent method is invoked

An attacker might create an object whose __destruct() method writes attacker-controlled data to a file (if the class has a file-writing destructor and the filename and content are stored in properties the attacker controls). Or a chain where __toString() calls a method that eventually reaches a function like system() or eval().

Python's pickle

Python's pickle module is explicitly documented as unsafe for untrusted data, yet developers frequently use it in networked applications. Pickle is particularly dangerous because it includes a __reduce__ method that specifies how to reconstruct an object - and this method can return a callable with arguments.

python
import pickle
import os
class Exploit:
def __reduce__(self):
return (os.system, ('id',))
# Serializing this creates a payload that executes 'id' on deserialisation
payload = pickle.dumps(Exploit())
pickle.loads(payload) # Executes os.system('id')

The reduce method tells pickle to call os.system with the argument 'id' when reconstructing the object. Any callable can be specified - subprocess.Popen, exec, or any function in any imported module.

Predict: does the server that calls pickle.loads(payload) need the Exploit class defined anywhere?

No. Exploit only exists on the attacker's machine, long enough for pickle.dumps to call its __reduce__. The payload records the callable by module and name (posix and system on Linux, since that's where os.system really lives) plus the argument tuple. pickle.loads imports that module, looks the name up and calls it. Run pickletools.dis(payload) on your own machine and you'll see a STACK_GLOBAL (or GLOBAL) opcode naming the function and a REDUCE that calls it, with no trace of Exploit. That's why "we never import anything dangerous" is no defence: the payload brings its own import.

Binary Serialisation Formats

Protocol Buffers, MessagePack, FlatBuffers, and similar binary formats are generally safer than language-native serialisation because they do not reconstruct arbitrary objects. They deserialize into predefined schema types, not arbitrary classes.

However, binary formats have their own risks:

Integer overflow in length fields: Binary formats encode string and array lengths as integers. If the deserializer allocates memory based on an attacker-controlled length field without validation, integer overflows can lead to buffer overflows - the same pattern as in web server exploitation.

text
MessagePack format:
[type byte] [length: 4 bytes] [data: length bytes]
If length = 0xFFFFFFFF and the code computes length + 1 in
32-bit arithmetic before calling malloc, the size wraps to 0,
but the read still copies 4GB.

Deeply nested structures: Formats that support nested objects can be abused with extremely deep nesting, causing stack overflow in recursive parsers or excessive memory allocation.

Schema confusion: If the deserializer does not strictly validate that incoming data matches the expected schema, type confusion vulnerabilities can arise. A field expected to be an integer might be provided as a string, and if the parser does not reject this, subsequent code may mishandle the data.

Schema Validation

Schema validation is the practice of verifying that deserialized data matches a predefined structure before processing it. Binary formats like Protocol Buffers enforce schemas at the protocol level, making it harder (but not impossible) for attackers to inject unexpected types or structures. Language-native serialisation (Java, PHP, Python) typically performs no schema validation.

Defence Against Deserialisation Attacks

The most effective defences are:

  1. Never deserialize untrusted data with language-native serialisation. Use JSON, Protocol Buffers, or similar formats that do not reconstruct arbitrary objects, and keep polymorphic type handling (Jackson default typing, fastjson autotype) switched off.

  2. Allowlist deserialisation filters: If you must use native serialisation (for backward compatibility, etc.), configure a filter that only permits specific, known-safe classes. Java 9+ provides ObjectInputFilter for this purpose.

  3. Integrity verification: Sign serialised data with an HMAC before storing or transmitting it. Verify the signature before deserialisation. This prevents an attacker from modifying the serialised bytes.

  4. Reduce the gadget surface: Remove unnecessary libraries from the classpath. If Apache Commons Collections is not needed, removing it eliminates a major source of gadget chains.

  5. Isolate deserialisation: If you must deserialize untrusted data, do it in a sandboxed process with minimal privileges, so even successful exploitation has limited impact.

Deserialisation is fundamentally about converting data into behaviour. When the data is attacker-controlled, the behaviour is too. The only defensible approach is to strictly limit what objects can be created, and to ensure no dangerous method chains can be reached from any of them.