Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: BankOperation fixed as BankOperations
Wiki Markup
            An object is partially initialized if a constructor has begun building the object but has not finished. If the object is not fully initialized, it must be hidden from other classes.

Other classes might access a partially-initialized object from concurrently-running threads.  This  rule is a specific instance of [TSM01-J. Do not let the (this) reference escape during object construction] but focuses only on single-threaded programs. Multithreaded programs must also comply with [TSM03-J. Do not publish partially initialized objects].

One of the ways in which a partially-initialized object can become visible to other classes is if the class's constructor throws an exception before initialization is complete.  An attacker can maliciously obtain the instance of such an object.  For example, an attack that uses the finalizer construct allows an attacker to invoke arbitrary methods within the class, even if the class methods are protected by a security manager.

There are several approaches to ensuring that a class's fields are initialized. Declaring a field to be final ensures that the compiler will produce a warning when there is a possibility that the field could remain uninitialized. This also guarantees initialization safety in multi-threaded code. According to [§17.5, "Final Field Semantics"|http://java.sun.com/docs/books/jls/third_edition/html/memory.html#17.5] of the _Java Language Specification_ \[[JLS 2005|AA. Bibliography#JLS 05]\]

{quote}
An object is considered to be _completely initialized_ when its constructor finishes. A thread that can only see a reference to an object after that object has been completely initialized is guaranteed to see the correctly initialized values for that object's final fields.
{quote}

In other words, when a constructor executing in one thread initializes a final field to a known safe value, other threads are unable to see the pre-initialization value of the object.

Finally, a third approach to dealing with uninitialized objects is to allow the object to exist in a known failed state; such objects are commonly known as "zombie objects." This solution is error-prone because any access to such a class must first check whether or not the object has been correctly initialized.

| _Solution_ | Prevents uninitialized values | Prevents partially-initialized objects |
| exception in constructor | yes | no |
| final field | yes | yes |
| initialized flag | no | no |

Some uses of variables require failure atomicity; that is, a variable must not be initialized to null as a result of an object construction failure. This requirement typically arises when a variable constitutes an aggregation of different objects, for example, a composition-and forwarding-based approach, as described in rule [OBJ02-J. Preserve dependencies in subclasses when changing superclasses]. In the absence of failure atomicity, the variable can be left in an inconsistent state as a result of missing or incorrect initialization.  


h2. Noncompliant Code Example (finalizer attack)

