如何通过不允许 Method
来加强反射安全, Field
, Constructor
对象调用 setAccessible(true)
? SecurityPolicy 文件还是其他?
通常对于独立的 Java 应用程序没有 SecurityManager
已注册。
我用这个System.setSecurityManager(new SecurityManager());
这种方法适用于调用方法。
我想强制执行整个 jar 或使用该 jar 的客户端代码不允许调用 setAccessible(true);
有什么更好的方法吗?
谢谢。
最佳答案
嗯,它确实适用于 setAccessible。见:
class A {
private String method1() {
return "Hello World!";
}
}
和
import java.lang.reflect.Method;
class B {
public static void main(String[] args) throws Exception {
System.setSecurityManager(new SecurityManager());
Class clazz = A.class;
Method m = clazz.getDeclaredMethod("method1");
m.setAccessible(true);
}
}
结果
Exception in thread "main" java.security.AccessControlException: access denied ("java.lang.reflect.ReflectPermission" "suppressAccessChecks")
at java.security.AccessControlContext.checkPermission(Unknown Source)
at java.security.AccessController.checkPermission(Unknown Source)
at java.lang.SecurityManager.checkPermission(Unknown Source)
at java.lang.reflect.AccessibleObject.setAccessible(Unknown Source)
at B.main(B.java:8)
根据 this post 中的评论,它可能对您不起作用的一个原因是它不适用于 Java 1.5,但适用于 6 及之后的版本。
编辑:要拒绝特定 jar,您需要使用策略文件,例如:
// specific file
grant codeBase "file:/test/path/tools.jar" {
// no permissions for this one
};
// default to giving all
grant {
permission java.security.AllPermission;
};
有两种指定策略文件的方法,要么将其添加为默认值,要么仅提供指定的文件 ( source ):
If you use
java -Djava.security.manager -Djava.security.policy==someURL SomeApp
(note the double equals) then just the specified policy file will be used; all the ones indicated in the security properties file will be ignored.
...或实现自定义安全管理器,doesn't look that hard .不过我自己还没有这样做。
关于java - 反射安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14639753/