如何将 setAccessible 限制为仅“合法"用途? [英] How to limit setAccessible to only "legitimate" uses?

查看:35
本文介绍了如何将 setAccessible 限制为仅“合法"用途?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 java.lang.reflect.AccessibleObject.setAccessible 的功能了解得越多,我就越惊讶于它的功能.这改编自我对问题的回答(使用反射更改静态最终 File.separatorChar 以进行单元测试).

The more I learned about the power of java.lang.reflect.AccessibleObject.setAccessible, the more astonished I am at what it can do. This is adapted from my answer to the question (Using reflection to change static final File.separatorChar for unit testing).

import java.lang.reflect.*;

public class EverythingIsTrue {
   static void setFinalStatic(Field field, Object newValue) throws Exception {
      field.setAccessible(true);

      Field modifiersField = Field.class.getDeclaredField("modifiers");
      modifiersField.setAccessible(true);
      modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);

      field.set(null, newValue);
   }
   public static void main(String args[]) throws Exception {      
      setFinalStatic(Boolean.class.getField("FALSE"), true);

      System.out.format("Everything is %s", false); // "Everything is true"
   }
}

你可以做出真正令人发指的事情:

You can do truly outrageous stuff:

public class UltimateAnswerToEverything {
   static Integer[] ultimateAnswer() {
      Integer[] ret = new Integer[256];
      java.util.Arrays.fill(ret, 42);
      return ret;
   }   
   public static void main(String args[]) throws Exception {
      EverythingIsTrue.setFinalStatic(
         Class.forName("java.lang.Integer$IntegerCache")
            .getDeclaredField("cache"),
         ultimateAnswer()
      );
      System.out.format("6 * 9 = %d", 6 * 9); // "6 * 9 = 42"
   }
}

大概 API 设计者意识到 setAccessible 的可滥用性,但必须承认它具有合法用途来提供它.所以我的问题是:

