Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

This rule is an instance of rule 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.

...

This compliant solution creates a defensive copy of the mutable Date object 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 rule SER03-J. Do not serialize unencrypted sensitive data for additional information).

Code Block
bgColor#ccccff
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
  ObjectInputStream.GetField fields = ois.readFields();
  Date inDate = (Date) fields.get("date", epoch);
  // Defensively copy the mutable component
  date = new Date(inDate.getTime());
  // Perform validation if necessary
}

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 writeUnshared() and readUnshared() methods as an alternative [Bloch 2008].

...

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

SER06-J

lowLow

probableProbable

mediumMedium

P4

L3

Automated Detection

Tool
Version
Checker
Description
Coverity7.5UNSAFE_DESERIALIZATIONImplemented

Related Guidelines

MITRE CWE

CWE-502. , Deserialization of untrusted dataUntrusted Data

Bibliography

[API 20062014]

 

[Bloch 2008]

Item 76, "Write readObject methods defensively Methods Defensively"

[Sun 2006]

Serialization Specification, A.6, Guarding Unshared Deserialized Objects

...