Video in progress
Why is Java's standard serialization mechanism (Serializable) dangerous, and what is serialVersionUID for?
readObject can create any class on the classpath from untrusted bytes and call its methods, and through gadget chains this has gone as far as RCE. serialVersionUID checks that class versions are compatible.
📖 Answer
If you don't write a serialVersionUID, the JVM computes it from the class structure. Even if you add one method to the class, the ID changes, and reading old data fails with InvalidClassException: local class incompatible. In prod this looks like this: a session or cache entry in Redis can't be read after a deploy.
public class CartItem implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
private String sku;
private transient PriceCalculator calc; // not serialized
}
Now the security side. Deserialization doesn't call a constructor, but it does call methods like readObject and readResolve. If libraries like Commons Collections are on the classpath, a specially crafted byte stream can reach Runtime.exec through a chain of those methods. Many RCE vulnerabilities in 2015 came from this.
What to do:
- never read data that comes from outside with
ObjectInputStream; - if you have to, give it a list of allowed classes with
ObjectInputFilter(Java 9+; the JVM-widejdk.serialFiltercomes from it too; Java 17 added a filter factory that chooses a filter by context, JEP 415); - for network and storage, use formats like JSON, Protobuf or Avro: they have schemas and carry only data.
Even the Java architects have called standard serialization one of the language's biggest mistakes. Avoiding it in new code is the normal thing to do.
Sign up to mark studied questions and save your progress.