为什么我不能在SecurityManager下关闭自己的ExecutorService?

时间:2010-08-30 01:01:53

标签: java security securitymanager jsr166

在默认安全管理器下,如果我创建ExecutorService(在这种情况下为ThreadPoolExecutor),我无法将其关闭,shutdown()只需调用checkPermission("modifyThread")即可模具:

import java.util.concurrent.*;

class A {
    public static void main( String[] args) {
        Thread ct = Thread.currentThread();
        System.out.println("current thread: " + ct);
        ct.checkAccess(); // we have access to our own thread...
        ThreadPoolExecutor tpe = new ThreadPoolExecutor(
            1, // one core thread
            1, // doesn't matter because queue is unbounded
            0, TimeUnit.SECONDS, // doesn't matter in this case
            new LinkedBlockingQueue<Runnable>(), /* unbound queue for
                                                  * our single thread */
            new ThreadFactory() {
                public Thread newThread(Runnable r) {
                    // obviously never gets called as we don't add any work
                    System.out.println("making thread");
                    return new Thread(r);
                }
            }
        );
        tpe.shutdown(); // raises security exception
    }
}

Sun JDK:

  

$ java -Djava.security.manager A.   当前线程:线程[main,5,main]   线程“main”中的异常java.security.AccessControlException:访问被拒绝(java.lang.RuntimePermission modifyThread)     在   java.security.AccessControlContext.checkPermission(AccessControlContext.java:323)     在   java.security.AccessController.checkPermission(AccessController.java:546)     在   java.lang.SecurityManager.checkPermission(SecurityManager.java:532)     在   java.util.concurrent.ThreadPoolExecutor.shutdown(ThreadPoolExecutor.java:1094)     在A.main(A.java:22)

OpenJDK的:

  

$ java -Djava.security.manager A.   当前线程:线程[main,5,main]   线程“main”中的异常java.security.AccessControlException:访问被拒绝(java.lang.RuntimePermission modifyThread)         at java.security.AccessControlContext.checkPermission(AccessControlContext.java:342)         at java.security.AccessController.checkPermission(AccessController.java:553)         在java.lang.SecurityManager.checkPermission(SecurityManager.java:549)         at java.util.concurrent.ThreadPoolExecutor.checkShutdownAccess(ThreadPoolExecutor.java:711)         at java.util.concurrent.ThreadPoolExecutor.shutdown(ThreadPoolExecutor.java:1351)         在A.main(A.java:22)

为什么??????? 什么是创建一个只有你控制并关闭它的线程池的安全隐患?这是实施中的错误,还是我错过了什么?

让我们看看ExecutorService.shutdown的规范是什么......

  

启动有序关闭,其中先前提交的任务已执行,但不会接受任何新任务。如果已经关闭,调用没有额外的效果。

     

抛出:   SecurityException - 如果存在安全管理器并且关闭此ExecutorService可能会操纵不允许调用者修改的线程,因为它不包含RuntimePermission(“modifyThread”),或者安全管理器的checkAccess方法拒绝访问。

这......和它一样含糊不清。关于在ExecutorService的生命周期中制作的任何“系统线程”,规范说没有,而且它允许你提供自己的线程,这证明应该当你这样做时,请“系统线程”。 (正如我在上面的示例源中所做的那样)

感觉就像Java SE实现者看到shutdown可以引发SecurityException,所以他们就像是,“哦,好吧,我只是在这里添加随机安全检查以确保合规性” ...

问题是,通过阅读OpenJDK源代码(openjdk-6-src-b20-21_jun_2010),结果发现方式任何线程都被创建,是通过调用你提供的ThreadFactory(由于我没有创建任何工作而从未在我的测试用例中调用过,我不会调用prestartCoreThreadpreStartAllCoreThreads)。因此在OpenJDK的ThreadPoolExecutor中没有明显的原因进行安全检查(就像在sun-jdk-1.6中完成的那样,但是我没有源代码):

/**
 * Initiates an orderly shutdown in which previously submitted
 * tasks are executed, but no new tasks will be accepted.
 * Invocation has no additional effect if already shut down.
 *
 * @throws SecurityException {@inheritDoc}
 */
