Restrict permissions to threads which execute third party software

好久不见. 提交于 2019-12-06 05:11:17

问题


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?

Thanks


回答1:


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);
}
}

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();
}

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



来源:https://stackoverflow.com/questions/13516766/restrict-permissions-to-threads-which-execute-third-party-software

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!