Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Wiki Markup
For a non-final class, if a constructor throws an exception before fully initializing the object, it becomes possible to maliciously obtain its instance. For example, an attack that uses the finalizer construct allows an attacker to invoke arbitrary methods within the class despite authorization measures.

h2. Noncompliant Code Example

This noncompliant code example, based on an example by Kabutz \[[Kabutz 01|AA. Java References#Kabutz 01]\], defines the constructor of {{BankOperations}} class so that it performs SSN verification using the method {{performSSNVerification()}}. Assume that an attacker does not know the correct SSN. As a result, this method trivially returns {{false}} in this example. 

When the SSN verification fails, a {{SecurityException}} is thrown. The {{UserApp}} class appropriately catches this exception and an access denied message is displayed. However, this does not prevent a malicious program from invoking methods of the partially initialized class {{BankOperations}}. This is illustrated in the code that follows this noncompliant code example example.   

{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 just enters 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");
  }
}

public class Storage {
  private static BankOperations bop;

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

{code}

Note that even if a malicious subclass catches the {{SecurityException}} that the {{BankOperations}} constructor throws, it cannot obtain its instance to cause further harm. To exploit this code, an attacker extends the {{BankOperations}} class and overrides the {{finalize()}} method. The gist of the attack is the capture of a handle of the partially initialized base class. 

When the constructor throws an exception, the garbage collector waits to grab the object reference. However, by overriding the finalizer, a reference is obtained using the {{this}} keyword. Consequently, any instance method on the base class can be invoked maliciously by using the stolen {{this}} instance. Even a security manager check can be bypassed this way.

{code}
public class Interceptor extends BankOperations {
  private static Interceptor stealInstance = null;
  public static Interceptor get() {
    try {
      new Interceptor();
    } 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);
  }
}

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}

The attacker's code violates the guideline [OBJ08-J. Avoid using finalizers].

h2. Compliant Solution

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

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


{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

This compliant solution prevents a hostile caller from using a partially initialized instance of the class. In the case of the noncompliant code example, the {{BankOperations}} class's superclass's constructor is called implicitly from the {{BankOperations}} constructor, just before the check. This exposes the partially initialized object to the finalizer attack.

In this compliant solution, the check is carried out before the superclass's constructor executes. This forbids hostile code from obtaining a partially initialized instance.

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

  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!"); 
  }
  
  public void greet() {
    System.out.println("Welcome user! You may now use all the features.");
  }
}
{code}

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

The method call {{performSSNVerification()}} is passed as an argument to a {{private}} constructor because the first statement in a constructor must be a call to either a super constructor, or to another constructor in the same subclass. If such a call is not provided, the default constructor of the superclass executes. This is not desirable because if the superclass constructor exits before the security check, the class would be exposed to the perils of a finalizer being added and executed.

h2. Compliant Solution

When the API can be extended (consider a non-final class, for example), it is permissible to use a flag to signal the successful completion of object construction. This is shown below. 

