javasecuritysecuritymanager

How to create newInstance with enabled SecurityManager in Java


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

classLoader.loadClass(UNSTRUSTED_CLASS).newInstance()

The problem is that if I enable security manager it doesn't permit to call newInstance, but if I have security manager disabled one can put malicious code into initialization block and it executes with no problem.

How one accomplishes creating new instance of untrusted class?


Solution

  • Well, what I used. As far as I have custom class loader which loads untrusted code from specific location I could define code base in policy file for my trusted code, which I granted permission to use reflection. Thus untrusted code from another codebase don't have this permission. i.e.

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

    With this policy file all code loaded from other locations than specified in codeBase will not have any permissions.