Every serializable class that has private mutable instance variables must defensively copy them in the
readObject() method. An attacker can tamper with the serialized form of such a class, appending extra references to the byte stream. When deserialized, this byte stream could allow the creation of a class instance whose internal variable references are controlled by the attacker. Consequently, the class instance can mutate and violate its class invariants.
This rule is an instance of OBJ06-J. Defensively copy mutable inputs and mutable internal components, which applies to constructors and to other methods that accept untrusted mutable arguments. This rule applies the same principle to deserialized mutable fields.
Noncompliant Code Example
This noncompliant code example fails to defensively copy the mutable
date. An attacker might be able to create an instance of
date object contains a nefarious subclass of
Date and whose methods can perform actions specified by an attacker. Any code that depends on the immutability of the subobject is vulnerable.
This compliant solution creates a defensive copy of the mutable
date in the
readObject() method. Note the use of field-by-field input and validation of incoming fields. Additionally, note that this compliant solution is insufficient to protect sensitive data (see SER03-J. Do not serialize unencrypted sensitive data for additional information).
There is no need to copy immutable subobjects. Also, avoid using the subobject's
clone() method because it can be overridden when the subobject's class is not final and produces only a shallow copy. The references to the subobjects themselves must be nonfinal so that defensive copying can occur. It is also inadvisable to use the
readUnshared() methods as an alternative [Bloch 2008].
Failure to defensively copy mutable components during deserialization can violate the immutability contract of an object.
Serialization Not Disabled (Java)
Item 76, "Write
Serialization Specification, A.6, Guarding Unshared Deserialized Objects