Versions Compared

Key

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

...

However, certain methods use a reduced security check, that only checks that the calling method has access, rather then checking every method in the call stack. Code that invokes these methods must guarentee that they are not being invoked on behalf of untrusted code. These methods are:

APIs that mirror language checksMethods that check calling method only

java.lang.Class.newInstance

java.lang.reflect.Constructor.newInstance

java.lang.reflect.Field.get*

java.lang.reflect.Field.set*

java.lang.reflect.Method.invoke

java.util.concurrent.atomic.AtomicIntegerFieldUpdater.newUpdater

java.util.concurrent.atomic.AtomicLongFieldUpdater.newUpdater

java.util.concurrent.atomic.AtomicReferenceFieldUpdater.newUpdater

Because the java.lang.reflect.Field.setAccessible/getAccessible methods are used to instruct the JVM to override the language access checks, they perform standard (and more restrictive) security manager checks and consequently lack the vulnerability discussed in this guideline. Nevertheless, these methods should be used only with extreme caution. The remaining set* and get* field reflection methods perform only the language access checks and consequently are vulnerable.

 

Class loaders allow a Java application to be dynamically extended at runtime by loading classes.  For each class that is loaded, the JVM tracks the class loader that was used to load the class. When a loaded class first refers to another class, the virtual machine requests that the referenced class be loaded by the same class loader used to load the referencing class. Java's class loader architecture controls interaction between code loaded from different sources by allowing the use of different class loaders. This separation of class loaders is fundamental to the separation of Class loaders allow a Java application to be dynamically extended at runtime by loading classes.  For each class that is loaded, the JVM tracks the class loader that was used to load the class. When a loaded class first refers to another class, the virtual machine requests that the referenced class be loaded by the same class loader used to load the referencing class. Java's class loader architecture controls interaction between code loaded from different sources by allowing the use of different class loaders. This separation of class loaders is fundamental to the separation of code; it prevents malicious code from gaining access to and subverting trusted code.

Several methods, that are charged with loading classes, delegate their work to the class loader of the class of the method that called them. The security checks associated with loading classes is often performed by class loaders. Consequently, any method that invokes one of these class-loading methods must guarentee that these methods are not acting on behalf of untrusted code. These methods are:

Methods that use calling method's class loader

java.lang.Class.forName

java.lang.Package.getPackage

java.lang.Package.getPackages

java.lang.Runtime.load

java.lang.Runtime.loadLibrary

java.lang.System.load

java.lang.System.loadLibrary

java.sql.DriverManager.getConnection

java.sql.DriverManager.getDriver

java.sql.DriverManager.getDrivers

java.sql.DriverManager.deregisterDriver

java.util.ResourceBundle.getBundle

The reflection APIs permit an object to access fields and methods of another object by name rather than by reference. The Java Virtual Machine (JVM) enforces policy compliance during such accesses by performing language access checks. For instance, although an object is not normally allowed to access private members or invoke methods of another class, the APIs belonging to the java.lang.reflectpackage allow an object to do so contingent upon performing the language-defined access checks. It is important to note, however, that these access checks consider only the language-level visibility of the immediate caller. Consequently, unwary programmers can afford an opportunity for a privilege escalation attack by untrusted callers.

Because the java.lang.reflect.Field.setAccessible/getAccessible methods are used to instruct the JVM to override the language access checks, they perform standard (and more restrictive) security manager checks and consequently lack the vulnerability discussed in this guideline. Nevertheless, these methods should be used only with extreme caution. The remaining set* and get* field reflection methods perform only the language access checks and consequently are vulnerable.

Use of reflection complicates security analysis and can introduce substantial security vulnerabilities. Consequently, programmers should avoid the use of the reflection APIs when it is feasible to do so. When use of reflection is necessary, exercise extreme caution.

In practice, the trusted code's class loader frequently allows these methods to be invoked whereas untrusted code's class loader may lack these privileges. However, when the untrusted code's class loader delegates to the trusted code's class loader, the untrusted code gains visibility to the trusted code. In the absence of such a delegation relationship, the class loaders would ensure namespace separation; consequently, the untrusted code would be unable to observe members or to invoke methods belonging to the trusted code.

A problem arises because the class loader delegation model is fundamental to many Java implementations and frameworks. So the best advice is to avoid exposing the methods listed above to untrusted code.

Consider, for example, an attack scenario where untrusted code is attempting to load a privileged class. If its class loader is permitted to delegate the class loading to a trusted class's class loader, privilege escalation can occur, because the untrusted code's class loader may lack permission to load the requested privileged class on its own. Furthermore, if the trusted code accepts tainted inputs, the trusted code's class loader could load additional privileged — or even malicious — classes on behalf of the untrusted code.

