Most methods lack security manager checks because they cannot 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 it proceedsthey 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 a trusted method methods in the call stack.
However, certain methods use a reduced-security check that checks only that the calling method has access rather than checking every method in the call stack. Code 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 |
---|
|
|
|
|
|
|
|
|
Because the java.lang.reflect.Field.setAccessible/getAccessible
methods ()
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 discussed in 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 consequently are 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 used 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 which 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 often 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 |
---|
|
|
|
|
|
|
|
|
|
|
|
|
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.
A problem arises because the class loader delegation model is fundamental to many Java implementations and frameworks. The best advice is to avoid exposing the methods listed in the table 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 its declared accessibility. When the trusted code uses any of the tabulated APIs, it bypasses security manager checks (with the exception of loadLibrary()
and load()
).
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 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.
...
Code Block | ||
---|---|---|
| ||
public void load(String libName) { AccessController.doPrivileged(new PrivilegedAction() { public Object run() { System.loadLibrary(libName); return null; } }); } |
It 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 indirectly 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 being applied to callers further up the execution chain.
Nonnative library code can also be susceptible to related security flaws. Loading a nonnative safe . 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, after loading an attacker could then load an additional unsafe library, an attacker can easily exploit the safe library if it contains other vulnerabilities. Moreoverlibrary that exploits the first library's vulnerability. Moveover, nonnative libraries often use doPrivileged
blocks, making them attractive targets.
...
This compliant solution hard codes the name of the library to prevent the possibility of tainted values. It also reduces the accessibility of method the load()
method from public
to private
. Consequently, untrusted callers are prohibited from loading the awt
library.
...
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 above is unsafe because it uses the url
argument to indicate a class to be loaded; this class serves as the database driver.
...
Code Block | ||||
---|---|---|---|---|
| ||||
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.0u10 0 update 6 that 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 a Class
object. This method delegated its work to the loadClass()
method, whose source code is shown here: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 get any class, bypassing the security manager:
Code Blockcode | ||||
---|---|---|---|---|
| ||||
/** * 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<?> theClassprivate Class GetClass(String paramString) throws Throwable { Object arrayOfObject[] = new Object[1]; arrayOfObject[0] = paramString; Expression localExpression = new Expression(Class.class, "forName", arrayOfObject); localExpression.execute(); if (className == null) { throw new RuntimeOperationsException(new IllegalArgumentException("The class name cannot be null"), return (Class)localExpression.getValue(); } |
The java.beans.Expression.execute()
method delegates its work to the following method:
Code Block | ||||
---|---|---|---|---|
| ||||
private Object invokeInternal() throws Exception { Object target = getTarget(); String methodName = getMethodName(); if (target == null || methodName == null) { throw new NullPointerException( (target == null ? "target" : "methodName") + "Exception occurredshould duringnot objectbe instantiationnull"); } Object[] arguments try { = getArguments(); if (loaderarguments == null) { arguments = emptyArray; } loader = MBeanInstantiator.class.getClassLoader(); if (loader != null) { theClass = Class.forName(className, false, loader);// 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:
Code Block | ||||
---|---|---|---|---|
| ||||
public static Class<?> findClass(String name) throws ClassNotFoundException { try { ClassLoader loader = Thread.currentThread().getContextClassLoader( else { theClass = Class.forName(className); if (loader == null) }{ }loader catch= ClassLoader.getSystemClassLoader(ClassNotFoundException e) {; } throw newif ReflectionException(e, loader != null) { "The MBean class could not be loaded"return Class.forName(name, false, loader); } } catch (ClassNotFoundException exception) { // Use current class returnloader theClass;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.
) method. The forName()
method delegates the work of loading the class to its to obtain the requested class. Class.forName()
delegates the search to the calling method's class loader. Because the calling method is MBeanInstantiator.loadClass()
, the core In this case, the calling class (com.sun.beans.finder.ClassFinder
) is part of core Java, so the trusted class loader is used , which provides no security checks.
...
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.0p11 by adding an access check to the loadClass0 update 7 by patching the com.sun.beans.finder.ClassFinder.findClass()
method. This access check ensures that the caller is permitted to access the class being sought: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.
Code Block | ||||
---|---|---|---|---|
| ||||
// ... if (className == null)public static Class<?> findClass(String name) throws ClassNotFoundException { checkPackageAccess(name); try { throw new RuntimeOperationsException(newClassLoader loader = Thread.currentThread().getContextClassLoader(); if (loader == null) { IllegalArgumentException("The class name// cannotCan be null"), in IE (see 6204697) loader = ClassLoader.getSystemClassLoader(); } if (loader != null) { "Exception occurred during object instantiation"return Class.forName(name, false, loader); } } catch ReflectUtil.checkPackageAccess(className);(ClassNotFoundException exception) { try// { Use current class loader instead } ifcatch (loaderSecurityException == null) // ... exception) { // Use current class loader instead } return Class.forName(name); } |
Noncompliant Code Example (
...
CVE-2013-0422)
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.)
The exploit runs as an applet. 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).
One goal of the exploit code was to access the private sun.awt.SunToolkit
class. However, invoking class.forName()
directly would cause a SecurityException
to be thrown. Consequently, the exploit code contained the following method to get any class, bypassing the security manager:
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:
Code Block | ||||
---|---|---|---|---|
| ||||
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:
| ||||
/**
* 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 | ||||
Code Block | ||||
---|---|---|---|---|
| ||||
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) { argumentsthrow = emptyArray; } // Class.forName() won't load classes outside // of core from a class inside core. Special // case this method. 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:
Code Block | ||||
---|---|---|---|---|
| ||||
public static Class<?> findClass(String name) throws ClassNotFoundException { try { ClassLoader loader = Thread.currentThread().getContextClassLoader(); 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) { loadertheClass = ClassLoaderClass.getSystemClassLoader(forName(className, false, loader); } else { if (loader != null) { theClass return= Class.forName(name, false, loaderclassName); } } catch (ClassNotFoundException exceptione) { // Use current classthrow loader instead new ReflectionException(e, } catch (SecurityException exception) { "The MBean class //could Usenot current class loader instead be loaded"); } return Class.forName(name)theClass; } |
Although this method is called in the context of an applet, it uses Class.forName()
to obtain the requested class. And This method delegates the task of dynamically loading the specified class to the Class.forName()
delegates the search to the method, which delegates the work to its calling method's class loader. In this case, Because the calling class (com.sun.beans.finder.ClassFinder
) is part of core Java, so the trusting class loader is used in place of the more paranoid applet class loadermethod is MBeanInstantiator.loadClass()
, the core class loader is used, which provides no security checks.
Compliant Solution (CVE-
...
2013-
...
0422)
Oracle mitigated this vulnerability 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 for trusted methods.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:
Code Block | ||||
---|---|---|---|---|
| ||||
public static Class<?> findClass(String name) throws ClassNotFoundException { checkPackageAccess(name); try { ClassLoader loader = Thread.currentThread().getContextClassLoader(); if (loader == null) {// ... if (className == null) { throw new RuntimeOperationsException(new // Can be null in IE IllegalArgumentException(see 6204697) loader = ClassLoader.getSystemClassLoader();"The class name cannot be null"), } if (loader != null) { return Class.forName(name, false, loader); } "Exception }occurred catchduring (ClassNotFoundExceptionobject exceptioninstantiation") {; //} Use current class loader instead ReflectUtil.checkPackageAccess(className); } catch (SecurityException exception)try { // Use current classif (loader instead } return Class.forName(name); }== null) // ... |
Applicability
Allowing untrusted code to invoke methods with reduced-security checks can grant excessive abilities to malicious coderesult in privilege escalation. Likewise, allowing untrusted code to carry out 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. Do not use the immediate caller's class loader as the third argument when instances must be returned to untrusted code.
Code Block |
---|
public static Class forName(String name, boolean initialize, ClassLoader loader) /* explicitly specify the class loader to use */ throws ClassNotFoundException |
Do not use the immediate caller's class loader as the third argument when instances must be returned to untrusted code.
Bibliography
[API 2011] | Class ClassLoader |
[Chan 1999] | java.lang.reflect AccessibleObject |
[Guillardoy 2012] | Java 0-day Analysis (CVE-2012-4681) |
[Manion 2013] | Anatomy of Java Exploits |
[Oracle 2013] | Oracle Security Alert for CVE-2013-0422 |
...