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

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

问题描述

我学到的知识越多,对于 java.lang.reflect.AccessibleObject.setAccessible 的力量越大,我所能做的就越是惊讶。这是从我对这个问题的回答(使用反射来更改静态最终的File.separatorChar进行单元测试)。

  import java.lang 。反映。*; 

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); //一切都是真的
}
}

不客气的东西:

  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 ,但必须承认它具有合法用途来提供它。所以我的问题是:




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


    • Java可以首先设计为不需要这个需求吗?

    • 什么是负面后果(如果有的话)?


  • 你可以将 setAccessible 合法使用?


    • 只能通过 SecurityManager


      • 它是如何工作的?白名单/黑名单,粒度等?

      • 在应用程序中必须配置它是常见的吗?


    • 无论 SecurityManager 配置,我可以将我的课程写成 setAccessible


      • 还是管理配置的任何人的怜悯?








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



我的任何类都没有任何可强制执行的隐私。单身人士模式(将其优点放在一边)现在是不可能执行的。如上面的代码片段所示,即使是Java基础工作的一些基本假设甚至不能保证。



这些问题是不是真的吗?






好的,我刚刚确认:感谢 setAccessible ,Java字符串是 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); // 你好,世界!
mutate(s);
System.out.println(s); // 你好,世界!
}
}

我是唯一一个认为这是巨大的人关心?

解决方案

我需要担心吗?



这完全取决于你正在写什么类型的程序和什么样的架构。



如果你正在分发软件组件叫做foo.jar给世界各地的人,你完全是怜悯的。他们可以修改.jar内的类定义(通过逆向工程或直接的字节码操作)。他们可以在自己的JVM中运行你的代码等等。在这种情况下,令人担忧的将不会很好。



如果你正在编写一个只与人和系统通过HTTP和你控制应用服务器,这也不是一个问题。确定您公司的同行编码者可能会创建破坏您的单身人格模式的代码,但只有当他们真的想要。



如果您将来的工作正在Sun Microsystems / Oracle,您的任务是为Java内核或其他受信任的组件编写代码,这是您应该注意的事项。然而,担心,只会让你失去你的头发。无论如何,他们可能会让您阅读安全编码指南以及内部文档。



如果你要编写Java小程序,安全框架是你应该注意的事情。您会发现尝试调用setAccessible的未签名小程序将只会导致一个SecurityException。



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



在沙盒环境(例如Java Applet,JavaFX)中,每个类都有一组权限并且访问Unsafe,setAccessible和定义本地实现是由SecurityManager控制的。



Java访问修饰符不是一个安全机制。



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



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

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



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



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



Java可以首先设计为不需要这个需求吗?



这是一个非常深刻的问题,很好地回答。我想是的,但你需要添加一些可能不是最喜欢的机制。



你可以将setAccessible限制为合法使用只有?



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



我可以将我的类写入设置为无限制的SecurityManager配置? ...或者我受到管理配置的任何人的怜悯吗?



你不能,而且你绝对是。


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"
   }
}

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:

  • 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?
  • Can you restrict setAccessible to legitimate uses only?
    • Is it only through SecurityManager?
      • How does it work? Whitelist/blacklist, granularity, etc?
      • Is it common to have to configure it in your applications?
    • Can I write my classes to be setAccessible-proof regardless of SecurityManager configuration?
      • Or am I at the mercy of whoever manages the configuration?

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

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???


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?

解决方案

DO I NEED TO WORRY ABOUT THIS???

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

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.

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.

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.

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 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.

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 access modifiers are not intended to be a security mechanism."

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.

What are the truly legitimate uses for setAccessible?

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.

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

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).

Could Java has been designed as to NOT have this need in the first place?

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.

Can you restrict setAccessible to legitimate uses only?

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.

Can I write my classes to be setAccessible-proof regardless of SecurityManager configuration? ... Or am I at the mercy of whoever manages the configuration?

You can't and you most certainly are.

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

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