Quick revision
The short answer
When ObjectInputStream reads untrusted bytes, the bytes choose which classes get instantiated, and any serializable class on the class path can be named. The readObject and similar methods of those classes run during reading, before our code ever sees or casts the result. A gadget chain is a sequence of such methods in ordinary library classes, linked so that reading a crafted stream ends in something dangerous such as running a command; even without a chain, crafted streams can exhaust CPU or memory.
What to remember
In this answer, we saw that ObjectInputStream builds whatever classes the stream names, as long as they are serializable and on the class path, and that their readObject and similar methods run before our code sees the result. A gadget chain links such methods across library classes so that reading a crafted stream reaches a dangerous sink, as public chains in libraries like Commons Collections showed. Even without a chain, deep or huge graphs can cause denial of service, so untrusted data should never reach ObjectInputStream, and filters are the fallback where serialization must stay.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
When ObjectInputStream reads untrusted bytes, the bytes choose which classes get instantiated, and any serializable class on the class path can be named. The readObject and similar methods of those classes run during reading, before our code ever sees or casts the result. A gadget chain is a sequence of such methods in ordinary library classes, linked so that reading a crafted stream ends in something dangerous such as running a command; even without a chain, crafted streams can exhaust CPU or memory.
Why this question is asked
Java deserialization vulnerabilities have been behind some of the most serious incidents in enterprise software, in application servers, build servers and admin consoles. What makes them surprising is that the vulnerable code usually looks harmless: a single readObject() call followed by a cast. Interviewers ask this question to see whether we understand why the danger lies in the data and the class path rather than in our own classes. In this answer, we will recap what ObjectInputStream does with the bytes, see where foreign code runs, build up the idea of a gadget chain with a made-up example, look at the real-world history, and finish with denial of service and the defences.
1A Quick Recap: The Stream Names the Classes
A Java serialization stream is not just data; it is a recipe for building objects. For each object, the stream contains a class descriptor with the fully qualified class name, and ObjectInputStream loads that class, allocates an instance and fills its fields. Nothing in this process asks what type we expect. The only requirement is that the class is on the class path and implements Serializable.
That is the root of the problem. A typical application has thousands of serializable classes on its class path, from the JDK, from Spring, from logging, collections and utility libraries. When the bytes come from an attacker, the attacker picks which of those classes to build and what their fields contain.
Notice when the cast happens. readObject() must completely build whatever object graph the stream describes and return it as Object; only then does the cast to Order check the type. If the stream described something else, the ClassCastException comes too late, because everything interesting already happened inside readObject().
2Where Library Code Runs During Reading
Many serializable classes customise how they are read. HashMap, for example, has a private readObject method that reads each key and value and puts them back into a new table, which means it calls hashCode() on every key. TreeMap and PriorityQueue call a comparator on their elements, and many classes have readResolve or validation logic. All of this is normal and necessary for these classes to work.
So during readObject(), ObjectInputStream runs methods of classes the stream chose, on objects whose fields the stream chose. Our code has not seen anything yet. Any method reachable from those callbacks, such as hashCode(), equals(), compareTo() or toString() of an element, can be triggered by the attacker.
3What a Gadget Chain Is
A gadget is a method in an existing class that does something useful to an attacker when called with attacker-controlled fields. Each gadget on its own is harmless code written for a legitimate purpose. A gadget chain links them: the entry point is a readObject that calls a method on a field, that method calls another method on another field, and so on, until the chain reaches a sink, a method that does something powerful such as invoking a method by reflection, loading a class or running a process.
Here is the shape of a chain, with made-up class names so the idea is clear.
7 messages in order. Play them, or step through them one at a time.
Everything dangerous happened inside readObject(), before the cast.
Notice that the attacker writes no code. They only arrange existing objects and set their fields, and the chain is executed by ordinary method calls that the JDK and libraries make while rebuilding the graph. That is why the fix cannot be a code review of our own classes: the gadgets live in our dependencies.
4Real Chains in Common Libraries
This is not a theoretical concern. Well-known chains were found in Apache Commons Collections 3.x, whose transformer classes could call arbitrary methods by reflection; version 3.2.2 disabled deserialization of the dangerous class by default. Similar chains have been documented in other widely used libraries, and public tools exist that generate payloads for many of them, so an attacker does not need to discover a chain, only to find an endpoint that deserializes their input and a vulnerable library on its class path.
Removing one library does not end the problem, because new chains keep being found in other libraries and sometimes in the JDK itself. The safe assumption is that a large class path always contains some chain.
5Denial of Service Without Any Gadget
Even with no dangerous library present, crafted streams can hurt. A stream can declare an array with two billion elements, so the reader tries to allocate it and runs out of memory. It can build deeply nested HashSets, each containing the previous one twice, so that computing a hash code during reading takes exponential time; a stream of a few kilobytes can keep a CPU busy practically forever. Very deep graphs can also cause StackOverflowError during reading.
| Attack | How | Defence |
|---|---|---|
| Code execution | gadget chain in a library on the class path | never read untrusted streams; allow-list filter |
| Memory exhaustion | huge array length or many objects | filter limits: maxarray, maxrefs, maxbytes |
| CPU exhaustion | nested HashSets with costly hashCode | filter limit: maxdepth |
| Stack overflow | very deep object graph | filter limit: maxdepth |
So the risks are code execution through chains and denial of service through the shape of the graph. Both come from the same place: letting untrusted data decide what to build.
6How We Defend Against It
The real fix is to not use Java serialization on data we do not trust: accept JSON or a schema-based format and map it to our types explicitly. Where serialization must stay, Java 9 and later provide deserialization filters through ObjectInputFilter, which let us allow only specific classes and set limits on depth, array size, number of references and stream size, applied per stream or JVM-wide. Keeping libraries updated and removing unused ones shrinks the supply of gadgets, but it is a second line of defence, never the first.
7Follow-up questions
Is it safe if we check the type after readObject()?
No. The type check, whether a cast or instanceof, runs after readObject() has already built the whole graph and run every readObject, readResolve and hashCode along the way. To control what gets built, we need a filter that is consulted during reading, or a format that never names classes.
Does using only our own serializable classes make us safe?
No. The attacker can name any serializable class on the class path, not just the ones we expect, so the libraries we depend on matter as much as our own code. Only an allow-list filter restricts the classes to ours.
Are other formats immune?
Formats that never let the data choose classes, such as plain JSON mapped to fixed types or Protobuf, are not affected by this class of attack. But JSON libraries with polymorphic typing that reads class names from the data, YAML loaders that build arbitrary objects, and similar features in other languages recreate the same risk.
8Conclusion
In this answer, we saw that ObjectInputStream builds whatever classes the stream names, as long as they are serializable and on the class path, and that their readObject and similar methods run before our code sees the result. A gadget chain links such methods across library classes so that reading a crafted stream reaches a dangerous sink, as public chains in libraries like Commons Collections showed. Even without a chain, deep or huge graphs can cause denial of service, so untrusted data should never reach ObjectInputStream, and filters are the fallback where serialization must stay.
Open with
Deserializing untrusted data is dangerous because the stream, not my code, decides which classes get instantiated. Each object in the stream carries a class name, and ObjectInputStream will load and build any serializable class on the class path, filling in fields with whatever values the attacker chose.
Then, if they want more
And many classes run code while being read: HashMap's readObject calls hashCode on every key, sorted collections call comparators, other classes have readResolve or validation. All of that runs inside readObject, before my cast to the expected type, so the cast gives no protection. A gadget chain is a way of linking those callbacks.
The entry point is a readObject that calls a method on a field, that method calls another method on another field, and so on through ordinary library classes until the chain reaches a sink, for example a reflective method call that ends up running a command. The attacker writes no code; they just arrange existing objects.
Real chains were found in Apache Commons Collections and other common libraries, and tools exist that generate payloads, so a large class path should be assumed to contain one. Even without a chain, a crafted stream can declare a huge array or deeply nested sets and exhaust memory or CPU.
So I never deserialize untrusted input with ObjectInputStream; I use JSON or a schema format, and where serialization must stay, an allow-list filter with limits.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 9
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- The Java Language Specification, Java SE 21, Java SE 21 API documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Why is deserializing untrusted data with ObjectInputStream dangerous? Explain what a...": https://scrivio-interview-library.netlify.app/java/serialization/ea79b749bb/