2012-11-22 36 views
4

我正在開發一個基於eclipse的應用程序,能夠執行第三方組件(而不是eclipse-plugin)。限制執行第三方軟件的線程的權限

每個組件都有一個自定義描述符,其中列出了許可權限(具有相應的動機)。這樣最終用戶可以決定是否執行它。

組件在分離的線程中執行。如何根據描述符限制對這些線程的權限,而不限制整個應用程序?

謝謝

回答

2

首先,你應該打開安全管理器。然後用所需的權限創建一個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(); 
} 

第一個線程打印您好,第二投AccessControlException: access denied ("java.lang.RuntimePermission" "exitVM.0")

+0

感謝您的答覆。從你的例子開始,我嘗試在noPerms中添加一個權限爲'noPerms.add(new FilePermission(「/」,「read」));'聲明,但是如果我嘗試列出目錄文件,權限不會受到影響。 –