Lesson · Serialization & Data Formats
The Serialization Security Problem: deserialization is code execution
15 min readThe Serialization Security Problem
ObjectInputStream does not load data, it reconstructs objects by running their readObject methods, and every class on your classpath contributes behaviour to a payload you did not write. Here is the shape of the attack, the boundaries it reaches, and the filter that stops it.
readObject is a method call, and the payload chooses it
An endpoint accepts a serialized request body, returns 200, and logs a clean request. Somewhere inside the read, before the handler saw anything, a process started on the host. The payload was never data to ObjectInputStream: it was a list of classes to instantiate and methods to run.
For every class descriptor the reader resolves the class, allocates an instance without a constructor, restores fields, and then calls whatever the class defines for that moment: readObject, readResolve, readExternal. Those methods are code you and your dependencies already shipped, and the writer decides which of them run, in what order, and with what state.
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); // everything below runs inside the read, on the reader, before the caller sees anything this.sink.publish(this.command); // both fields arrived from the stream, chosen by its writer }
- Resolve: every class name in the stream is looked up against the classpath and loaded.
- Allocate: instances are created without constructors, so a class's own consistency checks never ran.
- Run: readObject, readResolve and readExternal of every restored class execute in the order the graph dictates.
- Return: your handler receives an ordinary object graph, with no trace of which methods ran on the way in.
Deserialization is not parsing plus allocation, it is parsing plus running code. Anything a readObject does, it does before your validation and before you have seen the object.
Gadget chains: ordinary classes, arranged badly
The attack does not need a malicious class to be present. It composes classes that are already on the classpath, connecting a starting point to a sink through method calls that the restore path triggers. The composition is the exploit, and every link in it is shipped, reviewed code.
The classic shape starts with a container that calls a method on your data while restoring itself, and ends at an operation that runs something. Details differ per library version, the shape does not.
| Stage | Example | Why it is in the chain |
|---|---|---|
| Entry point | HashMap.readObject in java.base | rebuilding the table calls hashCode() on every key it read |
| Dispatcher | a dynamic proxy plus its InvocationHandler | a method call on the key is forwarded to state that arrived in the payload |
| Transformers | library function objects that wrap each other | one call walks the chain until the last link runs |
| Sink | Runtime.exec, a JNDI lookup, a class load | the operation the attacker actually wants |
HashMap.readObjectrebuilds its table and callshashCode()on each key, so restoring the container executes a method on your data.- The key in the stream is a dynamic proxy, and calling a method on it is forwarded to the
InvocationHandlerfrom the same stream. - That handler's
invokeenters a chain of function objects where each link wraps the next, so one call reaches the end of the chain. - The end of the chain is the sink: a process launch, a lookup, or a class load, executed inside
readObject. - The read then returns normally. The service sees a healthy-looking object, and the side effect has already happened.
- Chains are modular, not bespoke. Research tooling published in 2015 (ysoserial) turned them into a library of reusable pieces, and the technique has been rediscovered in new dependencies since.
- The famous links were patched. The JDK hardened its own
sun.reflect.annotation.AnnotationInvocationHandler, and Apache Commons Collections disabled serialization of its unsafe transformers in 3.2.2 and removed them in 4.0. The shape survives the patches. - URLDNS is the harmless one. It triggers a DNS lookup during a read and nothing else; it is used to prove that a service deserializes data at all.
A gadget chain is not a bug in one class. It is a set of ordinary classes agreeing that restoring state means calling these methods.
Where the boundary actually is
Any byte stream that reaches an ObjectInputStream is attack surface, regardless of the protocol that carried it. RMI and JMX are the historical favourites, because they deserialize by design and are often left reachable inside a network. HTTP endpoints that accept serialized bodies, messaging systems, caches and session replication bring the same reader with a friendlier name.
The question that decides safety is not which protocol, it is who can write those bytes. An internal queue with a producer you do not control is as exposed as a public endpoint, and a cache is worse, because it stores the payload until a consumer with a different classpath reads it.
- Internal only is not a control: an internal endpoint is exactly what an attacker reaches for after the first foothold.
- Stores are store-and-forward: a payload can enter a queue or cache from one service and be deserialized by another with a much richer classpath.
- Replication is deserialization with privileges: session replication and cluster state copy objects by serializing them between nodes.
- Your format decision leaks: if any field is whatever Serializable object the caller sent, no filter can know which classes are legitimate.
The boundary is defined by who can write the bytes, not by which protocol carried them.
ObjectInputFilter: an allowlist for classes
JEP 290 added deserialization filtering in Java 9. A filter sees each class and reference as the stream is read, along with the depth, reference count, byte count and array lengths, and it can reject the read before the object exists. Rejection is not subtle: the active read throws InvalidClassException and stops.
You can configure it three ways: the jdk.serialFilter system property (or the security property of the same name) before the runtime reads it, ObjectInputFilter.Config.setSerialFilter for the whole process, or ObjectInputStream.setObjectInputFilter for one stream. A per-stream filter can be set once and only before the first read, which is deliberate: the decision cannot be revised after data has been consumed.
The JDK's own example is example.*;java.base/*;!*: one application package, the core classes needed to read anything, and a final rule that rejects everything else. Read it as a boundary, not a template: java.base/* still admits every class in the core module, collections included, so a stricter list names only the JDK types your data actually uses.
ObjectInputFilter filter = ObjectInputFilter.Config.createFilter( "com.example.dto.*;java.base/*;!*"); // first matching pattern wins, then deny the rest ObjectInputFilter.Config.setSerialFilter(filter); // JVM-wide, once, before any stream is created try (ObjectInputStream in = new ObjectInputStream(bytes)) { in.setObjectInputFilter(filter); // or per stream: once, before the first read OrderDto dto = (OrderDto) in.readObject(); }
- Patterns, in order: a class name, a package with
.*, a package and its subpackages with.**, or a module prefix likemodule/, each optionally starting with!to reject; the first matching pattern decides, and a class that matches nothing is UNDECIDED. - Limits are part of the filter:
maxdepth,maxrefs,maxbytesandmaxarraycap resources the payload would otherwise choose. - Java 17 filter factories (JEP 415):
ObjectInputFilter.Config.setSerialFilterFactorycomposes a filter per stream, which is what one process serving several trust levels needs. - Watch it in production: JDK 17 added the
jdk.DeserializationJFR event, disabled by default, which records the classes read and whether the filter allowed them.
A filter is an allowlist of class names, not a repair. It decides which classes get to run; it cannot make an allowed class's readObject safe.
Deserialization one payload, two outcomes
Classes the payload names
no descriptor read yet
What runs during the read
nothing yet
jdk.serialFilter is not set
every class on the classpath is available to whoever wrote the bytes
A service exposes POST /import and hands the request body straight to ObjectInputStream. Nothing in the handler looks unusual; the bytes are the interface.
What a filter does not fix, and the rule that ends the debate
An allowlist is only as good as its entries. The filter matches class names, not behaviour, so allowing a broad package allows everything inside it, including classes whose readObject does far more than move fields. The useful allowlist is small, data-only, and reviewed like code, because it is code.
Two escape hatches are worth naming. The stream subclassing hooks (replaceObject and resolveObject via enableReplaceObject and enableResolveObject, and the enableSubclassImplementation pair) let a stream manufacture objects during a read; they are gated behind SerializablePermission and documented for trusted subclasses only. Never put them in the path of untrusted data.
- Never deserialize untrusted data. If the bytes come from outside your trust boundary, that is the bug; everything below is damage control.
- If the boundary must exist, filter it, and keep the allowlist to the DTO classes your endpoint actually reads.
- Compose per context with a filter factory (Java 17) when one JVM serves different trust levels.
- Keep dependencies current, and treat a new library as a new member of the allowlist review: the filter cannot tell you that a class you allowed is now dangerous.
- Choose a format that cannot name classes, which is the next lesson, because that removes the mechanism instead of policing it.
Any design that requires deserializing untrusted bytes is the vulnerability. The filter is a seatbelt for a boundary you have not removed yet, not a licence to keep the boundary.
The review that finds these paths
Deserialization boundaries are usually invisible in code review, because they look like a stream read. Make them visible: search the tree for ObjectInputStream, readObject, readExternal and Serializable payloads that cross a process boundary, then ask who can write those bytes.
For each hit, decide: remove the boundary, filter it while you migrate, or document why it is trusted. Anything in the third column needs an owner and a date.
| Path | Who can write the bytes | What to check |
|---|---|---|
| HTTP endpoint that accepts serialized bodies | any caller | do not accept them at all; if unavoidable, allowlist and authenticate |
| RMI or JMX exposed on a port | anyone who can reach the port | treat the port as an execution endpoint; these services deserialize by design |
| Message queue or cache | any producer, including older builds of your own service | consumers must never deserialize arbitrary classes from a shared store |
| Session replication or clustering | another node, possibly on a different version | replication payloads are read with the full application classpath |
| Files from users (imports, uploads, backups) | whoever supplies the file | a file read by ObjectInputStream is an input channel, whatever its extension |
If you cannot answer who can write the bytes, you cannot answer whether it is safe to read them.
readObject runs before your code does
The stream chooses which classes get restored, and restoring a class runs its readObject with attacker-chosen fields. You cannot review your way out of that after the fact, and no library upgrade changes it: the payload names the classes, and the classes bring the code. Filter the boundary while you have one, and plan to remove it.
Interview angles
Why is Java deserialization dangerous?+
ObjectInputStream reconstructs objects by running class-supplied readObject, readResolve and readExternal methods, and the payload chooses which classes on your classpath run. That is code execution driven by data, before the caller sees any object.
What is a gadget chain?+
A composition of classes that are already on the classpath whose restore-time calls (readObject, hashCode, equals, toString) reach a dangerous sink such as a process launch or a JNDI lookup. No single class is malicious; the arrangement is.
A common first hop is HashMap.readObject, because rebuilding the table calls hashCode() on every key. If the key is a dynamic proxy, the call lands in an InvocationHandler from the payload, and a chain of library function objects can carry it to the sink.
Common misconception: Gadget chains only work against applications with one specific vulnerable library.
Follow-up: Which of those classes can a filter exclude?
What does ObjectInputFilter check?+
Every class and reference as the stream is read, plus limits on depth, references, bytes and array length. The first matching pattern decides ALLOWED or REJECTED, and a rejection throws InvalidClassException mid-read, before the object is built.
Where do you configure a filter?+
Globally with the jdk.serialFilter system or security property, or ObjectInputFilter.Config.setSerialFilter before any stream exists; per stream with setObjectInputFilter, which can be called once and only before the first read. Java 17 (JEP 415) adds a filter factory so the filter can be chosen per stream from context.
Is a good allowlist enough?+
It is the difference between mitigation and a design. The filter matches class names, not behaviour, so allowing a library allows everything its readObject does. Keep the list small and data-only, and treat it as a boundary you intend to remove.
Follow-up: So what is the actual fix?
Which APIs should new designs avoid?+
The stream subclassing hooks: replaceObject and resolveObject (via enableReplaceObject and enableResolveObject) and the enableSubclassImplementation pair. They exist for trusted subclasses, are gated behind SerializablePermission, and let a stream produce objects outside the filter's view of the payload.