3

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?

krems
  • 749
  • 6
  • 14
  • Possibly duplicate of https://stackoverflow.com/questions/36091323/java-set-security-permission-of-created-instances – Akash Jul 11 '17 at 18:38
  • @Akash I've looked at that question. There's sufficient difference as I can isolate method calls, but can't isolate instantiation. unfortunately, Answer on that question doesn't help also. – krems Jul 11 '17 at 18:48
  • Can't you isolate the trusted calling type from the potentially untrusted callee, such that the former's `ProtectionDomain` can be granted (via `Policy` or `ClassLoader`) the necessary instantiation privileges, while the latter's is still subject to (strict) access control? – Uux Jul 14 '17 at 05:12
  • that's what I was trying to achieve, didn't know how now I know and shared as the answer – krems Jul 17 '17 at 16:12
  • Why on earth would you have a `SecurityManager` and not want it to apply to untrusted code? – user207421 Dec 18 '17 at 06:14
  • I want to apply to intrusted code, but NOT to apply to my code (calling reflection API) So my trusted code instantiates object of untrusted class I want security manager to be enabled while executing initialization+constructor of untrusted class, but to allow me to use reflection in my code – krems Jan 19 '18 at 09:10

2 Answers2

0

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.

krems
  • 749
  • 6
  • 14
0

The static initialiser and constructors of a class will always execute with that class on the stack, and hence the appropriate ProtectionDomain in the AccessControlContext. That's not to say there may be other issues with, for instance, actually getting a class from a parent class loader, giving access to the current Thread/ThreadGroup/AppContext/ThreadLocals.

Other than that, the three-arg Class.forName allows loading a class without initialisation. However, it's probably more typical to load the class using code in a parent class loader.

Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305