{code:bgColor=#ccccff}
class BankOperations {
  public volatile boolean initialized = false; // volatile flag

  public BankOperations() {
    if (!performSSNVerification()) {
      throw new SecurityException("Invalid SSN!"); 
    }  
    else {
      initialized = true; // object construction succeeded	  
    }
  }
  
  private boolean performSSNVerification() {
    return false;
  }
  
  public void greet() {
    if(initialized == true) {
      System.out.println("Welcome user! You may now use all the features.");
      // ...
    }
    else {
      System.out.println("You are not permitted!");
    }
  }
}
{code}

"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." \[[Lai 08|AA. Java References#Lai 08]\].

h2. Noncompliant Code Example

The Javabeans pattern uses a no-argument constructor along with a series of parallel setter methods to build an object. This pattern is not thread-safe and can  lead to inconsistent object state. Moreover, it permits another thread to access the object even though it may only be partially initialized (not all required fields are initialized).

{code:bgColor=#FFcccc}
class UnsafeCurrency {
  // total amount requested (required)
  private int dollars = -1; // initialize to default value
  private int cents = -1; // initialize to default value
  // change requested, denomination (optional)
  private int quarters = 0;
  private int dimes = 0;
  private int nickels = 0;
  private int pennies = 0;
  public UnsafeCurrency() {} // no argument constructor

  // setter methods 
  public void setDollar(int amount) { dollars = amount; }
  public void setCents(int amount) { cents = amount; }
  public void setQuarters(int quantity) { quarters = quantity; } 
  public void setDimes(int quantity) { dimes = quantity; }
  public void setNickels(int quantity) { nickels = quantity; }
  public void setPennies(int quantity) { pennies = quantity; }
}
{code}

h2. Compliant Solution

Use the Builder pattern's \[[Gamma 95|AA. Java References#Gamma 95]\] variant suggested by Bloch \[[Bloch 08|AA. Java References#Bloch 08]\] to ensure thread safety and atomicity of object creation. The idea is to call the constructor with the _required_ parameters and obtain a _builder_ object. Each _optional_ parameter can be set using setters on the builder. The object construction concludes with the invocation of the {{build()}} method. This also has the effect of making the class {{Currency}} immutable. 

{code:bgColor=#ccccff}
class Currency {
  // total amount requested (required)
  private final int dollars;
  private final int cents;
  // change requested, denomination (optional)
  private final int quarters;
  private final int dimes;
  private final int nickels;
  private final int pennies;
  
  // Static class member 
  private Currency(Builder builder) {
    dollars = builder.dollars;
    cents = builder.cents;
   
    quarters = builder.quarters;
    dimes = builder.dimes;
    nickels = builder.nickels;
    pennies = builder.pennies;
  }

  // Static class member 
  public static class Builder {
    private final int dollars;
    private final int cents;
    private int quarters = 0;
    private int dimes = 0;
    private int nickels = 0;
    private int pennies = 0;
	 
    public Builder(int dollars, int cents) {
      this.dollars = dollars;
      this.cents = cents;
    }
    public Builder quarters(int quantity) {
      quarters = quantity;  
      return this; 
    }
    public Builder dimes(int quantity) {
      dimes = quantity; 
      return this;	 
    }
    public Builder nickles(int quantity) {
      nickels = quantity; 
      return this;	 
    }
    public Builder pennies(int quantity) {
      pennies = quantity; 
      return this;	 
    }
    public Currency build() {
      return new Currency(this); 	 
    }
 }
}

Client code:
Currency USD = new Currency.Builder(100,56).quarters(2).nickles(1).pennies(1).build();
{code}

If input has to be validated, make sure that the values are copied from the builder class to the containing class's fields prior to checking. The builder class does not violate [SCP03-J. Do not expose sensitive private members of the outer class from within a nested class] because it maintains a copy of the variables defined in the scope of the containing class. These take precedence and as a result do not break encapsulation.

h2. Exceptions

*EX1:* It is permissible to use the telescoping pattern when the overhead of the builder pattern is significant as compared to the number of parameters required to be initialized. This pattern prescribes a constructor to initialize the required parameters and individual constructors for each optional parameter that is added.

h2. Risk Assessment

Allowing a partially initialized object to be accessed can provide an attacker with an opportunity to resurrect the object before its finalization and bypass any security checks.

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



h3. Automated Detection

TODO



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 has managed to construct a {{ClassLoader}} object, by-passing the restrictions against doing so in an applet, and that {{ClassLoader}} allows it to construct classes that are not subject to the security restrictions of an applet. The vulnerability is described in depth in [SER09-J. Do not deserialize from a privileged context].

Search for vulnerabilities resulting from the violation of this rule on the [CERT website|https://www.kb.cert.org/vulnotes/bymetric?searchview&query=FIELD+KEYWORDS+contains+OBJ32-J].

h2. References

\[[JLS 05|AA. Java References#JLS 05]\] Section 12.6, Finalization of Class Instances
\[[API 06|AA. Java References#API 06]\] [finalize()|http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html#finalize()]
\[[SCG 07|AA. Java References#SCG 07]\] Guideline 4-2 Defend against partially initialized instances of non-final classes
\[[SCG 09|AA. Java References#SCG 09]\] Guideline 1-2 Limit the extensibility of classes and methods
\[[Kabutz 01|AA. Java References#Kabutz 01]\] Issue 032 - Exceptional Constructors - Resurrecting the dead
\[[Bloch 08|AA. Java References#Bloch 08]\] Item 7, Avoid finalizers
\[[Darwin 04|AA. Java References#Darwin 04]\] Section 9.5, The Finalize Method
\[[Flanagan 05|AA. Java References#Flanagan 05]\] Section 3.3, Destroying and Finalizing Objects
\[[Lai 08|AA. Java References#Lai 08]\]

----
[!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_left.png!|OBJ03-J. Do not use public static non-final variables]      [!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_up.png!|08. Object Orientation (OBJ)]      [!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_right.png!|OBJ05-J. Limit the extensibility of non-final classes and methods to only trusted subclasses]