Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Edited by sciSpider Java v3.0

Every serializable container class that has private mutable instance variables must defensively copy them in the readObject method. An adversary can append extra references to the variables to generate a new byte stream. When deserialized, this byte stream allows the creation of a container instance whose internal variable references will be attacker controllable. Consequently, this allows the instance of the container class to mutate and violate its guarantees.

Noncompliant Code Example

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 value of the date sub-object.

Code Block
bgColor#FFcccc
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
  }
}

Compliant Solution

This compliant solution creates a defensive copy of the mutable Date object in the readObject method.

Code Block
bgColor#ccccff
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
  ois.defaultReadObject();
  //defensively copy the mutable component
  date = new Date(date.getTime());
  //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. 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]\].

Risk Assessment

Failure to defensively copy mutable components during deserialization can violate the immutability contract of an object.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

SER34- J

low

probable

medium

P4

L3

Automated Detection

TODO

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

References

Wiki Markup
\[[API 06|AA. Java References#API 06]\]
\[[Sun 06|AA. Java References#Sun 06]\] "Serialization specification: A.6  Guarding Unshared Deserialized Objects"
\[[Bloch 08|AA. Java References#Bloch 08]\] Item 76: "Write readObject methods defensively"


SER33-J. Do not serialize instances of inner classes      12. Serialization (SER)      12. Serialization (SER)