Classes that have the same defining class loader will exist in the same namespace but can have different privileges, depending on the security policy. Security vulnerabilities can arise when trusted code coexists with untrusted code (or less-privileged code) that was loaded by the same class loader. In this case, the untrusted (or less-privileged) code can freely access members of the trusted code according to their declared accessibility. When the trusted code uses any of the tabulated APIs, it bypasses security manager checks (with the exception of loadLibrary() and load()).

A security-sensitive class loader typically employs the security manager to enforce a security policy before loading new classes. For example, the applet class loader ensures that an applet cannot directly invoke methods of classes present in the com.sun.* package. A security manager check ensures that specific actions are allowed or denied depending on the privileges of all of the caller methods on the call stack (the privileges are associated with the code source that encompasses the class). A security manager complements, rather than superseding, the security offered by the class loader architecture. Consequently, APIs that perform security manager checks may still violate this guideline at the class loader level when exposed to untrusted callers.

With the exception of the loadLibrary() and load() methods, the tabulated methods fail to perform any security manager checks. The loadLibrary() and load() APIs are typically used from within a doPrivileged block; in that case, unprivileged callers can directly invoke them without requiring any special permissions. Consequently, the security manager checks are curtailed at the immediate caller. The security manager fails to examine the entire call stack and so fails to enhance security. Accepting tainted inputs from untrusted code and allowing them to be used by these APIs may expose vulnerabilities.

The following lists the APIs that only check the immediate caller's class for security.

Because the java.lang.reflect.Field.setAccessible/getAccessible methods are used to instruct the JVM to override the language access checks, they perform standard (and more restrictive) security manager checks and consequently lack the vulnerability discussed in this guideline. Nevertheless, these methods should be used only with extreme caution. The remaining set* and get* field reflection methods perform only the language access checks and consequently are vulnerable.

Use of reflection complicates security analysis and can introduce substantial security vulnerabilities. Consequently, programmers should avoid the use of the reflection APIs when it is feasible to do so. When use of reflection is necessary, exercise extreme caution.

This guideline is an instance of SEC03-J. Do not load trusted classes after allowing untrusted code to load arbitrary classes. Many examples also violate SEC00-J. Do not allow privileged blocks to leak sensitive information across a trust boundary.

 

Noncompliant Code Example (CVE-2013-0422)

Java 1.7.0u10 was exploited in January 2013 because of several vulnerabilities. One vulnerability in the MBeanInstantiator class granted unprivileged code the ability to access any class regardless of the current security policy or accessibility rules. The MBeanInstantiator.findClass() method could be invoked with any string and would attempt to return a Class object. This method delegated its work to the loadClass() method, whose source code is shown:

In practice, the trusted code's class loader frequently allows these methods to be invoked whereas untrusted code's class loader may lack these privileges. However, when the untrusted code's class loader delegates to the trusted code's class loader, the untrusted code gains visibility to the trusted code. In the absence of such a delegation relationship, the class loaders would ensure namespace separation; consequently, the untrusted code would be unable to observe members or to invoke methods belonging to the trusted code.

A problem arises because the class loader delegation model is fundamental to many Java implementations and frameworks. So the best advice is to avoid exposing the methods listed above to untrusted code. Consider, for example, an attack scenario where untrusted code is attempting to load a privileged class. If its class loader is permitted to delegate the class loading to a trusted class's class loader, privilege escalation can occur, because the untrusted code's class loader may lack permission to load the requested privileged class on its own. Furthermore, if the trusted code accepts tainted inputs, the trusted code's class loader could load additional privileged — or even malicious — classes on behalf of the untrusted code.

Classes that have the same defining class loader will exist in the same namespace but can have different privileges, depending on the security policy. Security vulnerabilities can arise when trusted code coexists with untrusted code (or less-privileged code) that was loaded by the same class loader. In this case, the untrusted (or less-privileged) code can freely access members of the trusted code according to their declared accessibility. When the trusted code uses any of the tabulated APIs, it bypasses security manager checks (with the exception of loadLibrary() and load()).

With the exception of the loadLibrary() and load() methods, the tabulated methods fail to perform any security manager checks. The loadLibrary() and load() APIs are typically used from within a doPrivileged block; in that case, unprivileged callers can directly invoke them without requiring any special permissions. Consequently, the security manager checks are curtailed at the immediate caller. The security manager fails to examine the entire call stack and so fails to enhance security. Accepting tainted inputs from untrusted code and allowing them to be used by these APIs may expose vulnerabilities.

 

