Java Serialization Risks and Safer Alternatives Explained
Why native Java deserialization is dangerous, how gadget chains work, how to filter with ObjectInputFilter and what to use instead.

ObjectInputStream.readObject() is one of the most dangerous methods in the JDK. It reads a stream of bytes, decides from the bytes which classes to instantiate and runs their code, all before returning a value your code can inspect. If an attacker supplies the bytes, the attacker chooses which classes run. Java's own designers have called serialization a "horrible mistake" and have an announced goal of removing it. Yet it persists in session stores, caches, message queues and RPC protocols, which is why deserialization flaws have driven some of the most severe vulnerabilities in Java software. This post explains the mechanism, shows an exploit-shaped example without a working payload, then covers the defences in order of strength. For the security practice around it, see preventing insecure deserialization. The related class design topic is building immutable classes, and the Java security checklist before release lists this among the checks.
What native serialization does
A class opts in by implementing java.io.Serializable. The JVM can then write its fields to a byte stream with ObjectOutputStream and rebuild an equivalent object with ObjectInputStream. The convenient part is that it handles object graphs, cycles and inheritance automatically. The risky part is how reconstruction works:
package dev.javahacks.ser;
import java.io.*;
public class Session implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
private final String user;
private final boolean admin;
public Session(String user, boolean admin) {
this.user = user;
this.admin = admin;
}
public String user() { return user; }
public boolean admin() { return admin; }
}// writing
try (var out = new ObjectOutputStream(new FileOutputStream("session.bin"))) {
out.writeObject(new Session("ana", false));
}
// reading
try (var in = new ObjectInputStream(new FileInputStream("session.bin"))) {
Session s = (Session) in.readObject(); // the cast happens AFTER the object is built
}Look at the comment on the read. The stream names the class to create. readObject() loads that class, allocates an instance without calling its constructor, fills in the fields from the stream and calls any readObject method the class defines. Only then does it return, and only then does your cast to Session run. If the stream contained a different class, the cast throws ClassCastException, but the other class's deserialization code has already executed. The check is too late to help.
Gadget chains
The classes in the stream do not need to be yours. Any class on the classpath that implements Serializable can be named, and some of them, in libraries such as older Apache Commons Collections, Spring, Groovy and others, perform dangerous operations in methods that deserialization triggers automatically: readObject, readResolve, hashCode when put into a map, compareTo when sorted. An attacker finds a sequence of such classes, a gadget chain, where each step's automatic call leads into the next, until the last step does something like invoke a method by reflection or load a remote class. None of the classes is a bug on its own; the vulnerability is that deserialization lets someone else compose them.
The shape of a chain, without any working payload, is:
readObject() on HashMap
-> calls hashCode() on the key
-> key is a class whose hashCode() calls a method on a "transformer"
-> the transformer invokes a method chosen by data in the stream
-> the data names Runtime.exec with an attacker's commandTools exist that generate such payloads for known library versions, which is why a vulnerable endpoint can be exploited by anyone who has the library list. A service that deserializes bytes from a request, a cookie, a message or a cache entry that others can write is exposed. The class of bug has had many names and many CVEs, and the lesson is structural: the risk is in the act of deserializing untrusted data, not in any single library.
Defence 1: do not deserialize untrusted data
The only complete defence is not to use native serialization across a trust boundary. A boundary is anything the attacker might influence: HTTP bodies, cookies, uploaded files, message queue contents, shared caches such as Redis that other systems write to, files in user writable directories. Replace it with a format that parses data into data, without choosing classes:
| Format | Class chosen by the data? | Notes |
|---|---|---|
| Native Java serialization | Yes | The risky one |
| JSON with a fixed target type | No | Jackson with a concrete class; avoid enableDefaultTyping and polymorphic Object fields |
| Protocol Buffers, Avro | No | Schema defined; compact; good for services |
| XML with a fixed binding | No | Disable external entities, see preventing XXE |
| Java records with explicit parsing | No | Read the fields yourself |
Even JSON can reintroduce the problem. Jackson's polymorphic typing, when it lets the input name the class (@JsonTypeInfo(use = Id.CLASS) or global default typing), has the same flaw in a different encoding and has produced its own series of CVEs. Use a closed list of subtypes with @JsonSubTypes and names, never class names from the data.
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = CardPayment.class, name = "card"),
@JsonSubTypes.Type(value = BankPayment.class, name = "bank")
})
public sealed interface Payment permits CardPayment, BankPayment {}Defence 2: a deserialization filter
When you cannot remove ObjectInputStream, because a legacy protocol or a third-party system needs it, reduce the damage with a filter. JEP 290, added in Java 9 and backported to updates of 8, introduced ObjectInputFilter, which is consulted for every class before it is instantiated. Prefer an allow list, naming exactly what you expect, and reject everything else:
package dev.javahacks.ser;
import java.io.*;
public final class SafeReader {
private static final ObjectInputFilter FILTER = ObjectInputFilter.Config.createFilter(
"dev.javahacks.ser.Session;java.base/java.lang.*;java.base/java.util.*;" +
"maxdepth=10;maxrefs=1000;maxbytes=65536;!*");
public static Session read(InputStream bytes) throws IOException, ClassNotFoundException {
try (var in = new ObjectInputStream(bytes)) {
in.setObjectInputFilter(FILTER);
return (Session) in.readObject();
}
}
}The pattern syntax is a semicolon separated list evaluated in order. Each entry allows a class or package, ! rejects, and !* at the end rejects anything not allowed above. The numeric limits (maxdepth, maxrefs, maxbytes) guard against denial of service through deeply nested or enormous graphs. A rejected class produces a clear failure before construction:
java.io.InvalidClassException: filter status: REJECTED
at java.base/java.io.ObjectInputStream.filterCheck(ObjectInputStream.java:1412)The filter can also be set for the whole JVM, as a safety net for code you did not write: -Djdk.serialFilter="dev.javahacks.**;java.base/*;!*" or the equivalent property in java.security. Since Java 17, ObjectInputFilter.Config.setSerialFilterFactory allows a per-stream context aware filter. Keep the allow list small and under version control, and remember that allowing java.util.* broadly permits collections that can participate in chains in older library versions; allow the specific classes you need.
A filter is a mitigation, not a cure. It depends on the list being right, and a list that permits a class with a dangerous method is still exploitable. Treat it as defence in depth behind removing untrusted input.
Defence 3: make your own classes safer
For classes you control and must keep serializable, a few practices reduce the exposure.
Prefer records. Deserialization of a record always goes through the canonical constructor, so validation in the constructor runs, which is not true of ordinary classes where the constructor is bypassed. This closes the "object in an invalid state" hole.
**Validate in readObject.** For a normal class, a private readObject can check invariants after the fields are read, and throw InvalidObjectException if they are wrong:
@Serial
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
if (user == null || user.isBlank()) {
throw new InvalidObjectException("session without a user");
}
}Use a serialization proxy. The pattern from *Effective Java* has writeReplace return a small private nested class, and its readResolve build the real object through the public constructor. The real class's invariants are enforced by the constructor, so a crafted stream cannot produce an object that skips them.
**Make fields transient for secrets** and mark classes that must never be serialized by throwing from writeObject and readObject:
@Serial
private void readObject(ObjectInputStream in) throws IOException {
throw new InvalidObjectException("this class is not serializable");
}**Declare serialVersionUID explicitly.** Without it the JVM computes one from the class structure, and an unrelated change breaks compatibility with stored data: InvalidClassException: local class incompatible: stream classdesc serialVersionUID = ..., local class serialVersionUID = ....
Replacing it in practice
The common places native serialization hides in a Java system, and the usual replacements:
| Where | Typical replacement |
|---|---|
| HTTP session replication in a servlet container | Store a small id in the session and keep state in a database or Redis as JSON; or restrict session attributes to simple types |
Spring Data Redis with JdkSerializationRedisSerializer | Jackson2JsonRedisSerializer or GenericJackson2JsonRedisSerializer with a closed type set, or a typed serializer per cache |
| RMI, JMX and legacy remoting | Move to REST or gRPC; if kept, restrict with a filter and the network |
Message queues (JMS ObjectMessage) | JSON or Protobuf text messages |
| Caching plugins that serialize values | Configure JSON serialization |
Files written by ObjectOutputStream for state | JSON, SQLite or a database |
Search a codebase for ObjectInputStream, readObject, Serializable and JdkSerializationRedisSerializer to find the places. OpenJDK's own direction is to deprecate and eventually remove serialization in favour of explicit mechanisms; the JDK team has described this in a series of articles on the Java platform's serialization future.
Testing
Include a test that proves the filter rejects an unexpected class, so a refactoring that loosens the list is caught:
@Test
void rejectsAClassOutsideTheAllowList() throws Exception {
byte[] bytes;
try (var buf = new ByteArrayOutputStream(); var out = new ObjectOutputStream(buf)) {
out.writeObject(new java.util.concurrent.atomic.AtomicLong(1)); // not on the allow list
out.flush();
bytes = buf.toByteArray();
}
assertThatThrownBy(() -> SafeReader.read(new ByteArrayInputStream(bytes)))
.isInstanceOf(InvalidClassException.class)
.hasMessageContaining("REJECTED");
}When this does not apply
Serialization between two components that you control, inside one trust boundary and over a channel nobody else can write to, is lower risk, though still best replaced the next time the code is touched. In-process uses such as deep copying through Serializable are not a network risk, though they are slow and fragile. Never conclude that a filtered stream is safe because the filter exists; verify the allow list contains only classes with no dangerous behaviour. The reference documents are JEP 290 on filtering incoming serialization data, the Java Serialization Filtering guide and the OWASP deserialization cheat sheet.


