Java Security Manager completely disables display

I read quite a few questions about Stackoverflow about this question, but couldn't stop finding a solution or answer my problems. If there is already one, I would be grateful if someone gave a hint ...

My problem / question is, can reflection be completely disabled for untrusted code? Functions like getDeclaredMethods() (see Test.java). I already have a Java security manager that throws security exceptions if the code tries to write / read / etc ....

If possible, can someone show me?

Bruno

test.java

 TestClass cls = new TestClass(); Class c = cls.getClass(); // returns the array of Method objects Method[] m = c.getDeclaredMethods(); for(int i = 0; i < m.length; i++) { System.out.println("method = " + m[i].toString()); } 
+6
source share
2 answers

Therefore, I did not solve the problem directly with checkPermission (). My workaround is to check if the java.lang.reflect package is available.

 @Override public void checkPackageAccess(String pkg){ // don't allow the use of the reflection package if(pkg.equals("java.lang.reflect")){ throw new SecurityException("Reflection is not allowed!"); } } 
+4
source

Extend your SecurityManager and test it for ReflectPermission and RuntimePermission . Then you need to decide if the caller has permission for Reflection:

 @Override public void checkPermission(Permission perm) { if (perm instanceof ReflectPermission) { // called for Method.setAccessible(true) // determine whether caller is permitted using getClassContext() } if (perm instanceof RuntimePermission) { if (perm.implies(new RuntimePermission("accessDeclaredMembers"))) { // called for Class.getDeclardFields() System.out.println("getDeclaredFields() called"); } } 
+3
source

Source: https://habr.com/ru/post/1011651/


All Articles