...
There is no defensive copying of the mutable components or sub-objects (Date
object) in this noncompliant code example. An attacker may be able to create an instance of MutableSer
with a mutated so that all invariants hold when validation is carried out and later, mutate the value of the date
sub-object to violate the class's contract. Any code that depends on the immutability of the sub-object is vulnerable.
Code Block | ||
---|---|---|
| ||
class MutableSer implements Serializable { private Date date = null; // Mutable component public MutableSer(Date d){ date = new Date(d.getTime()); // Constructor performs defensive copying } private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { ois.defaultReadObject(); // Perform validation if necessary } } |
...
Wiki Markup |
---|
There is no need to copy immutable sub-objects. Also, avoid using the sub-object's {{clone()}} method because it can be overridden when the sub-object's class is non-final. Moreover, it produces only a shallow copy. The sub-objects ({{date}}) themselves must be non-final so that defensive copying can occur. It is also inadvisable to use the {{writeUnshared()}} and {{readUnshared()}} methods as an alternative \[[Bloch 08|AA. Java References#Bloch 08]\]. |
...