Java Security Manager completely disable reflection

こ雲淡風輕ζ 提交于 2020-02-27 05:03:31

问题


I've been reading quite a lot of questions on Stackoverflow about this question but couldn't quit find a solution or answer for my problem. If there is already one I would be grateful if somebody would give a hint ...

My problem/question is if it is possible to completely disable reflection for not trustworthy code? Functions like getDeclaredMethods()(See test.java). I've already got a Java Security Manager which throws Security Exceptions if the code tries to write/read/etc. ...

If it is possible, can somebody show me how?

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());
}

回答1:


So I solved the problem not directly with checkPermission(). My workaround is to check if the java.lang.reflect package is accessed.

@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!");
    }
}



回答2:


Extend your SecurityManager and have it check for ReflectPermission and RuntimePermission. Then you have to decide whether 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:


As long as we dont provide security manager, private members of class can be accessible. To access private members of class you should set setAccessible(true), this will allow you to access private members. To restrict access private members Keep below line of code in your immutable class constructor.

System.setSecurityManager(new SecurityManager());

This will throw AccessControlException when you try to set setAccessible(true).



来源:https://stackoverflow.com/questions/40218973/java-security-manager-completely-disable-reflection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!