本文介绍了有没有办法让java中的SecurityManager有选择地授予ReflectPermission(“suppressAccessChecks”)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法让Java中的SecurityManager有选择地授予ReflectPermission(suppressAccessChecks),具体取决于调用setAccessible()的详细信息?我没有看到任何方法可以完成。

Is there any way for a SecurityManager in Java to selectively grant ReflectPermission("suppressAccessChecks") depending on the details of what setAccessible() is being called on? I don't see any way for this to be done.

对于某些沙盒代码,它将非常有用(例如运行各种动态JVM语言)以允许要调用的setAccessible()反射API,但是当在源自沙盒代码的类的方法/字段上调用setAccessible()时,

For some sandboxed code, it would be very useful (such as for running various dynamic JVM languages) to allow the setAccessible() reflection API to be called, but only when setAccessible() is called on a method/field of a class that originates in the sandboxed code.

如果不可能,除了选择性授予ReflectPermission(suppressAccessChecks)之外,是否还有其他任何建议?在所有情况下,如果SecurityManager.checkMemberAccess()有足够的限制条件,可能会安全吗?

Does anyone have any alternative suggestions other than selective granting of ReflectPermission("suppressAccessChecks") if this isn't possible? Perhaps it would be safe to grant in all cases if SecurityManager.checkMemberAccess() is sufficiently restrictive?

推荐答案

也许看着电话堆栈就足够了吗?类似于:

Maybe looking at the call stack would be enough for your purposes? Something like:

import java.lang.reflect.ReflectPermission;
import java.security.Permission;

public class Test {
    private static int foo;

    public static void main(String[] args) throws Exception {
        System.setSecurityManager(new SecurityManager() {
            @Override
            public void checkPermission(Permission perm) {
                if (perm instanceof ReflectPermission && "suppressAccessChecks".equals(perm.getName())) {
                    for (StackTraceElement elem : Thread.currentThread().getStackTrace()) {
                        if ("Test".equals(elem.getClassName()) && "badSetAccessible".equals(elem.getMethodName())) {
                            throw new SecurityException();
                        }
                    }
                }
            }
        });

        goodSetAccessible(); // works
        badSetAccessible(); // throws SecurityException
    }

    private static void goodSetAccessible() throws Exception {
        Test.class.getDeclaredField("foo").setAccessible(true);
    }

    private static void badSetAccessible() throws Exception {
        Test.class.getDeclaredField("foo").setAccessible(true);
    }
}

这篇关于有没有办法让java中的SecurityManager有选择地授予ReflectPermission(“suppressAccessChecks”)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 04:17