public void shutdown() {
    final ReentrantLock mainLock = this.mainLock;
    mainLock.lock();
    try {
        checkShutdownAccess();
        advanceRunState(SHUTDOWN);
        interruptIdleWorkers();
        onShutdown(); // hook for ScheduledThreadPoolExecutor
    } finally {
        mainLock.unlock();
    }
    tryTerminate();
}
在做任何事之前都会调用{p> checkShutdownAccess ...

/**
 * If there is a security manager, makes sure caller has
 * permission to shut down threads in general (see shutdownPerm).
 * If this passes, additionally makes sure the caller is allowed
 * to interrupt each worker thread. This might not be true even if
 * first check passed, if the SecurityManager treats some threads
 * specially.
 */
private void checkShutdownAccess() {
    SecurityManager security = System.getSecurityManager();
    if (security != null) {
        security.checkPermission(shutdownPerm);
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            for (Worker w : workers)
                security.checkAccess(w.thread);
        } finally {
            mainLock.unlock();
        }
    }
}

如您所见,无条件地在安全管理器上调用checkPermission(shutdownPerm) .... shutdownPerm定义为......     private static final RuntimePermission shutdownPerm =         new RuntimePermission(“modifyThread”);

...据我所知,这完全没有意义,因为modifyThread意味着访问系统线程,并且 没有系统线程在这里玩,事实上,根本没有线程,因为我没有提交任何工作或预启动,即使有线程,他们也是我的线程,因为我传入了{{ 1}}。该规范没有说明神奇的死亡,除了涉及系统线程(它们不是),可能有一个ThreadFactory

基本上,为什么我不能删除检查系统线程访问权限的行?我认为没有安全隐含要求它。怎么没有其他人遇到这个问题?我在问题跟踪器上看到了一个帖子,他们通过将对SecurityException的调用更改为shutdownNow来“解决”此问题,显然,这并没有为他们解决问题。

2 个答案:

答案 0 :(得分:1)

这很简单:你不能在主线程组中做到这一点。它部分是为applet设计的。 从关机方法想法复制为什么? 如果这是一个问题,您可以自由使用PrivilegedAction来调用shutdown。请记住,Thread.interrupt()是无辜的,它也可能看起来throws SecurityException

要回答这个问题:只需确保您授予自己的代码权限,您就会感到高兴。或者“modifyThread”也可以自由授予,它主要由applet使用。

对于不受信任的代码:嗯,不受信任的代码甚至不应该处理其ThreadGroup之外的线程,因此提供API来创建ThreadPool,并允许关闭由调用者创建的。您可以根据呼叫者授予权限。

希望这有点帮助(问号的数量清楚地表明了绝望和最大的烦恼)

    /*
     * Conceptually, shutdown is just a matter of changing the
     * runState to SHUTDOWN, and then interrupting any worker
     * threads that might be blocked in getTask() to wake them up
     * so they can exit. Then, if there happen not to be any
     * threads or tasks, we can directly terminate pool via
     * tryTerminate.  Else, the last worker to leave the building
     * turns off the lights (in workerDone).
     *
     * But this is made more delicate because we must cooperate
     * with the security manager (if present), which may implement
     * policies that make more sense for operations on Threads
     * than they do for ThreadPools. This requires 3 steps:
     *
     * 1. Making sure caller has permission to shut down threads
     * in general (see shutdownPerm).
     *
     * 2. If (1) passes, making sure the caller is allowed to
     * modify each of our threads. This might not be true even if
     * first check passed, if the SecurityManager treats some
     * threads specially. If this check passes, then we can try
     * to set runState.
     *
     * 3. If both (1) and (2) pass, dealing with inconsistent
     * security managers that allow checkAccess but then throw a
     * SecurityException when interrupt() is invoked.  In this
     * third case, because we have already set runState, we can
     * only try to back out from the shutdown as cleanly as
     * possible. Some workers may have been killed but we remain
     * in non-shutdown state (which may entail tryTerminate from
     * workerDone starting a new worker to maintain liveness.)
     */

答案 1 :(得分:0)

听起来像是懒惰和/或安全的实现。它不是检查是否涉及其他线程,而是假设有些线程。最好抛出一个安全例外而不是留下潜在的安全漏洞。