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