Skip to content
javahacks.dev
Security

Insecure Deserialization Java Prevention With Serial Filters

Prevent insecure deserialization in Java: avoid ObjectInputStream on untrusted data, use serial filters, safe formats like JSON and gadget chain awareness.

6 min read
Summarize in AI
Flat illustration of an object serialised to JSON and read back, with the Spring Security, YAML and OpenAPI Initiative logos.

Java serialization turns objects into bytes and back. The reading side creates the objects named in the bytes and calls their methods before the application receives the result. If an attacker controls the bytes, they choose which classes get instantiated.

The risk

java
try (ObjectInputStream in = new ObjectInputStream(request.getInputStream())) {
    Object payload = in.readObject();            // dangerous on untrusted data
}

Whatever class the stream describes is loaded and its readObject runs. A gadget chain links methods in classes already on the classpath, often in commons-collections, Spring, or the JDK itself, so that deserialization ends up calling Runtime.exec. Tools like ysoserial generate such payloads. Cast checks happen after the damage. This vulnerability class has produced many critical CVEs and appears in the OWASP list, see OWASP Top Ten for Java.

Where it hides

  • HTTP endpoints or message queues that accept serialized objects.
  • RMI and JMX endpoints, legacy remoting protocols.
  • Session stores and caches that serialize objects with ObjectOutputStream, if an attacker can write to the store.
  • Cookies or hidden form fields holding serialized state (view state in JSF with client-side saving, see JSF view state).
  • Libraries: Jackson with default typing enabled, XStream, Kryo, SnakeYAML with arbitrary types.

Fix 1: do not deserialize untrusted objects

Use a data format that maps to known types. With Jackson:

java
record OrderRequest(String customer, int quantity) { }

OrderRequest order = mapper.readValue(body, OrderRequest.class);

The mapper builds only the declared class. Avoid enableDefaultTyping and @JsonTypeInfo(use = Id.CLASS) on untrusted input, since they let the payload name the class. If you need polymorphism, use an explicit @JsonSubTypes allowlist, as in Jackson errors. SnakeYAML should load with SafeConstructor or the safe LoaderOptions of recent versions.

Fix 2: a serialization filter when you cannot avoid it

JEP 290 introduced ObjectInputFilter:

java
ObjectInputFilter filter = ObjectInputFilter.Config.createFilter(
        "dev.javahacks.model.*;java.base/java.util.*;!*;maxdepth=10;maxrefs=1000;maxbytes=65536");

try (ObjectInputStream in = new ObjectInputStream(input)) {
    in.setObjectInputFilter(filter);
    Object payload = in.readObject();
}

The pattern is an allowlist: the permitted packages first, then !* rejects everything else, with limits on depth, references and size to stop denial of service. A rejected class throws InvalidClassException before instantiation. Allow only classes you need, and review the list when the data model changes.

Fix 3: a process-wide filter

Set a default for every stream in the JVM:

Text
-Djdk.serialFilter="dev.javahacks.**;java.base/*;!*"

or in conf/security/java.security with jdk.serialFilter. Java 17 and later also support filter factories (ObjectInputFilter.Config.setSerialFilterFactory) for per-context rules. A global filter catches code paths you forgot. Test the application, since libraries such as session replication may need extra allowances.

Reduce the gadget supply

  • Keep dependencies updated: many gadget chains are closed in later versions of commons-collections and similar libraries.
  • Remove unused jars from the classpath.
  • Mark sensitive classes with a readObject that throws, or make them non-serializable.

Detect

Dependency scanners flag known vulnerable libraries, and tools such as Find Security Bugs report ObjectInputStream use. Search the code for readObject, readUnshared, XMLDecoder and XStream. In logs, InvalidClassException: filter status: REJECTED shows a filter at work.

The filter pattern language

A serialization filter is a string of patterns separated by semicolons, checked in order, and the first match decides. The syntax is small enough to learn in a table:

