gpt4 book ai didi

java-module - SecurityManager 弃用和通过抑制访问检查进行反射

转载 作者:行者123 更新时间:2023-12-02 01:24:11 28 4
gpt4 key购买 nike

我是一名大学讲师,我正在修改关于 Java 反射的讲座。其他年份,当我教授抑制访问检查的恐怖时,我展示了您可以设置一个 SecurityManager 并执行类似的操作

    if ("suppressAccessChecks".equals(p.getName())){
StackTraceElement[] st = Thread.currentThread().getStackTrace();
if(.. st ..) { throw new SecurityException(); }
}

通过这种方式,您可以允许白名单反序列化器仅调用suppressAccessChecks。然而,现在他们正在弃用 SecurityManager。我认为新的模块系统应该在这里有所帮助,但我找不到解释如何支持上面白名单反序列化器的想法的资源。

有什么提示吗?

最佳答案

使用 Java 模块, setAccessible is already restricted ,即使没有安全管理器:

This method may be used by a caller in class C to enable access to a member of declaring class D if any of the following hold:

  • C and D are in the same module.
  • The member is public and D is public in a package that the module containing D exports to at least the module containing C.
  • The member is protected static, D is public in a package that the module containing D exports to at least the module containing C, and C is a subclass of D.
  • D is in a package that the module containing D opens to at least the module containing C. All packages in unnamed and open modules are open to all modules and so this method always succeeds when D is in an unnamed or open module.

如果我们假设模块 M 使用模块 P 中的持久性服务的典型场景,并且成员无论如何都不可访问,则仅适用最后一条; M必须打开包裹到P启用访问覆盖。

这可以通过qualified opens directive来完成

module M {
opens aPackage.needing.persistence to P;
}

这样,只有明确指定的模块,即 P ,可以使用setAccessible对于 aPackage.needing.persistence 中类型的成员.

对于 HotSpot JVM,有选项 --add-opens允许添加合格的opens除了声明的关系之外,启动时的关系,但是已经运行的应用程序的模块无法选择在运行时创建这样的关系来本身获得额外的访问权限(除非安全性已经被破坏)。可以想象,其他环境甚至不支持这样的启动选项。


值得一提的是,仍有一些新的限制无法通过这种方式规避。正如 setAccessible ’s documentation 中也提到的那样:

This method cannot be used to enable write access to a non-modifiable final field. The following fields are non-modifiable:

  • static final fields declared in any class or interface
  • final fields declared in a hidden class
  • final fields declared in a record

另请参阅 this answer

换句话说,如果出现 record类型,持久性服务仍然必须使用构造函数来反序列化实例,即使在抑制访问检查时也是如此。

关于java-module - SecurityManager 弃用和通过抑制访问检查进行反射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75204684/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com