You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 62 Next »

An attacker can maliciously obtain the instance of an object when a constructor for a non-final class throws an exception before it completes the initialization of the new object. For example, an attack that uses the finalizer construct allows an attacker to invoke arbitrary methods within the class despite authorization measures.

Noncompliant Code Example

This noncompliant code example, based on an example by Kabutz [[Kabutz 2001]], defines the constructor of 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.

The constructor throws a SecurityException when SSN verification fails. The UserApp class appropriately catches this exception and displays an access denied message. However, this fails to prevent a malicious program from invoking methods of the partially initialized class BankOperations, as illustrated in the additional code below.

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

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;
    }
  }
}

Even when a malicious subclass catches the SecurityException thrown by the BankOperations constructor, it remains unable to cause further harm by obtaining the new object instance. Rather, an attacker can exploit this code by extending the BankOperations class and overriding the finalize() method. The essence of the attack is the capture of a reference to a partially initialized object of the base class.

When the constructor throws an exception, the garbage collector waits to grab the object reference. However, the object cannot become garbage until after the finalizer completes its execution. The attacker's overridden 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 security manager check.

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
  }
}

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

Compliant Solution

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

public final class BankOperations {
  // ...
}
Unknown macro: {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

Unknown macro: { System.out.println("invoked"); in.registerValidation(this, 5); in.defaultReadObject(); }

public void doSomething1(ObjectInputStream ois) throws IOException, ClassNotFoundException

Unknown macro: { ois.readObject(); }

public void doSomething2()

Unknown macro: { System.out.println("bypassed"); }

public void validateObject() throws InvalidObjectException

Unknown macro: { throw new InvalidObjectException("Something is wrong"); }

}

class B implements Serializable

Unknown macro: { C c; }

class C implements Serializable

Unknown macro: { A a; }

class Test {
public static void main( String [] args ) throws IOException, ClassNotFoundException

Unknown macro: { A a = new A(); a.b = new B(); a.b.c = new C(); a.b.c.a = a; FileOutputStream fos = new FileOutputStream("c}


}

class Interceptor extends A {
private static Interceptor stealInstance = null;
public static Interceptor get() {
try

Unknown macro: { FileInputStream fis = new FileInputStream("c}

catch(Exception ex) { } // Ignore the exception
try {
synchronized(Interceptor.class) {
while (stealInstance == null)

Unknown macro: { System.gc(); Interceptor.class.wait(10); }

}
} catch(InterruptedException ex)

Unknown macro: { return null; }

return stealInstance;
}

public void finalize() {
synchronized(Interceptor.class)

Unknown macro: { stealInstance = this; Interceptor.class.notify(); }

System.out.println("Stolen the instance in finalize of " + this);
}
}

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.

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.");
  }
}

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 2009]].

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. When such a call is not provided, the default constructor of the superclass executes. This is not desirable because should the superclass constructor exit before the security check, the class would be exposed to the perils of a finalizer being added and executed.

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.

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!");
    }
  }
}

"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 2008]].

Exceptions

OBJ04-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.

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; consequently, the attacker can bypass any security checks.

Guideline

Severity

Likelihood

Remediation Cost

Priority

Level

OBJ04-J

high

probable

medium

P12

L1

Automated Detection

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

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 guideline [SER09-J. Do not deserialize from a privileged context].

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

Bibliography

[[API 2006]] finalize()
[[Darwin 2004]] Section 9.5, The Finalize Method
[[Flanagan 2005]] Section 3.3, Destroying and Finalizing Objects
[[JLS 2005]] Section 12.6, Finalization of Class Instances
[[Kabutz 2001]] Issue 032 - Exceptional Constructors - Resurrecting the dead
[[Lai 2008]]
[[SCG 2007]] Guideline 4-2 Defend against partially initialized instances of non-final classes
[[SCG 2009]] Guideline 1-2 Limit the extensibility of classes and methods


[!The CERT Oracle Secure Coding Standard for Java^button_arrow_left.png!]      [!The CERT Oracle Secure Coding Standard for Java^button_arrow_up.png!]      [!The CERT Oracle Secure Coding Standard for Java^button_arrow_right.png!]

  • No labels