Versions Compared

Key

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

Object Although serialization allows saving an object's state to be saved as a sequence of bytes and its reconstitution then reconstituted at a later time. The primary application of serialization is in Java Remote Method Invocation (RMI) wherein objects must be (un)packed and exchanged between distributed virtual machines. It also finds extensive use in Java Beans.Java language's access control mechanisms cease to remain effective after a class is serialized. Consequently, any sensitive data that was originally protected using , it provides no mechanism to protect the serialized data. An attacker who gains access to the serialized data can use it to discover sensitive information and to determine implementation details of the objects. An attacker can also modify the serialized data in an attempt to compromise the system when the malicious data is deserialized. Consequently, sensitive data that is serialized is potentially exposed, without regard to the access qualifiers (such as the private keyword) gets exposedthat were used in the original code. Moreover, the security manager does not provide any checks to guarantee cannot guarantee the integrity of the deserialized data.

Examples of sensitive data that should never be serialized include cryptographic keys, digital certificates, and classes that may hold references to sensitive data at the time of serialization.

This rule is meant to prevent the unintentional serialization of sensitive information. SER02-J. Sign then seal objects before sending them outside a trust boundary applies to the intentional serialization of sensitive information.

Noncompliant Code Example

The data members of class Point are declared as private. The saveState and readState methods are used for serialization and de-serialization respectively. The coordinates (x,y) that are written to the data stream are susceptible Assuming the coordinates are sensitive, their presence in the data stream would expose them to malicious tampering.

Code Block
bgColor#FFcccc

public class Point implements Serializable {

  private double x;
  private double y;

  public Point(double x, double y) {
    this.x = x;
    this.y = y;
  }

 
 public Point()
 {
    //no No-argument constructor
  } 
}

import java.io.Serializable;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

public class Coordinates extends Point implements Serializable {

  public static void main(String[] args) {
 {
   FileOutputStream fout = null;
    try {
      Point p = new Point(5, 2);
   FileOutputStream   fout = new FileOutputStream("point.ser");
      ObjectOutputStream oout = new ObjectOutputStream(fout);
      oout.writeObject(p);
    } oout.close();
  }
  catch (Exception e) {System.err.println(e);} 
 }
}

Compliant Solutions

catch (Throwable t) { 
      // Forward to handler 
    } finally {
      if (fout != null) {
        try {
          fout.close();
        } catch (IOException x) {
          // Handle error
        }
      }
    }
  }
}

In the absence of sensitive data, a class classes can be serialized by simply implementing the java.io.Serializable interface. By doing so, the class indicates that no security issues may result from the object's serialization. Note that any sub classes will derived subclasses also inherit this interface and will as a result be serializable. are consequently serializable. This approach is inappropriate for any class that contains sensitive data.

Compliant Solution

When serializing a class that contains sensitive data, programs must ensure that sensitive data is omitted from the serialized form. This includes suppressing both serialization of data members that contain sensitive data and serialization of references to nonserializable or sensitive objects.

This compliant solution both avoids the possibility of incorrect serialization and protects sensitive data members from accidental serialization by declaring the relevant members as transient so that they are omitted from When serialization is unavoidable, it is still possible to have classes that cannot implement serializable. This condition is common when there are references to non-serializable objects within the contained methods. The following compliant solution avoids this issue and also protects sensitive data members from getting serialized accidentally. The basic idea is to declare the target member as transient so that it is not included in the list of fields to be serialized , whenever by the default serialization is being usedmechanism.

Code Block
bgColor#ccccff


public class Point implements Serializable {

 private transient double x; // Declared transient
 private transient double y; // Declared transient

 public Point(double x, double y) {
  this.x = x;
  this.y = y;
 }

 public Point()
 {
   //no No-argument constructor
 }
 
}

import java.io.Serializable;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

public class Coordinates extends Point implements Serializable {

  public static void main(String[] args) {
 {    FileOutputStream fout = null;
    try {
      Point p = new Point(5,2);
   FileOutputStream   fout = new FileOutputStream("point.ser");
      ObjectOutputStream oout = new ObjectOutputStream(fout);
      oout.writeObject(p);
      oout.close();
    }
  catch (Exception e) {System.err.println(e);} 
) {
      // Forward to handler
    } finally {
      if (fout != null) {
        try {
          fout.close();
        } catch (IOException x) {
          // Handle error
        }
      }
    }
  }
}

Other compliant solutions include

  • Developing custom

...

  • implementations of the writeObject(), writeReplace(), and writeExternal() methods

...

  • that prevent sensitive fields

...

  • from being written to the serialized stream

...

  • .
  • Defining the serialPersistentFields array field and

...

  • ensuring that sensitive fields are

...

  • omitted from the array

...

Noncompliant Code Example

...

