Most methods lack security manager checks because they do not provide access to sensitive parts of the system, such as the file system. Most methods that do provide security manager checks verify that every class and method in the call stack is authorized before they proceed. This security model allows restricted programs, such as Java applets, to have full access to the core Java library. It also prevents a sensitive method from acting on behalf of a malicious method that hides behind trusted methods in the call stack.

However, certain methods use a reduced-security check that checks only that the calling method is authorized rather than checking every method in the call stack. Any code that invokes these methods must guarantee that they cannot be invoked on behalf of untrusted code. These methods are listed in the following table.

Methods That Check the 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() and getAccessible() methods are used to instruct the Java Virtual Machine (JVM) to override the language access checks, they perform standard (and more restrictive) security manager checks and consequently lack the vulnerability described by this guideline. Nevertheless, these methods should also be used with extreme caution. The remaining set* and get* field reflection methods perform only the language access checks and are consequently vulnerable.

Class Loaders

Class loaders allow a Java application to be dynamically extended at runtime by loading additional 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 that was 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 are performed by class loaders. Consequently, any method that invokes one of these class loading methods must guarantee that these methods cannot act on behalf of untrusted code. These methods are listed in the following table.

Methods That Use the 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

With the exception of the loadLibrary() and load() methods, the tabulated methods do not perform any security manager checks; they delegate security checks to the appropriate class loader. 

In practice, the trusted code's class loader frequently allows these methods to be invoked, whereas the 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.

The class loader delegation model is fundamental to many Java implementations and frameworks. Avoid exposing the methods listed in the preceding tables to untrusted code. Consider, for example, an attack scenario where untrusted code is attempting to load a privileged class. If its class loader lacks permission to load the requested privileged class on its own, but the class loader is permitted to delegate the class loading to a trusted class's class loader, privilege escalation can occur. Furthermore, if the trusted code accepts tainted inputs, the trusted code's class loader could be persuaded to load privileged, malicious classes on behalf of the untrusted code.

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

This guideline is similar to 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

In this noncompliant code example, a call to System.loadLibrary() is embedded in a doPrivileged block.

public void load(String libName) {
  AccessController.doPrivileged(new PrivilegedAction() {
    public Object run() { 
      System.loadLibrary(libName);
      return null; 
    }
  });
}

This code is insecure because it could load a library on behalf of untrusted code. In essence, the untrusted code's class loader may be able to use this code to load a library even though it lacks sufficient permissions to do so directly. After loading the library, the untrusted code can call native methods from the library, if those methods are accessible, because the doPrivileged block stops any security manager checks from being applied to callers further up the execution stack.

Nonnative library code can also be susceptible to related security flaws. Suppose there exists a library that contains a vulnerability that is not directly exposed, perhaps because it lies in an unused method. Loading this library may not directly expose a vulnerability. However, an attacker could then load an additional library that exploits the first library's vulnerability. Moreover, nonnative libraries often use doPrivileged blocks, making them attractive targets.

Compliant Solution

This compliant solution hard codes the name of the library to prevent the possibility of tainted values. It also reduces the accessibility of the load() method from public to private. Consequently, untrusted callers are prohibited from loading the awt library. 

private void load() {
  AccessController.doPrivileged(new PrivilegedAction() {
    public Object run() { 
      System.loadLibrary("awt");
      return null; 
    }
  });
}

Noncompliant Code Example

This noncompliant code example returns an instance of java.sql.Connection from trusted to untrusted code.

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

Untrusted code that lacks the permissions required to create a SQL connection can bypass these restrictions by using the acquired instance directly. The getConnection() method is unsafe because it uses the url argument to indicate a class to be loaded; this class serves as the database driver.

Compliant Solution

This compliant solution prevents malicious users from supplying their own URL to the database connection, thereby limiting their ability to load untrusted drivers.

private String url = // Hardwired value

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

Noncompliant Code Example (CERT Vulnerability 636312)

CERT Vulnerability Note VU#636312 describes a vulnerability in Java 1.7.0 update 6 that was widely 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 exploit runs as a Java applet. The applet class loader ensures that an applet cannot directly invoke methods of classes present in the com.sun.* package. A normal 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).

The first goal of the exploit code was to access the private sun.awt.SunToolkit class. However, invoking class.forName() directly on the name of this class would cause a SecurityException to be thrown. Consequently, the exploit code used the following method to access any class, bypassing the security manager:

private Class GetClass(String paramString)
    throws Throwable
{
    Object arrayOfObject[] = new Object[1];
    arrayOfObject[0] = paramString;
    Expression localExpression = new Expression(Class.class, "forName", arrayOfObject);
    localExpression.execute();
    return (Class)localExpression.getValue();
}

The java.beans.Expression.execute() method delegates its work to the following method:

private Object invokeInternal() throws Exception {
  Object target = getTarget();
  String methodName = getMethodName();

  if (target == null || methodName == null) {
    throw new NullPointerException(
      (target == null ? "target" : "methodName") + 
       " should not be null");
  }

  Object[] arguments = getArguments();
  if (arguments == null) {
    arguments = emptyArray;
  }
  // Class.forName() won't load classes outside
  // of core from a class inside core, so it
  // is handled as a special case.
  if (target == Class.class && methodName.equals("forName")) {
    return ClassFinder.resolveClass((String)arguments[0], this.loader);
  }

// ...

The com.sun.beans.finder.ClassFinder.resolveClass() method delegates its work to the findClass() method:

public static Class<?> findClass(String name) 
   throws ClassNotFoundException {
  try {
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    if (loader == null) {
      loader = ClassLoader.getSystemClassLoader();
    }
    if (loader != null) {
      return Class.forName(name, false, loader);
    }
  } catch (ClassNotFoundException exception) {
    // Use current class loader instead
  } catch (SecurityException exception) {
    // Use current class loader instead
  }
  return Class.forName(name);
}

Although this method is called in the context of an applet, it uses Class.forName() to obtain the requested class. Class.forName() delegates the search to the calling method's class loader. In this case, the calling class (com.sun.beans.finder.ClassFinder) is part of core Java, so the trusted class loader is used in place of the more restrictive applet class loader, and the trusted class loader loads the class, unaware that it is acting on behalf of malicious code.

Compliant Solution (CVE-2012-4681)

Oracle mitigated this vulnerability in Java 1.7.0 update 7 by patching the com.sun.beans.finder.ClassFinder.findClass() method. The checkPackageAccess() method checks the entire call stack to ensure that Class.forName(), in this instance only, fetches classes only on behalf of trusted methods.

public static Class<?> findClass(String name) 
   throws ClassNotFoundException {
  checkPackageAccess(name);
  try {
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    if (loader == null) {
      // Can be null in IE (see 6204697)
      loader = ClassLoader.getSystemClassLoader();
    }
    if (loader != null) {
      return Class.forName(name, false, loader);
    }

  } catch (ClassNotFoundException exception) {
    // Use current class loader instead
  } catch (SecurityException exception) {
    // Use current class loader instead
  }
  return Class.forName(name);
}

Noncompliant Code Example (CVE-2013-0422)

Java 1.7.0 update 10 was widely 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 the Class object named after the string. This method delegated its work to the loadClass() method, whose source code is shown here:

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

This method delegates the task of dynamically loading the specified class to the Class.forName() method, which delegates the work to its calling method's class loader. Because the calling method is MBeanInstantiator.loadClass(), the core class loader is used, which provides no security checks.

Compliant Solution (CVE-2013-0422)

Oracle mitigated this vulnerability in Java 1.7.0 update 11 by adding an access check to the MBeanInstantiator.loadClass() method. This access check ensures that the caller is permitted to access the class being sought:

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

Applicability

Allowing untrusted code to invoke methods with reduced-security checks can result in privilege escalation. Likewise, allowing untrusted code to perform actions using the immediate caller's class loader may allow the untrusted code to execute with the same privileges as the immediate caller.

Methods that avoid using the immediate caller's class loader instance fall outside the scope of this guideline. For example, the three-argument java.lang.Class.forName() method requires an explicit argument that specifies the class loader instance to use.

public static Class forName(String name, boolean initialize,
       ClassLoader loader) throws ClassNotFoundException

Do not use the immediate caller's class loader as the third argument when instances must be returned to untrusted code.

Bibliography

 


18 Comments

  1. Appears to be a subset of SEC04 and I'm not certain where this one is going. The SCG 07 document had some details but I didn't follow the distinction too well. The table is important though.

  2. I feel this rule should go. As Dhruv mentions, it is a subset of SEC04-J. And it's much more complex. AFAICT all the NCCEs violate SEC04-J.

    If the table is useful (and I'm not convinced it is), it can go into SEC04-J.

    1. No, I think that this is fundamentally different from SEC04-J, although it is related to SEC04-J and should have a reference to it.

      I think this is about a specific "nasty problem" that I'm not sure I fully understand, but the new SCG (SCG 2010) might be a better source of information than SCG 2007.

      1. Well, the intro is complex and difficult to wade through, and partially redundant with SEC04-J. (although the 'immediate caller's class loader instance' is unique). But, more important, the code examples all:

        • violate SEC04-J
        • are skeletons, and not particularly realistic
        • do not deal with the 'immediate claller's class loader instance'.

        If you want to convince me that this rule is worth saving, I need a NCCE/CS pair that involves an exploit involving the immediate caller's class loader instance. (That is, write vulnerable code, and then code to exploit it, and then how to mitigate the vulnerable code.) If the vulnerable code also complies with SEC04-J, that's even better, but I don't think that's possible.

  3. All these API methods listed in this rule either can load an arbitrary class or shared library.

    • The load() and loadLibrary() methods can load arbitrary shared libraries. This can be malicious as shared libraries may not be subject to a security manager's restrictions.

    BUT

    • The load() and loadLibrary() methods are always checked; the check is never bypassed depending on the calling function. According to the Runtime.loadLibrary() method javadocs:

    First, if there is a security manager, its checkLink method is called with the libname as its argument. This may result in a security exception.

    • Finally, Oracle's Secure Coding Guidelines do explain that these methods (among others) use the calling method's class loader. For the load & loadlibrary methods, this makes no difference. (It's useful for the other methods which employ reflection, to distinguish if a security check is warranted, and to disambiguate classes with the same name, but in different namespaces).

    I would conclude from these points that this rule can be deleted; as it is a mix of issues some of which are covered by other rules, and others which are not security problems at all. I will void this rule next week if someone doesn't try to save it.

    1. After a three-month haitus (and attending JavaOne), I've mellowed out on this rule. It doesn't belong in our official standard, but its OK as a guideline. (If we decide the book is too big, this is one of the first guidelines on the chopping block IMHO.)

      I still agree with Dhruv: this rule is a subset of SEC04-J, but still worthwhile wrt the table and foibles of its functions. Technically load() and loadLibrary() do not belong in the table, for reasons explained in the intro...my arguments in the above comment are still valid. However, the table comes directly from SCG 2010, as do the reasons for including them, so I'll relax on those functions.

      Here's my TODO for this guideline...then it can stay:

      • Should mention that this rule is a subset of SEC04-J. (All the NCCEs violate SEC04-J)
      • Should also reference SEC00-J...many of the NCCEs violate that too.

      The 2nd NCCE/CS pair is a good (though abstract) illustration of what this rule preaches.

      • 3rd CS needs a bit of rewording. There is nothing wrong with loading an arbitrary class, as noted by SEC03-J. The vul is in accessing an already-loaded sensitive class.
      • I think the point of the 4th NCCE is that the url could be tainted. Need to illustrate this.
      • The code sample in Applicability prob belongs in the 2nd CS
      1. I've made the changes listed above, and approved the rule.

        1. Given my re-write of the intro, I am no longer convinced that the guideline is an instance of:

          SEC04-J. Protect sensitive operations with security manager checks.

  4. I have numerous issues with this guideline, the first one being is that it confuses "don't call" with "call with static arguments".

  5. Classes loaded by different class loaders are in different name-spaces and cannot gain access to each other unless the application explicitly allows it. By default, classes can only see other classes that were loaded by the same class loader.

    Wrong. Classes most definitely can see classes loaded by different class loaders. The rules are complex, but it boils down to, if class Foo references a class Bar that hasn't been loaded by Foo's class loader, than the system searches for class Bar on the 'class loader tree'. If there are multiple Bar classes, the one returned is the one 'nearest' Foo, where 'nearest' is defined by certain rules about tree traversal (that I don't remember offhand (smile). The SEC04-J rule shows a vulnerability that resulted from the wrong class being found because of poor understanding of class loading. (EDIT: the rule is actually SEC03-J. Do not load trusted classes after allowing untrusted code to load arbitrary classes  ~DS)

    Class loading is poorly-understood; there are several JavaOne lectures trying to clear things up (and not doing that good a job).

    IIRC I've had long arguments about whether this rule should stay; it strikes me as informative rather than normative.

    The rule was lifted from Sun/Oracle's own secure coding standard, with the emphasis being that the methods listed in the table do a lessor security check than other sensitive methods (such as methods for opening files or network connections).

      • I agree with David's reasoning about class loaders and visibility ~ his last comment
      • Thanks David for pointing out that SEC04 is actually SEC03 now
      • In my last edit of this guideline I tried to clarify that the class loading mechanism provides security that is different from the one provided by the AccessController/security manager. Someone could get confused.
      • We know that except for loadLibrary() and load() all the listed methods do not throw a security exception by using a security manager check. The question is - is untrusted code, say an applet, allowed to invoke these methods? If this guideline is followed that should be disallowed for security reasons (what prevents the invocations? Even the security manager may be employed here - will need to check what happens exactly). So the advice does appear to carry some weight.
  6. These are guidelines, so they do not need to have a normative requirement.  In fact, if they have a normative requirement, they should probably go in the Java Secure Coding Standard and not here.

  7. We should probably note that violation of this rule was involved in both of the recent Java zero-day attacks (August '12 and January '13).  David???

     

    1. I've added a NCCE/CS pair from the January exploit. 

      1. David, the discussion you have at https://www.cert.org/blogs/certcc/2013/01/anatomy_of_java_exploits.html is useful for understanding the first NCE/CS and how an attacker can bypass standard security manager checks and then exploit the class loader issue. Can we fit that text here?

        1. I don't mind that text coming here, but IMO most of it is irrelevant, as it is about two exploits and four vulnerabilities, and this rule only focuses on one. Go ahead and copy whatever text from there that you would find helpful.

  8. The August-class.forName vul, mentioned in my CERT/CC blog post might make a good example for this rule.