gpt4 book ai didi

java - java的内部类会带来安全风险吗?

转载 作者:IT老高 更新时间:2023-10-28 21:02:55 26 4
gpt4 key购买 nike

最近,我项目的安全团队发布了一份安全代码指南文档,旨在用作我们代码审查的一部分。首先让我印象深刻的是一个项目,上面写着“不要使用内部类”。我认为这似乎是一个非常严厉和笼统的声明。如果使用正确,内部类很好吗?但我做了一些谷歌搜索,发现 this ,为方便起见,在此引用。

Rule 5: Don't Use Inner Classes

Some Java language books say that inner classes can only be accessed by the outer classes that enclose them. This is not true. Java byte code has no concept of inner classes, so inner classes are translated by the compiler into ordinary classes that happen to be accessible to any code in the same package. And Rule 4 says not to depend on package scope for protection.

But wait, it gets worse. An inner class gets access to the fields of the enclosing outer class, even if these fields are declared private. And the inner class is translated into a separate class. In order to allow this separate class access to the fields of the outer class, the compiler silently changes these fields from private to package scope! It's bad enough that the inner class is exposed, but it's even worse that the compiler is silently overruling your decision to make some fields private. Don't use inner classes if you can help it. (Ironically, the new Java 2 doPrivileged() API usage guidelines suggest that you use an inner class to write privileged code. That's one reason we don't like the doPrivileged() API.)

我的问题是

  1. 这种行为在 java 5/6 中是否仍然存在?
  2. 考虑到除了外部类和内部类之外的任何试图访问外部类的私有(private)成员的类都无法编译,这实际上是否存在安全风险?
  3. 它是否构成足够的安全风险来保证“准则”“不要使用内部类”?

最佳答案

此信息已经过时了大约十年。 AccessController.doPrivileged 广泛使用匿名内部类应该是一个线索。 (如果您不喜欢该 API,请考虑 JDK 中错误丢失的 try-finally block 的比例。)

策略是,如果两个类由不同的类加载器加载或具有不同的证书,则它们不能共享同一个包。为了获得更多保护,请在您的 jar list 中将包裹标记为已密封。因此,从安全的角度来看,“规则 4”是虚假的,因此也是这条规则。

在任何情况下,制定安全策略您都应该了解您要防范的内容。这些类型的策略用于处理可能具有不同信任级别的移动代码(移动的代码)。除非您正在处理移动代码,或者您的代码正在进入可能需要的库,否则这些预防措施几乎没有意义。然而,使用健壮的编程风格几乎总是一个好主意,例如复制和验证参数和返回值。

关于java - java的内部类会带来安全风险吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1935479/

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