Best Practices for Safe Serialization
You'll learn the essential guidelines for using Java serialization securely and avoiding common pitfalls.
Serialization is powerful but dangerous—it's like opening a door into your application's internals. Over the previous lessons, you've seen how attackers can exploit deserialization, how object graphs can spiral out of control, and how class evolution causes maintenance headaches. Now let's consolidate the defensive strategies into actionable best practices.
The Golden Rules
Never deserialize untrusted data. This is rule zero. If you don't control the source of the serialized bytes, don't deserialize them. Period. Even with input filtering, attackers constantly discover new gadget chains. The only safe serialized data is data you created yourself in a controlled environment.
Use sealed classes and immutability. When you must serialize, prefer immutable objects with final fields. Sealed classes (from recent Java versions) limit which classes can be in your object graph, reducing the attack surface.
Always validate in readObject. Every custom readObject method should validate all fields after reading them. Check ranges, nullability, and invariants. Don't assume deserialized data is valid just because it compiled—attackers can craft binary data that bypasses your constructors entirely.
Implement readResolve for singletons. Protect singleton patterns from being broken by deserialization.
Filter object streams. Use ObjectInputFilter (Java 9+) or ValidatingObjectInputStream to whitelist acceptable classes before deserialization happens.
Consider alternatives. JSON, Protocol Buffers, or custom formats give you more control and are generally safer than native serialization.
Think of serialization like handling hazardous materials: use protective equipment (validation), limit exposure (minimize usage), and prefer safer alternatives when available.
Key Takeaway:
Safe serialization requires treating all deserialized data as hostile, validating rigorously, limiting class exposure, and preferably avoiding Java serialization altogether in favor of modern alternatives.