PatternMeaning
com.example.dto.OrderAllow exactly this class
com.example.dto.*Allow every class in this package
com.example.dto.**Allow this package and its sub-packages
!com.example.legacy.*Reject this package
java.base/*Allow classes of the java.base module
maxdepth=10Limit the depth of the object graph
maxrefs=1000Limit the number of references
maxbytes=100000Limit the stream length in bytes
maxarray=10000Limit the size of any array
!*Reject everything not matched earlier

End every allow-list with !*. Without it, an unlisted class is undecided and is allowed. The limits stop denial-of-service attacks that use a small stream that expands into a huge graph, which the class allow-list alone does not.

java
ObjectInputFilter filter = ObjectInputFilter.Config.createFilter(
        "maxdepth=10;maxrefs=1000;maxbytes=65536;com.example.dto.*;java.base/*;!*");
ObjectInputStream in = new ObjectInputStream(stream);
in.setObjectInputFilter(filter);

Apply it to the whole process

A filter set on each stream depends on every developer remembering to call it. A process-wide setting covers streams that nobody remembered, including those inside libraries:

Shell
java -Djdk.serialFilter='maxdepth=10;com.example.dto.*;java.base/*;!*' -jar app.jar

A library that deserializes its own classes will be rejected by a filter that does not list them, and the log shows an InvalidClassException: filter status: REJECTED. Start in a staging environment and read the rejected class names, add the legitimate ones and keep the rest blocked. JDK 17 added a filter factory, jdk.serialFilterFactory, for choosing the filter per stream context when one global string is not enough.

Prove it rejects what it should

A security control that is never tested is an assumption. Serialize an object of a class that is not on the list, and check that reading it fails:

java
@Test
void rejectsClassOutsideAllowList() throws Exception {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    try (ObjectOutputStream out = new ObjectOutputStream(bytes)) {
        out.writeObject(new java.util.concurrent.ConcurrentLinkedQueue<String>());
    }
    ObjectInputFilter filter = ObjectInputFilter.Config.createFilter("com.example.dto.*;!*");

    try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray()))) {
        in.setObjectInputFilter(filter);
        assertThrows(InvalidClassException.class, in::readObject);
    }
}

The test fails the build if someone later widens the pattern to a wildcard that admits too much.

Find the places that read objects

A search finds the code that matters. Look for the stream class and for the hook that classes implement:

Shell
grep -rnE 'ObjectInputStream|readObject\(|readResolve|XMLDecoder|enableDefaultTyping|activateDefaultTyping' src

XMLDecoder and Jackson's default typing are not Java serialization, and both have the same flaw: the input names the classes to create. Jackson's activateDefaultTyping with a permissive validator is a frequent cause. Use a PolymorphicTypeValidator with an allow-list, or avoid polymorphic typing from untrusted input.

The better fix is to stop using it

Java serialization is a format with a long history of vulnerabilities, and the list of safe alternatives is short and boring: JSON with fixed target types, Protocol Buffers, Avro. A message queue, a cache or a session store that holds serialized Java objects is a candidate to replace. Records have a restricted serialization form that does not call a constructor chain you cannot see, and it is safer than the classic one, and still a poor choice for untrusted data.

Make the decision visible in the architecture

Every place that deserializes data is a decision about trust, and a short register records it. List each use: where the bytes come from, who can influence them, which classes are allowed and what filter applies. A cache between two of your own services in a private network is one risk, and a session cookie that a browser sends back is another. The register shows which uses can be removed, which are filtered, and which are still open.

Review it when a dependency is added, because libraries deserialize on their own. A message client or a session store that uses Java serialization by default is a new entry that nobody typed into the code.

Where this does not apply

Records and sealed classes do not make Java serialization safe. Your own trusted internal storage, with authenticated and integrity-protected data, carries less risk, and signing the data adds assurance. For other input-driven flaws see XXE. The reference is the serialization filtering guide, and the OWASP Deserialization Cheat Sheet lists more cases.

Also inJava Core
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.