...
This noncompliant code example returns an instance of the immediate caller's class loader to any invoker. A malicious invoker can consequently, obtain the associated class loader using standard APIs such as java.lang.Class.getClassLoader()
. Once this is achieved, it is trivial to use Class.forname()
to load the malicious class from attacker space or exploit a trusted method that calls Class.newInstance()
on an arbitrarily supplied object. Class.newInstance()
does not throw any security exception when the immediate caller's class loader is either the same or the delegation ancestor of the object's class loader. (SEC05-J. Do not expose standard APIs that may bypass Security Manager checks to untrusted code)sql.Connection
from trusted to untrusted code. The untrusted code that does not have the permissions to create an SQL connection can bypass this restriction by directly using the acquired instance.
Code Block | ||
---|---|---|
| ||
public ClassConnection doLogicgetConnection() { ClassLoader myLoader = new myClassLoader();// ... Class myClass = myLoader.loadClass("MyClass"); return myClass; // Returns Class instance to untrusted codereturn DriverManager.getConnection(url, username, password); } |
Compliant Solution
Always make sure that any internal Class
, ClassLoader
and Thread
instances Ensure that instances of objects created using the vulnerable methods are not returned to untrusted code. Furthermore, it is preferable to reduce the accessibility of methods that perform sensitive operations and define wrapper methods that are accessible from untrusted code.
Code Block | ||
---|---|---|
| ||
private void doLogicgetConnection() { ClassLoader myLoader// ... conn = new myClassLoader(); Class myClass = myLoader.loadClass("MyClass"DriverManager.getConnection(url, username, password); // Do what is is required here itself; do not return myClassthe connection } public void doLogicWrapperDoDatabaseOperationWrapper() { // Perform any checks or validate input doLogicgetConnection(); } |
Exceptions
EX1: It is permissible to use APIs 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 if 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 |
...