How to create a newInstance with SecurityManager enabled in Java

I need to create a new instance of a class loaded from an untrusted classfile. Now I am doing the following:

classLoader.loadClass(UNSTRUSTED_CLASS).newInstance()

      

The problem is that if I enable the security manager, it does not allow calling newInstance, but if I have the security manager disabled, it is possible to put malicious code in the initialization block and it will work without problems.

How do I create a new instance of an untrusted class?

+3


source to share


2 answers


Good thing I used. Since I have a custom classloader that loads untrusted code from a specific location, I could define a code base in a policy file for my trusted code that I gave permission to use reflection. Therefore, untrusted code from a different codebase does not have this permission. i.e.

grant codeBase "file:/C:/path/to/trusted/code/classes" {
     permission java.lang.reflect.ReflectPermission "suppressAccessChecks";
};

      



In this policy file, all code loaded from locations other than those specified in CodeBase will not have any rights.

0


source


The static initializer and class constructors will always execute with that class on the stack and therefore the corresponding ProtectionDomain

in AccessControlContext

. This is not to say that other problems may arise, for example, when getting a class from a parent class loader that provides access to the current Thread

/ ThreadGroup

/ AppContext

/ ThreadLocal

s.



In addition, three-arg Class.forName

allows the class to be loaded without initialization. However, it is most likely more typical to load the class using code into the parent class loader.

0


source







All Articles