Serialization can also be used maliciously , for example, to return multiple instances of a singleton -like class object. In this noncompliant example, a subclass {{SensitiveClass}} inadvertently becomes Serializable since it extends the {{Exception}} class that implements {{Serializable}}. (Based on \[[Bloch 05|AA. Java References#Bloch 05]\])code example (based on [Bloch 2005]), a subclass SensitiveClass inadvertently becomes serializable because it extends the java.lang.Number class, which implements Serializable:

Code Block
bgColor#FFcccc

public class SensitiveClass extends ExceptionNumber {
   public// ... Implement abstract methods, such as Number.doubleValue()…

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

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

  protectedprivate int printBalance() {balance = 1000;
  protected  int balance = 1000;getBalance() {
    return balance;
  }
}

class Malicious {
  public static void main(String[] args) {

    SensitiveClass sc =
       (SensitiveClass) deepCopy(SensitiveClass.INSTANCEgetInstance());
    // Prints false; indicates new instance
    System.out.println(sc == SensitiveClass.INSTANCE);  // prints falsegetInstance()); indicates new instance
    System.out.println("Balance = " + sc.printBalancegetBalance());
  }

  // This method should not be used in production quality code

  static public Object deepCopy(Object obj) {
    try {
          ByteArrayOutputStream bos = new ByteArrayOutputStream();
          new ObjectOutputStream(bos).writeObject(obj);
      ByteArrayInputStream bin =
   ByteArrayInputStream     bin = new ByteArrayInputStream(bos.toByteArray());
          return new ObjectInputStream(bin).readObject();
    } catch (Exception e) { 
      throw new IllegalArgumentException(e);
    }
  }
}

Compliant Solution

See MSC07-J. Prevent multiple instantiations of singleton objects for more information about singleton classes.

Compliant Solution

Extending a class or interface that implements Serializable should be avoided whenever possible. For instance, a nonserializable class could contain an instance of a serializable class and delegate method calls to the serializable class.

When extension of a serializable class by an unserializable class is necessary, inappropriate Undue serialization of the subclass can be prohibited by throwing a NotSerializableException from a custom writeObject() method or the readResolve, readObject(), and readObjectNoData() method methods, defined in the subclass SensitiveClass. Ideally, one should avoid extending a class or interface that implements Serializablenonserializable subclass. These custom methods must be declared private (see SER01-J. Do not deviate from the proper signatures of serialization methods for more information).

Code Block
bgColor#ccccff
class SensitiveClass extends Number {
  // ...

  private final Object writeObject(java.io.ObjectOutputStream out) throws NotSerializableException {
    throw new NotSerializableException();
  }
  private Object readResolve() final Object readObject(java.io.ObjectInputStream in) throws NotSerializableException {
    throw new NotSerializableException();
  }
  private final Object readObjectNoData(java.io.ObjectInputStream in) throws NotSerializableException {
    throw new NotSerializableException();
  }
}

It is still possible for an attacker to obtain uninitialized instances of SensitiveClass by catching NotSerializableException or by using a finalizer attack (see OBJ11-J. Be wary of letting constructors throw exceptions for more information). Consequently, an unserializable class that extends a serializable class must always validate its invariants before executing any methods. That is, any object of such a class must inspect its fields, its actual type (to prevent it being a malicious subclass), and any invariants it possesses (such as being a malicious second object of a singleton class).

Exceptions

SER03-J-EX0: Sensitive data that has been properly encrypted may be serialized.

Risk Assessment

If sensitive data can be serialized then , it may be transmitted over an insecure linkconnection, or stored in an insecure medium, and thereby released location, or disclosed inappropriately.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

FIO32

SER03-J

medium

Medium

likely

Likely

high

High

P6

L2

Automated Detection

...

TODO

Related Vulnerabilities

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

References

Wiki Markup
\[[JLS 05|AA. Java References#JLS 05]\] [Transient modifier|http://java.sun.com/docs/books/jls/third_edition/html/classes.html#37020]
\[[SCG 07|AA. Java References#SCG 07]\] Guideline 5-1 Guard sensitive data during serialization
\[[Harold 99|AA. Java References#Harold 99]\]
\[[Long 05|AA. Java References#Long 05]\] Section 2.4, Serialization
\[[Greanier 00|AA. Java References#Greanier 00]\] [Discover the secrets of the Java Serialization API|http://java.sun.com/developer/technicalArticles/Programming/serialization/]
\[[Bloch 05|AA. Java References#Bloch 05]\] Puzzle 83: Dyslexic Monotheism
\[[Bloch 01|AA. Java References#Bloch 01]\] Item 1: Enforce the singleton property with a private constructor
\[[MITRE 09|AA. Java References#MITRE 09]\] [CWE ID 502|http://cwe.mitre.org/data/definitions/502.html] "Deserialization of Untrusted Data", [CWE ID 499|http://cwe.mitre.org/data/definitions/499.html] "Serializable Class Containing Sensitive Data"

Tool
Version
Checker
Description
CodeSonar
Include Page
CodeSonar_V
CodeSonar_V

JAVA.CLASS.SER.ND

Serialization Not Disabled (Java)

Coverity7.5UNSAFE_DESERIALIZATIONImplemented
Parasoft Jtest
Include Page
Parasoft_V
Parasoft_V
CERT.SER03.SIFInspect instance fields of serializable objects to make sure they will not expose sensitive information

Related Guidelines

MITRE CWE

CWE-499, Serializable Class Containing Sensitive Data
CWE-502, Deserialization of Untrusted Data

Secure Coding Guidelines for Java SE, Version 5.0

Guideline 8-2 / SERIAL-2: Guard sensitive data during serialization

Bibliography

[Bloch 2005]

Puzzle 83, "Dyslexic monotheism"

[Bloch 2001]

Item 1, "Enforce the Singleton Property with a Private Constructor"

[Greanier 2000]

Discover the Secrets of the Java Serialization API

[Harold 1999]


[Long 2005]

Section 2.4, "Serialization"

[Sun 2006]

Serialization Specification, A.4, Preventing Serialization of Sensitive Data


...

Image Added Image Added Image AddedFIO31-J. Create a copy of mutable inputs      07. Input Output (FIO)      SER32-J. Do not allow serialization and deserialization to bypass the Security Manager