This noncompliant code example, based on an example by Kabutz \[[Kabutz 2001|AA. Bibliography#Kabutz 01]\], defines the constructor of the {{BankOperations}} class so that it performs SSN verification using the method {{performSSNVerification()}}. Because we assume that an attacker does not know the correct SSN, the example implementation of the {{performSSNVerification()}} method trivially returns {{false}}.

{code:bgColor=#FFcccc}
public class BankOperations {
  public BankOperations() {
    if (!performSSNVerification()) {
      throw new SecurityException("Invalid SSN!");
    }
  }

  private boolean performSSNVerification() {
    return false; // Returns true if data entered is valid, else false. Assume that the attacker always enters an invalid SSN.
  }

  public void greet() {
    System.out.println("Welcome user! You may now use all the features.");
  }
}

public class UserApp {
  public static void main(String[] args) {
    BankOperations bo;
    try {
      bo = new BankOperations();
    } catch(SecurityException ex) { bo = null; }

    Storage.store(bo);
    System.out.println("Proceed with normal logic");
  }
}
{code}

The constructor throws a {{SecurityException}} when SSN verification fails. The {{UserApp}} class appropriately catches this exception and displays an access denied message. However, these precautions fail to prevent a malicious program from invoking methods of the partially-initialized class {{BankOperations}}, as shown by the following exploit code.

{code}
public class Storage {
  private static BankOperations bop;

  public static void store(BankOperations bo) {
  // Only store if it is initialized
    if (bop == null) {
      if (bo == null) {
        System.out.println("Invalid object!");
        System.exit(1);
      }
      bop = bo;
    }
  }
}
{code}

The goal of the attack is to capture a reference to the partially initialized object of the {{BankOperationBankOperations}} class. If a malicious subclass catches the {{SecurityException}} thrown by the {{BankOperations}} constructor, it is unable to further exploit the vulnerable code because the new object instance has gone out of scope. Instead, an attacker can exploit this code by extending the {{BankOperations}} class and overriding the {{finalize()}} method.

When the constructor throws an exception, the garbage collector waits to grab the object reference. However, the object cannot be garbage-collected until _after_ the finalizer completes its execution. The attacker's finalizer obtains and stores a reference by using the {{this}} keyword. Consequently, the attacker can maliciously invoke any instance method on the base class by using the stolen instance reference. This attack can even bypass a check by a security manager.

{code:bgColor=#FFcccc}
public class Interceptor extends BankOperations {
  private static Interceptor stealInstance = null;

  public static Interceptor get() {
    try {
      new Interceptor();
    } catch (Exception ex) {/* ignore exception */}
    try {
      synchronized(Interceptor.class) {
        while (stealInstance == null) {
          System.gc();
          Interceptor.class.wait(10);
        }
      }
    } catch(InterruptedException ex) { return null; }
    return stealInstance;
  }

  public void finalize() {
    synchronized(Interceptor.class) {
      stealInstance = this;
      Interceptor.class.notify();
    }
    System.out.println("Stole the instance in finalize of " + this);
  }
}
{code}

The attacker's code intentionally violates rule [MET12-J. Do not use finalizers] to exploit the vulnerable code.

{code}
public class AttackerApp { // Invoke class and gain access to the restrictive features
  public static void main(String[] args) {
    Interceptor i = Interceptor.get(); // stolen instance

    // Can store the stolen object though this should have printed "Invalid Object!"
    Storage.store(i);

    // Now invoke any instance method of BankOperations class
    i.greet();

    UserApp.main(args); // Invoke the original UserApp
  }
}
{code}

Compliance with the rules [ERR00-J. Do not suppress or ignore checked exceptions] and [ERR03-J. Restore prior object state on method failure] can help to ensure that fields are appropriately initialized in catch blocks. A developer who explicitly initializes the variable to null is more likely to document this behavior so that other programmers or clients include the appropriate null checks where required. Moreover, this guarantees initialization safety in a multi-threaded scenario.

h2. Compliant Solution ({{final}})

This compliant solution declares the partially initialized class {{final}} so that it cannot be extended.

{code:bgColor=#ccccff}
public final class BankOperations {
  // ...
}
{code}


h2. Compliant Solution ({{final finalize()}})

If the class itself can not be declared final, it can still thwart the finalizer attack by declaring its own finalize() method, and making it final.

{code:bgColor=#ccccff}
public final class BankOperations {
  public final void finalize() {
    // do nothing
  }
}
{code}

This falls under *EX1* of [MET12-J. Do not use finalizers].

{mc}
/**
This is an example of a finalizer attack in serialization. (Deserialization of cyclic references)
*/

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.ObjectInputValidation;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class A implements Serializable, ObjectInputValidation {
  B b;
  private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    System.out.println("invoked");
    in.registerValidation(this, 5);
    in.defaultReadObject();
  }

  public void doSomething1(ObjectInputStream ois) throws IOException, ClassNotFoundException {
    ois.readObject();
  }

  public void doSomething2() {
    System.out.println("bypassed");
  }

  public void validateObject() throws InvalidObjectException {
    throw new InvalidObjectException("Something is wrong");
  }
}

class B implements Serializable { C c; }
class C implements Serializable { A a; }
class Test {
  public static void main( String [] args ) throws IOException, ClassNotFoundException {
    A a = new A();
    a.b = new B();
    a.b.c = new C();
    a.b.c.a = a;

    FileOutputStream fos = new FileOutputStream("c:\\cmu\\cyclic.txt");
    ObjectOutputStream  oos = new ObjectOutputStream(fos);
    oos.writeObject(a);

    Interceptor i = Interceptor.get();
    i.doSomething2();
  }
}

class Interceptor extends A {
  private static Interceptor stealInstance = null;
  public static Interceptor get() {
    try {
      FileInputStream fis = new FileInputStream("c:\\cyclic.txt");
      ObjectInputStream  ois = new ObjectInputStream(fis);
      new Interceptor().doSomething1(ois);

    } catch(Exception ex) { } // Ignore the exception
      try {
        synchronized(Interceptor.class) {
          while (stealInstance == null) {
            System.gc();
            Interceptor.class.wait(10);
          }
      }
    } catch(InterruptedException ex) { return null; }
      return stealInstance;
  }

  public void finalize() {
    synchronized(Interceptor.class) {
      stealInstance = this;
      Interceptor.class.notify();
    }
    System.out.println("Stolen the instance in finalize of " + this);
  }
}
{mc}

h2. Compliant Solution (Java SE 6, {{public}} and {{private}} constructors)

This compliant solution applies to Java SE 6 and later versions, where a finalizer is prevented from being executed when an exception is thrown before the {{java.lang.Object}} constructor exits \[[SCG 2009|AA. Bibliography#SCG 09]\].

In the public constructor, the method call {{performSSNVerification()}} is passed as an argument to a {{private}} constructor. Also, the {{performSSNVerification()}} method actually throws an exception rather than returning {{false}} if the security check fails.

{code:bgColor=#ccccff}
public class BankOperations {
  public BankOperations() {
    this( performSSNVerification());
  }

  private BankOperations(boolean secure) {
    // secure is always true
    // constructor without any security checks
  }

  private static boolean performSSNVerification() {
    // Returns true if data entered is valid, else throws a SecurityException
    // Assume that the attacker just enters invalid SSN; so this method always throws the exception
    throw new SecurityException("Invalid SSN!");
  }

  // ...remainder of BankOperations class definition
}
{code}

The first statement in any constructor must be a call to either a super constructor or to another constructor in the same class. If a constructor call was not provided in the public constructor, the default constructor of the superclass executes. Unfortunately, this could allow a finalizer to be added and executed if the superclass constructor exited before the security check.


h2. Compliant Solution (initialized flag)

Rather than throwing an exception, this compliant solution uses an _initialized flag_ to indicate if an object was successfully constructed. The flag is initialized to {{false}} and set to {{true}} when the constructor completes successfully.

{code:bgColor=#ccccff}
class BankOperations {
  private volatile boolean initialized = false;

  public BankOperations() {
    if (!performSSNVerification()) {
      throw new SecurityException("Invalid SSN!");
    }

    this.initialized = true; // object construction successful
  }

  private boolean performSSNVerification() {
    return false;
  }

  public void greet() {
    if (!this.initialized) {
      throw new SecurityException("Invalid SSN!");
    }

    System.out.println("Welcome user! You may now use all the features.");
  }
}
{code}

The {{initialized}} flag prevents any attempt to access the object's methods if the object is not fully constructed.  Because each method must check the initialized flag to detect a partially constructed object, this solution imposes a speed penalty on the program. It is also harder to maintain because it is easy for a maintainer to add a method that fails to check the initialized flag.

According to Charlie Lai \[[Lai 2008|AA. Bibliography#Lai 08]\]:

"If an object is only partially initialized, its internal fields likely contain safe default values such as {{null}}. Even in an untrusted environment, such an object is unlikely to be useful to an attacker. If the developer deems the partially initialized object state secure, then the developer doesn't have to pollute the class with the flag. The flag is necessary only when such a state isn't secure or when accessible methods in the class perform sensitive operations without referencing any internal field."


h2. Noncompliant Code Example (Class Variable)

This noncompliant code example uses a non-final class variable. The _Java Language Specification_ does not mandate complete initialization and safe publication even though a static initializer has been used. Note that, in the event of an exception during initialization, the variable can be incorrectly initialized. 

{code:bgColor=#FFcccc}
class Trade {
  private static Stock s;
  static {
    try {
      s = new Stock();
    } catch (IOException e) {
      /* does not initialize s to a safe state */
    }
  }
  // ...
}
{code}

h2. Compliant Solution (Final Class Variable)

This compliant solution guarantees safe publication by declaring the {{Stock}} field to be final. 

{code:bgColor=#ccccff}
private static final Stock s;  // final
{code}

Unlike the previous compliant solution, however, this approach permits a possibly-null value but guarantees that a non-null value refers to a completely initialized object.


h2. Risk Assessment

Allowing access to a partially initialized object can provide an attacker with an opportunity to resurrect the object before or during its finalization; as a result, the attacker can bypass any security checks.

|| Rule || Severity || Likelihood || Remediation Cost || Priority || Level ||
| OBJ11-J | high | probable | medium | {color:red}{*}P12{*}{color} | {color:red}{*}L1{*}{color} |


h3. Automated Detection

Automated detection for this rule appears infeasible in the general case. Some instances of non-final classes whose constructors can throw exceptions could be straightforward to diagnose.


h3. Related Vulnerabilities

Vulnerability CVE-2008-5339 concerns a series of vulnerabilities in Java. In one of the vulnerabilities, an applet causes an object to be deserialized using {{ObjectInputStream.readObject()}}, but the input is controlled by an attacker. The object actually read is a serializable subclass of {{ClassLoader}}, and it has a {{readObject()}} method that stashes the object instance into a static variable; consequently, the object survives the serialization. As a result, the applet manages to construct a {{ClassLoader}} object by passing the restrictions against this in an applet, and the {{ClassLoader}} allows it to construct classes that are not subject to the security restrictions of an applet. This vulnerability is described in depth in rule "[SER08-J. Minimize privileges before deserializing from a privileged context]."

h2. Related Guidelines

| [Secure Coding Guidelines for the Java Programming Language, Version 3.0|http://www.oracle.com/technetwork/java/seccodeguide-139067.html] | Guideline 1-2 Limit the extensibility of classes and methods |
| | Guideline 4-3 Defend against partially initialized instances of non-final classes |

h2. Bibliography

| \[[API 2006|AA. Bibliography#API 06]\] | [finalize()|http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html#finalize()] |
| \[[Darwin 2004|AA. Bibliography#Darwin 04]\] | §9.5, The Finalize Method |
| \[[Flanagan 2005|AA. Bibliography#Flanagan 05]\] | §3.3, Destroying and Finalizing Objects |
| \[[JLS 2005|AA. Bibliography#JLS 05]\] | [§12.6|http://java.sun.com/docs/books/jls/third_edition /html/execution.html#12.6], Finalization of Class Instances | 
| |[§8.3.1, "Field Modifiers"|http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.3.1] | 
| |[§17.5, "Final Field Semantics"|http://java.sun.com/docs/books/jls/third_edition/html/memory.html#17.5] |
| \[[Kabutz 2001|AA. Bibliography#Kabutz 01]\] | Issue 032: Exceptional Constructors - Resurrecting the dead |
| \[[Lai 2008|AA. Bibliography#Lai 08]\] | Java Insecurity: Accounting for Subtleties That Can Compromise Code |

----
[!The CERT Oracle Secure Coding Standard for Java^button_arrow_left.png!|OBJ10-J. Do not use public static non-final variables]      [!The CERT Oracle Secure Coding Standard for Java^button_arrow_up.png!|04. Object Orientation (OBJ)]      [!The CERT Oracle Secure Coding Standard for Java^button_arrow_right.png!|05. Methods (MET)]