Restrict permissions to threads which execute thir

2019-04-10 13:27发布

问题:

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")