Presumably the API designers realize how abusable setAccessible can be, but must have conceded that it has legitimate uses to provide it. So my questions are:

  • setAccessible 真正合法的用途是什么?
    • Java 是否可以设计为一开始就没有这种需求?
    • 这种设计的负面后果(如果有的话)是什么?
    • What are the truly legitimate uses for setAccessible?
      • Could Java has been designed as to NOT have this need in the first place?
      • What would the negative consequences (if any) of such design be?
      • 是否只能通过SecurityManager?
        • 它是如何工作的?白名单/黑名单、粒度等?
        • 必须在您的应用程序中对其进行配置是否很常见?
        • 或者我是否受到管理配置的人的支配?

        我想还有一个更重要的问题是:我需要担心这个吗???

        I guess one more important question is: DO I NEED TO WORRY ABOUT THIS???

        我的任何课程都没有任何可强制执行的隐私.单例模式(将对其优点的怀疑放在一边)现在无法执行.正如我上面的片段所示,即使是关于 Java 基础工作原理的一些基本假设也无法保证.

        None of my classes have any semblance of enforceable privacy what-so-ever. The singleton pattern (putting doubts about its merits aside) is now impossible to enforce. As my snippets above show, even some basic assumptions of how Java fundamental works is not even close to being guaranteed.

        这些问题不是真的吗???

        ARE THESE PROBLEMS NOT REAL???

        好的,我刚刚确认:感谢 setAccessible,Java 字符串不是不可变的.

        Okay, I just confirmed: thanks to setAccessible, Java strings are NOT immutable.

        import java.lang.reflect.*;
        
        public class MutableStrings {
           static void mutate(String s) throws Exception {
              Field value = String.class.getDeclaredField("value");
              value.setAccessible(true);
              value.set(s, s.toUpperCase().toCharArray());
           }   
           public static void main(String args[]) throws Exception {
              final String s = "Hello world!";
              System.out.println(s); // "Hello world!"
              mutate(s);
              System.out.println(s); // "HELLO WORLD!"
           }
        }
        

        只有我认为这是一个巨大的问题吗?

        Am I the only one who thinks this is a HUGE concern?

        推荐答案

        我需要担心这个吗???

        这完全取决于您编写的程序类型和架构类型.

        That depends entirely on what types of programs you're writing and for what kind of an architecture.

        如果您要向全世界的人们分发名为 foo.jar 的软件组件,那么无论如何您都完全可以任由他们摆布.他们可以修改 .jar 中的类定义(通过逆向工程或直接字节码操作).他们可以在他们自己的 JVM 等中运行你的代码.在这种情况下,担心对你​​没有好处.

        If you're distributing a software component called foo.jar to the people of the world, you're completely at their mercy anyway. They could modify the class definitions inside your .jar (through reverse engineering or direct bytecode manipulation). They could run your code in their own JVM, etc. In this case worrying will do you no good.

        如果您正在编写仅通过 HTTP 与人和系统交互的 Web 应用程序,并且您控制应用程序服务器,那么这也不是问题.当然,您公司的其他编码人员可能会创建打破单例模式的代码,但前提是他们真的想这样做.

        If you're writing a web-application that only interfaces with people and systems via HTTP and you control the application server, it's also not a concern. Sure the fellow coders at your company may create code that breaks your singleton pattern, but only if they really want to.

        如果您未来的工作是在 Sun Microsystems/Oracle 编写代码,并且您的任务是为 Java 核心或其他受信任的组件编写代码,那么您应该注意这一点.然而,担心只会让你脱发.无论如何,他们可能会让您阅读安全编码指南以及内部文档.

        If your future job is writing code at Sun Microsystems/Oracle and you're tasked with writing code for the Java core or other trusted components, it's something you should be aware of. Worrying, however, will just make you lose your hair. In any case they'll probably make you read the Secure Coding Guidelines along with internal documentation.

        如果您要编写 Java 小程序,那么您应该了解安全框架.您会发现尝试调用 setAccessible 的未签名小程序只会导致 SecurityException.

        If you're going to be writing Java applets, the security framework is something you should be aware of. You'll find that unsigned applets trying to call setAccessible will just result in a SecurityException.

        setAccessible 不是唯一绕过传统完整性检查的东西.有一个名为 sun.misc.Unsafe 的非 API 核心 Java 类,它几乎可以做任何它想做的事情,包括直接访问内存.本机代码 (JNI) 也可以绕过这种控制.

        setAccessible is not the only thing that goes around conventional integrity checks. There's a non-API, core Java class called sun.misc.Unsafe that can do pretty much anything at all it wants to, including accessing memory directly. Native code (JNI) can go around this kind of control as well.

        在沙盒环境(例如 Java Applets、JavaFX)中,每个类都有一组权限,对 Unsafe、setAccessible 和定义本机实现的访问由 SecurityManager 控制.

        In a sandboxed environment (for example Java Applets, JavaFX), each class has a set of permissions and access to Unsafe, setAccessible and defining native implementations are controlled by the SecurityManager.

        Java 访问修饰符不是一种安全机制."

        "Java access modifiers are not intended to be a security mechanism."

        这在很大程度上取决于运行 Java 代码的位置.核心 Java 类确实使用访问修饰符作为安全机制来强制执行沙箱.

        That very much depends on where the Java code is being run. The core Java classes do use access modifiers as a security mechanism to enforce the sandbox.

        setAccessible 真正合法的用途是什么?

        Java 核心类使用它作为访问出于安全原因必须保持私有的内容的简单方法.例如,Java 序列化框架在反序列化对象时使用它来调用私有对象构造函数.有人提到了 System.setErr,这将是一个很好的例子,但奇怪的是 System 类方法 setOut/setErr/setIn 都使用本机代码来设置最终字段的值.

        The Java core classes use it as an easy way to access stuff that has to remain private for security reasons. As an example, the Java Serialization framework uses it to invoke private object constructors when deserializing objects. Someone mentioned System.setErr, and it would be a good example, but curiously the System class methods setOut/setErr/setIn all use native code for setting the value of the final field.

        另一个明显的合法用途是需要窥探对象内部的框架(持久性、Web 框架、注入).

        Another obvious legitimate use are the frameworks (persistence, web frameworks, injection) that need to peek into the insides of objects.

        在我看来,调试器不属于这一类,因为它们通常不在同一个 JVM 进程中运行,而是使用其他方式 (JPDA) 与 JVM 进行接口.

        Debuggers, in my opinion, don't fall into this category, as they normally don't run in the same JVM process, but instead the interface with the JVM using other means (JPDA).

        Java 是否可以设计为一开始就没有这种需求?

        这是一个非常深刻的问题,需要很好地回答.我想是的,但您需要添加一些其他可能不是那么可取的机制.

        That's a pretty deep question to answer well. I imagine yes, but you'd need to add some other mechanism(s) that might not be all that preferrable.

        您能否将 setAccessible 限制为仅用于合法用途?

        您可以应用的最直接的 OOTB 限制是拥有一个 SecurityManager 并只允许 setAccessible 来自某些来源的代码.这是 Java 已经做的 - 来自 JAVA_HOME 的标准 Java 类可以执行 setAccessible,而来自 foo.com 的未签名小程序类不允许执行 setAccessible.如前所述,此权限是二元的,从某种意义上说,要么拥有,要么不拥有.没有明显的方法可以允许 setAccessible 修改某些字段/方法同时禁止其他字段/方法.但是,您可以使用 SecurityManager 禁止类完全引用某些包,无论有没有反射.

        The most straight-forward OOTB restriction you can apply is to have a SecurityManager and allow setAccessible only to code coming from certain sources. This is what Java already does - the standard Java classes that come from your JAVA_HOME are allowed to do setAccessible, while unsigned applet classes from foo.com aren't allowed to do setAccessible. As was said before, this permission is binary, in the sense that one either has it or not. There is no obvious way to allow setAccessible to modify certain fields/methods while disallowing others. Using the SecurityManager you could, however, disallow classes from referencing certain packages completely, with or without reflection.

        无论 SecurityManager 配置如何,我都可以将我的类编写为 setAccessible-proof 吗?... 还是我任由管理配置的人摆布?

        你不能,而且你肯定是.

        You can't and you most certainly are.

        这篇关于如何将 setAccessible 限制为仅“合法"用途?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