限制对执行第三方软件的线程的权限
我正在开发一个基于eclipse的应用程序,能够执行第三方组件(不是eclipse-plugin)。
每个组件都有一个自定义描述符,其中列出了权限(具有相应的动机)。 通过这种方式,最终用户可以决定是否执行它。
组件在分离的线程中执行。 如何根据描述符限制对这些线程的权限,而不限制整个应用程序?
谢谢
首先,您应该打开安全管理器。 然后创建具有所需权限的AccessControlContext 。 (在我的示例中没有权限。)最后在AccessController.doPrivileged(…)方法中执行第三方代码。
这是一个非常简单的解决方案:
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:
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: access denied ("java.lang.RuntimePermission" "exitVM.0")