Versions Compared

Key

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

...

This noncompliant code example fails to defensively copy the mutable Date object date. An attacker might be able to create an instance of MutableSer whose 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.

Code Block
bgColor#FFcccc

class MutableSer implements Serializable {
  private static final Date epoch = new Date(0);
  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
  }
}

...

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
}

...

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

SER06-J

low

probable

medium

P4

L3

Automated Detection

Tool
Version
Checker
Description
Coverity7.5UNSAFE_DESERIALIZATIONImplemented

Related Guidelines

MITRE CWE

CWE-502. Deserialization of untrusted data

...

[API 2006]

 

[Bloch 2008]

Item 76, Write readObject methods defensively

[Sun 2006]

Serialization Specification, A.6, Guarding Unshared Deserialized Objects

 

      13. Serialization (SER)