反思安全 [英] Reflection Security

查看:197
本文介绍了反思安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过不允许方法字段构造函数<来强制执行反射安全性/ code>要调用的对象 setAccessible(true)? SecurityPolicy文件还是别的?

How to enforce reflection security by not allow the Method, Field, Constructor object to call setAccessible(true) ? SecurityPolicy File or something else?

通常,对于独立的Java应用程序,没有注册 SecurityManager

Normally for stand-alone Java applications there is no SecurityManager registered.

我使用此 System.setSecurityManager(new SecurityManager());

这种方法适用于调用方法。

This approach will work for calling methods.

我想强制执行使用jar的整个jar或客户端代码不允许调用 setAccessible(true);

I would like to enforce the whole jar or client code that uses the jar is not allow to call setAccessible(true);

有更好的方法吗?

谢谢。

推荐答案

嗯,它为setAccessible工作。请参阅:

Um, it does work for setAccessible. See:

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)

根据中的评论,它可能对您不起作用的一个原因是这篇文章它没有用于在Java 1.5中工作,但在6及之后工作。

One reason it might've not worked for you is that according to comments in this post it didn't use to work in Java 1.5, but works in 6 and thereafter.

编辑:要拒绝特定的罐子,你需要使用一个策略文件,例如:

to deny it for specific jars, you need to either use a policy file, example:

// specific file
grant codeBase "file:/test/path/tools.jar" {
  // no permissions for this one
};

// default to giving all
grant {
  permission java.security.AllPermission;
};

有两种方法可以指定策略文件,或者将其作为默认值添加,或者只提供那些已指定(来源):

There's two ways of specifying the policy file, either give it as additions to default, or give only those that are specified (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.

...或实现自定义安全管理器, 看起来并不那么难。但是我自己也没做过。

...or implement a custom security manager, which doesn't look that hard. Haven't done that myself though.

这篇关于反思安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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