Java 安全管理器完全禁用反射

Java Security Manager completely disable reflection

我已经在 Whosebug 上阅读了很多关于这个问题的问题,但无法停止为我的问题找到解决方案或答案。如果已经有一个,如果有人能给出提示,我将不胜感激......

我的 problem/question 是否可以完全禁用不可信代码的反射?类似 getDeclaredMethods() 的函数(参见 test.java)。我已经有一个 Java 安全管理器,它会在代码尝试 write/read/etc 时抛出安全异常。 ...

如果可能的话,有人可以告诉我怎么做吗?

布鲁诺

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

扩展您的 SecurityManager 并让它检查 ReflectPermissionRuntimePermission。然后你要判断调用者是否有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");
    }
}

所以我没有直接用checkPermission()解决了这个问题。我的解决方法是检查 java.lang.reflect 包是否被访问。

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

只要我们不提供安全管理器,就可以访问 class 的私有成员。要访问 class 的私有成员,您应该设置 setAccessible(true),这将允许您访问私有成员。限制访问私有成员在不可变的 class 构造函数中保留以下代码行。

System.setSecurityManager(new SecurityManager());

这将在您尝试设置 setAccessible(true) 时抛出 AccessControlException。