不可能定义一个安全策略来阻止代码使用标准 Java SecurityManager 创建和启动新线程。
假设您有以下代码:
public class Test {
public static void main(String [] args) {
System.out.println(System.getSecurityManager() != null ? "Secure" : "");
Thread thread = new Thread(
new Runnable() {
public void run() {
System.out.println("Ran");
}
});
thread.start();
}
}
然后使用以下命令运行它:
java -Djava.security.manager -Djava.security.policy==/dev/null Test
它会运行得很好并输出:
Secure
Ran
即使我们将安全策略设置为 /dev/null ,这将为任何代码授予零权限。因此,不可能授予较少的权限来阻止代码创建该线程。
这是因为标准 java.lang.SecuritManager 仅在代码尝试在根 ThreadGroup 中创建线程时执行权限检查。同时,SecurityManager的getThreadGroup方法总是返回当前Thread的线程组,它永远不会是根线程组,因此总是会授予创建新Thread的权限。
解决这个问题的一种方法是子类化 java.lang.SecurityManager 并重写 getThreadGroup 方法以返回根 ThreadGroup。然后,这将允许您根据代码是否具有 java.lang.RuntimePermission“modifyThreadGroup”来控制代码是否可以创建线程。
因此,如果我们现在定义 SecurityManager 的子类,如下所示:
public class ThreadSecurityManager extends SecurityManager {
private static ThreadGroup rootGroup;
@Override
public ThreadGroup getThreadGroup() {
if (rootGroup == null) {
rootGroup = getRootGroup();
}
return rootGroup;
}
private static ThreadGroup getRootGroup() {
ThreadGroup root = Thread.currentThread().getThreadGroup();
while (root.getParent() != null) {
root = root.getParent();
}
return root;
}
}
然后再次运行我们的命令,但这次指定我们的子类 ThreadSecurityManager:
java -Djava.security.manager=ThreadSecurityManager -Djava.security.policy==/dev/null Test
当我们尝试创建新线程时,我们的 Test 类中出现异常:
Exception in thread "main" java.security.AccessControlException: access denied ("java.lang.RuntimePermission" "modifyThreadGroup")