Scrivio Interview library
ConceptIntermediate7 min read · updated 12 November 2026

Why is Java native deserialization of untrusted data dangerous, and what protections does the JDK offer? How do similar risks appear with Jackson and YAML?

Java native deserialization is dangerous because ObjectInputStream will create objects of any serializable class on the classpath and run their readObject and related methods, and attackers chain those methods (gadget chains) into remote code execution. The JDK offers ObjectInputFilter (JEP 290, Java 9 and backported) to allowlist classes and limit depth, array size and references, and since Java 17 a filter factory (JEP 415) can choose a filter per context. Jackson and YAML have the same problem when the input is allowed to name the class to create, so we use explicit subtypes or a strict PolymorphicTypeValidator with Jackson, safe constructors with YAML, and best of all we never deserialize untrusted Java objects at all.

Why this question is asked

Deserialization bugs gave us some of the worst Java vulnerabilities of the last decade, from Apache Commons Collections gadgets to attacks on application servers, message brokers and caches. They are hard to see in code review, because the dangerous line is just readObject(). Interviewers ask this to check whether we understand why the attack works, not just that it exists, and whether we know the same idea appears in JSON and YAML libraries. In this answer, we will recap what deserialization does, see how a gadget chain turns it into code execution, look at ObjectInputFilter and filter factories, and then move to Jackson and YAML.

1A Quick Recap of Java Serialization

Serialization turns an object graph into bytes, and deserialization turns the bytes back into objects. Java's built-in mechanism works on any class that implements java.io.Serializable. ObjectOutputStream writes the class name and field values, and ObjectInputStream reads them back.

The important detail is what ObjectInputStream does with the class name in the stream. It looks the class up on the classpath, creates an instance without calling the normal constructor, fills its fields, and calls special methods the class may define, such as readObject, readResolve or readExternal. The bytes decide which classes are created. If those bytes come from a user, the user decides.

Java
try (var in = new ObjectInputStream(request.getInputStream())) {
Object o = in.readObject(); // classes named in the stream are loaded and their readObject() runs
Cart cart = (Cart) o; // the cast happens too late: the damage is done during readObject()
}

Notice the cast. Many developers assume it protects them, because a wrong type throws ClassCastException. But by the time the cast runs, every object in the graph has already been created and its methods have already executed.

2How a Gadget Chain Becomes Remote Code Execution

A gadget is an ordinary class on the classpath whose deserialization method does something with its fields, such as calling hashCode() on a key, invoking a method by name, or comparing two objects. None of these classes is malicious alone. An attacker builds a graph where one gadget's field holds another gadget, so that readObject on the outer object triggers a method on the next, and so on, until the last link calls something powerful like Runtime.exec or loads a class from bytes.

Tools such as ysoserial collected chains for popular libraries, so an attacker only needs to know that, say, a certain version of Commons Collections or Spring is on the classpath. The application does not even have to use those classes; it is enough that they are loadable. That is why this vulnerability is so broad: any endpoint, cache or queue that deserializes untrusted bytes is exposed to every gadget in every dependency.

Step throughA gadget chain during readObject()
AttackerServiceObjectInputStreamGadget classes
POST crafted serialized bytes
readObject()
create outer gadget, call its readObject()
field.hashCode() triggers next gadget
reflection invokes Runtime.exec(...)
returns some object
cast fails: too late, the command already ran

7 messages in order. Play them, or step through them one at a time.

The application never asked for these classes; being on the classpath was enough.

3What the JDK Offers: ObjectInputFilter

JEP 290 added ObjectInputFilter in Java 9 (and backported it to 8u121 and later). A filter is called for each class, and also reports array lengths, graph depth, number of references and stream size, so it can reject both unexpected classes and oversized graphs that would exhaust memory. We can set a process-wide filter with the jdk.serialFilter system property, or a filter on a single stream.

The safe style is an allowlist: name the packages we expect and end with !* to reject everything else. A denylist of known gadgets is always one discovery behind.

Java
ObjectInputFilter filter = ObjectInputFilter.Config.createFilter(
"com.shop.cart.*;java.util.ArrayList;java.lang.*;maxdepth=10;maxarray=10000;maxbytes=1048576;!*");
try (var in = new ObjectInputStream(bytes)) {
in.setObjectInputFilter(filter);
Cart cart = (Cart) in.readObject(); // allowed classes only
}
// A stream naming org.apache.commons.collections.functors.InvokerTransformer:
// java.io.InvalidClassException: filter status: REJECTED

Java 17 added JEP 415, context-specific filters. Instead of one global pattern, we register a filter factory with ObjectInputFilter.Config.setSerialFilterFactory (or the jdk.serialFilterFactory property). The JVM calls the factory each time a stream is created, so it can combine the global filter with one chosen for the current context, for example a strict allowlist when a particular library deserializes. Java 17 also added helpers such as ObjectInputFilter.allowFilter, rejectFilter and merge to build these filters in code.

4The Same Risk in Jackson

JSON looks safe because it only holds strings, numbers, arrays and objects. The risk returns when the library lets the JSON decide which Java class to create. Jackson does this with polymorphic typing: a property such as @class carries a class name. With the old enableDefaultTyping, or with @JsonTypeInfo(use = Id.CLASS) on a field of type Object, an attacker can name any class with a dangerous setter or constructor, and Jackson has had a long list of CVEs about such gadget classes.