This guideline is an instance of SEC03-J. Do not load trusted classes after allowing untrusted code to load arbitrary classes. Many examples also violate SEC00-J. Do not allow privileged blocks to leak sensitive information across a trust boundary.

Noncompliant Code Example (CVE-2013-0422)

Java 1.7.0u10 was exploited in January 2013 because of several vulnerabilities. One vulnerability in the MBeanInstantiator class granted unprivileged code the ability to access any class regardless of the current security policy or accessibility rules. The MBeanInstantiator.findClass() method could be invoked with any string and would attempt to return a Class object. This method delegated its work to the loadClass() method, whose source code is shown:

Code Block
bgColor#ffcccc
langjava
/**
 * Load a class with the specified loader, or with this object
 * class loader if the specified loader is null.
 **/
static Class<?> loadClass(String className, ClassLoader loader)
    throws ReflectionException {

    Class<?> theClass;
    if (className == null) {
        throw new RuntimeOperationsException(new
            IllegalArgumentException("The class name cannot be null"),
      
Code Block
bgColor#ffcccc
langjava
/**
 * Load a class with the specified loader, or with this object
 * class loader if the specified loader is null.
 **/
static Class<?> loadClass(String className, ClassLoader loader)
    throws ReflectionException {

    Class<?> theClass;
    if (className == null) {
        throw new RuntimeOperationsException(new
            IllegalArgumentException("The class name cannot be null"),
                          "Exception occurred during object instantiation");
    }
    try {
        if (loader == null)
            loader = MBeanInstantiator.class.getClassLoader();
        if (loader != null) {
            theClass = Class.forName(className, false, loader);
        } else {
            theClass = Class.forName(className);
        }
    } catch (ClassNotFoundException e) {
        throw new ReflectionException(e,
        "The MBean class could not be loaded");
    }
    return theClass;
}

...

Code Block
bgColor#ccccff
langjava
// ...
// ...
    if (className == null) {
        throw new RuntimeOperationsException(new
           if (className == null) {IllegalArgumentException("The class name cannot be null"),
                          "Exception occurred during object instantiation");
    }
    ReflectUtil.checkPackageAccess(className);
    throw new RuntimeOperationsException(newtry {
        if (loader ==  IllegalArgumentException("The class name cannot be null"),
                          "Exception occurred during object instantiation");
    }
    ReflectUtil.checkPackageAccess(className);
    try {
        if (loader == null)
// ...

Noncompliant Code Example (CERT Vul# 636312)

null)
// ...

Noncompliant Code Example (CERT Vul# 636312)

CERT Vulnerability 636312 describes a vulnerability in Java that was successfully exploited in August 2012. (The exploit actually used two vulnerabilities; the other one is described in SEC05-J. Do not use reflection to increase accessibility of classes, methods, or fields.

A security-sensitive class loader typically employs the security manager to enforce a security policy before loading new classes. For example, the applet class loader ensures that an applet cannot directly invoke methods of classes present in the com.sun.* package. A security manager check ensures that specific actions are allowed or denied depending on the privileges of all of the caller methods on the call stack (the privileges are associated with the code source that encompasses the class). A security manager complements, rather than superseding, the security offered by the class loader architecture. Consequently, APIs that perform security manager checks may still violate this guideline at the class loader level when exposed to untrusted callersCERT Vulnerability 636312 describes a vulnerability in Java that was successfully exploited in August 2012. (The exploit actually used two vulnerabilities; the other one is described in SEC05-J. Do not use reflection to increase accessibility of classes, methods, or fields.

The goal of the exploit code was to access the private sun.awt.SunToolkit class. However, as the attack code runs in an applet, accessing it directly, using class.forName() would cause a SecurityException to be thrown. Consequently, the exploit code contains the following method to get a class, bypassing its security manager:

...

Code Block
bgColor#ccccff
langjava
private String url = // hardwired value

public Connection getConnection(String username, String password) {
  // ...
  return DriverManager.getConnection(this.url, username, password);
}

Applicability

Allowing untrusted code to invoke methods with reduced security checks can grant excessive abilities to malicious code. Likewise, allowing untrusted code to carry out actions using the immediate caller's class loader may allow the untrusted code to execute with the same privileges as the immediate caller.

It is permissible to use APIs This guideline does not apply to methods that do not use the immediate caller's class loader instance. For example, the three-argument java.lang.Class.forName() method requires an explicit argument that specifies the class loader instance to use. Do not use the immediate caller's class loader as the third argument when instances must be returned to untrusted code.

...

Guillardoy, Esteban (Immunity Products), Java 0-day analysis (CVE-2012-4681), August 28, 2012

[Chan 1999] java.lang.reflect AccessibleObject

...