Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Changed name to make sense.

...

Validating deserialized objects establishes that the object state is within defined limits and ensures that all transient and static fields have secure values. However, fields that are declared final with a constant value will always be restored to the same constant value after deserialization. For example, the value of the field private transient final n = 42 will be 42 after deserialization rather than 0. Deserialization produces default values for all other cases.

Noncompliant Code Example (Singleton)

Wiki Markup
In this noncompliant code example \[[Bloch 2005|AA. References#Bloch 05]\], a class with singleton semantics uses the default serialized form, which fails to enforce any implementation-defined invariants. Consequently, malicious code can create a second instance even though the class should have only a single instance. For purposes of this example, we assume that the class contains only nonsensitive data.

Code Block
bgColor#FFcccc
public class NumberData extends Number {
  // ...implement abstract Number methods, like Number.doubleValue()...

  private static final NumberData INSTANCE = new NumberData ();
  public static NumberData getInstance() {
    return INSTANCE;
  }

  private NumberData() {
    // Perform security checks and parameter validation
  }

  protected int printData() {
    int data = 1000;
    // print data
    return data;
  }
}

class Malicious {
  public static void main(String[] args) {
    NumberData sc = (NumberData) deepCopy(NumberData.getInstance());
    // Prints false; indicates new instance
    System.out.println(sc == NumberData.getInstance());  
    System.out.println("Balance = " + sc.printData());
  }

  // This method should not be used in production code
  public static Object deepCopy(Object obj) {
    try {
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      new ObjectOutputStream(bos).writeObject(obj);
      ByteArrayInputStream bin =
          new ByteArrayInputStream(bos.toByteArray());
      return new ObjectInputStream(bin).readObject();
    } catch (Exception e) { 
      throw new IllegalArgumentException(e);
    }
  }
}

Compliant Solution

This compliant solution adds a custom readResolve() method that replaces the deserialized instance with a reference to the appropriate singleton from the current execution. More complicated cases may also require custom writeObject() or readObject() methods in addition to (or instead of) the custom readResolve() method.

...

More information on singleton classes is available in rule MSC07-J. Prevent multiple instantiations of singleton objects.

Noncompliant Code Example

This noncompliant code example uses a custom-defined readObject() method but fails to perform input validation after deserialization. The design of the system requires the maximum ticket number of any lottery ticket to be 20,000, and the ninimum ticket number be greater than 0. However, an attacker can manipulate the serialized array to generate a different number on deserialization. Such a number could be greater than 20,000, or could be 0 or negative.

Code Block
bgColor#FFcccc
public class Lottery implements Serializable {	
  private int ticket = 1;
  private SecureRandom draw = new SecureRandom();

  public Lottery(int ticket) {
    this.ticket = (int) (Math.abs(ticket % 20000) + 1);
  }

  public int getTicket() {
    return this.ticket;	
  }

  public int roll() {
    this.ticket = (int) ((Math.abs(draw.nextInt()) % 20000) + 1);
    return this.ticket;
  }

  public static void main(String[] args) {
    Lottery l = new Lottery(2);
    for (int i = 0; i < 10; i++) {
      l.roll();
      System.out.println(l.getTicket());
    }
  }

  private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    in.defaultReadObject();
  }
}

Compliant Solution

Any input validation performed in the constructors must also be implemented where ever an object can be deserialized. This compliant solution performs field-by-field validation by reading all fields of the object using the readFields() method and ObjectInputStream.GetField constructor. The value for each field must be fully validated before it is assigned to the object under construction. For more complicated invariants, this may require reading multiple field values into local variables to enable checks that depend on combinations of field values.

...

Note that this compliant solution is insufficient to protect sensitive data. See rule SER03-J. Do not serialize unencrypted, sensitive data for additional information.

Compliant Solution (Transient)

This compliant solution marks the fields as transient, so they are not serialized. The readObject() method initializes them using the roll() method. This class need not be final, as its fields are private and cannot be tampered with by subclasses, and its methods have been declared final, to prevent subclasses from overriding and ignoring them.

Code Block
bgColor#ccccff
public class Lottery implements Serializable {
  private transient int ticket = 1;
  private transient SecureRandom draw = new SecureRandom();

  public Lottery(int ticket) {
    this.ticket = (int) (Math.abs(ticket % 20000) + 1);
  }

  public final int getTicket() {
    return this.ticket;
  }

  public final int roll() {
    this.ticket = (int) ((Math.abs(draw.nextInt()) % 20000) + 1);
    return this.ticket;
  }

  public static void main(String[] args) {
    Lottery l = new Lottery(2);
    for (int i = 0; i < 10; i++) {
      l.roll();
      System.out.println(l.getTicket());
    }
  }

  private void readObject(ObjectInputStream in)
          throws IOException, ClassNotFoundException {
    in.defaultReadObject();
    this.draw = new SecureRandom();
    roll();
  }
}

Compliant Solution (Non-serializable)

This compliant solution simply does not mark the Lottery class serializable.

Code Block
bgColor#ccccff
public final class Lottery {	
  // ...
}

Risk Assessment

Using the default serialized form for any class with implementation-defined invariants may result in the malicious tampering of class invariants.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

SER07-J

medium

probable

high

P4

L3

Related Guidelines

MITRE CWE

CWE-502, "Deserialization of Untrusted Data"

Secure Coding Guidelines for the Java Programming Language, Version 3.0

Guideline 5-3. View deserialization the same as object construction

Bibliography

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="447a75a063da9f21-32f4e05e-4e88426b-b6f3881d-3aadbec5d1a1fe016138c27c"><ac:plain-text-body><![CDATA[

[[API 2006

AA. References#API 06]]

Class Object, Class Hashtable

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="37744478d3a073d6-ec368652-4f25480b-9b50ab16-48306bd7a7159e4e660a7c41"><ac:plain-text-body><![CDATA[

[[Bloch 2008

AA. References#Bloch 08]]

Item 75, Consider using a custom serialized form

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="09e180e89af304f9-81299714-41ee452d-aeb6a733-1ebcd76743ac1d0efb313008"><ac:plain-text-body><![CDATA[

[[Greanier 2000

AA. References#Greanier 00]]

 

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="e3688171674aaa53-4b0a48ee-45b74a5e-a2e8a8f2-48f2abbf287ed289bd9dc1ef"><ac:plain-text-body><![CDATA[

[[Harold 1999

AA. References#Harold 99]]

Chapter 11, Object Serialization, Validation

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="c4561c5e6ddb4317-fbce29c1-4ff94ed1-82279b3f-60cc381efd959a72e1ac2ca4"><ac:plain-text-body><![CDATA[

[[Hawtin 2008

AA. References#Hawtin 08]]

Antipattern 8. Believing deserialisation is unrelated to construction

]]></ac:plain-text-body></ac:structured-macro>

...