The fix is to keep the set of possible types closed. We prefer logical type names with explicit subtypes, so the JSON can only choose from classes we listed. If we truly need class-based typing, we use activateDefaultTyping with a strict PolymorphicTypeValidator that allows only our packages.

Java
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = CardPayment.class, name = "card"),
@JsonSubTypes.Type(value = BankPayment.class, name = "bank")})
sealed interface Payment permits CardPayment, BankPayment {}
// {"type":"card", ...} -> CardPayment
// {"type":"java.net.URL", ...} -> InvalidTypeIdException: not a known subtype
var ptv = BasicPolymorphicTypeValidator.builder()
.allowIfSubType("com.shop.events.") // only our own event classes
.build();
mapper.activateDefaultTyping(ptv, ObjectMapper.DefaultTyping.NON_FINAL);

5The Same Risk in YAML

YAML supports tags that name a type, such as !!javax.script.ScriptEngineManager. SnakeYAML's general Constructor used to create any class a tag named, which led to code execution when applications parsed YAML from users with new Yaml(). SnakeYAML 2.0 changed the default so that global tags are not allowed unless we configure them, and offers SafeConstructor, which builds only standard maps, lists and scalars.

So with YAML from outside, we parse with SafeConstructor or into a specific class with a restricted set of allowed tags, and we keep the library current. Spring Boot reads its own configuration YAML with safe settings, but our own code that parses user-uploaded YAML is our responsibility.

Java
Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions()));
Map<String, Object> data = yaml.load(input); // only maps, lists, strings, numbers, booleans
// input "!!javax.script.ScriptEngineManager [...]" -> ConstructorException: could not determine a constructor
Where the input chooses the class
FormatDangerous settingSafer choice
Java serializationObjectInputStream on untrusted bytesDo not use; else allowlist filter
Jackson JSONDefault typing or Id.CLASS on Object fieldsId.NAME with explicit subtypes
Jackson JSONactivateDefaultTyping with permissive validatorStrict PolymorphicTypeValidator
SnakeYAMLConstructor allowing global tagsSafeConstructor, SnakeYAML 2

6The Best Practice: Do Not Deserialize Untrusted Objects

Filters and validators reduce the risk, but the real lesson is that formats which let input choose classes are a poor fit for untrusted data. The reliable design is to accept plain data, such as JSON or Protobuf, and map it onto a fixed, known type: a record or DTO with ordinary fields. Then the worst an attacker can do is send wrong values, which normal validation handles.

So when we review a service, we look for ObjectInputStream, XMLDecoder, Java serialization in caches, sessions and message converters, and polymorphic typing in Jackson configuration. Each one is either removed or locked down with an allowlist.

7Follow-up questions

Does a filter with a denylist of known gadgets protect us?

Only partly. New gadget chains are found in popular libraries regularly, and a denylist cannot know about them. An allowlist ending in !* rejects every class we did not expect, which also blocks future gadgets. Denylists are a short-term mitigation during an incident, not a design.

Is it safe if the bytes only come from our own Redis cache?

It is safer, but the cache becomes part of the attack surface. Anyone who can write to that cache, through another bug or a misconfigured network, can then run code in every service that reads it. Using JSON serializers for caches, or at least an allowlist filter, removes that chain of trust.

8Conclusion

In this answer, we saw that ObjectInputStream creates whatever classes the stream names and runs their methods before our code can check the type, which lets gadget chains reach remote code execution. The JDK gives us ObjectInputFilter from JEP 290 to allowlist classes and limit depth and size, and Java 17's filter factories from JEP 415 to choose filters per context. Jackson and YAML have the same weakness when input names the class, fixed with explicit subtypes, strict validators and safe constructors. The best protection is not to deserialize untrusted Java objects at all and to map plain data onto known types.

What to say in the interviewAbout 90 seconds aloud

Open with

Native deserialization is dangerous because ObjectInputStream reads class names from the stream, creates those objects and runs their readObject or readResolve methods. If the bytes come from an attacker, they choose the classes.

Then, if they want more

Attackers combine ordinary library classes on our classpath into gadget chains, where one object's deserialization calls a method on the next until something like Runtime.exec runs. The cast to our expected type happens afterwards, so it does not help. The JDK answer is ObjectInputFilter from JEP 290.

I set an allowlist pattern with our packages, limits on depth, array size and bytes, and end it with !* so everything else is rejected. Since Java 17, JEP 415 lets me register a filter factory that picks a filter for each stream, so different libraries can have different allowlists.

The same problem appears in Jackson when polymorphic typing lets the JSON carry a class name, for example the old default typing or Id.CLASS on an Object field. I use logical type names with explicit subtypes, or a strict PolymorphicTypeValidator if I really need class names. With YAML I use SafeConstructor, and SnakeYAML 2 disallows global tags by default.

But my real rule is not to deserialize untrusted Java objects at all: accept JSON or Protobuf and map it onto a fixed DTO, so the worst case is a bad value that validation rejects.

About this answer

Last updated
12 November 2026
Versions it names
Java 17, 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
OWASP Top Ten
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 Java native deserialization of untrusted data dangerous, and what protections...": https://scrivio-interview-library.netlify.app/spring-boot/web-security-threats/0dbe4f5d99/