限制对执行第三方软件的线程的权限

限制对执行第三方软件的线程的权限

本文介绍了限制对执行第三方软件的线程的权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个基于eclipse的应用程序,能够执行第三方组件(不是eclipse-plugin)。

I'm developing an eclipse based application capable to execute third party component (not eclipse-plugin).

每个组件都有一个自定义描述符,其中列出了权限(有相应的动机)。通过这种方式,最终用户可以决定是否执行它。

Each component has a custom descriptor, where are listed permissions (with correspondent motivation). In this way final user can decide if execute it or not.

组件在分离的线程中执行。如何根据描述符限制对这些线程的权限,而不限制整个应用程序?

Components are executed in separated threads. How can I restrict permissions to these threads according with the descriptor, without restrict entire application?

谢谢

推荐答案

首先,您应该打开安全管理器。然后使用所需权限创建。 (我的示例中没有权限。)最后在方法。

First of all, you should turn on the Security Manager. Then create an AccessControlContext with the desired permissions. (No permissions in my example.) Finally execute the third party code in the AccessController.doPrivileged(...) method.

这个是一个非常简单的解决方案:

This is a very simple solution:

public abstract class SafeRunnable implements Runnable {

public abstract void protectedRun();

@Override
public final void run() {
    CodeSource nullSource = new CodeSource(null, (CodeSigner[]) null);
    PermissionCollection noPerms = new Permissions();
    ProtectionDomain domain = new ProtectionDomain(nullSource, noPerms);
    AccessControlContext safeContext = new AccessControlContext(
            new ProtectionDomain[] { domain });

    AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            protectedRun();
            return null;
        }
    }, safeContext);
}
}

测试SafeRunnable:

Testing the SafeRunnable:

public static void main(String args[]) throws Exception {
    // Turn on the security management
    SecurityManager sm = new SecurityManager();
    System.setSecurityManager(sm);

    new Thread(new SafeRunnable() {
        public void protectedRun() {
            // friendly operation:
            System.out.println("Hello");
        }
    }).start();

    new Thread(new SafeRunnable() {
        public void protectedRun() {
            // malicious operation
            System.exit(0);
        }
    }).start();
}

第一个线程打印Hello,第二个抛出 AccessControlException:访问被拒绝(java.lang.RuntimePermissionexitVM.0)

First thread prints Hello, the second throws AccessControlException: access denied ("java.lang.RuntimePermission" "exitVM.0")

这篇关于限制对执行第三方软件的线程的权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 21:59