是否可以在 Java 中对我的 Runnable 进行沙箱处理?给定一个 Runnable,我希望它内部的代码(以及它产生的任何线程)在沙箱中运行,只允许代码访问文件系统上的特定路径。一旦 Runnable 完成,线程应该回到它拥有的任何正常权限,而任何剩余的衍生线程仍将应用文件系统限制。
我想在运行时执行此操作。这意味着我想避免创建策略文件并将自定义参数传递给 JVM。到目前为止,我已经能够将沙盒应用于我的整个应用程序,但我还没有找到一种方法将其范围限定为仅在当前线程中运行的 Runnable ......
if (System.getSecurityManager() == null) {
System.setSecurityManager(new SecurityManager());
}
CodeSource nullSource = new CodeSource(null, (CodeSigner[]) null);
PermissionCollection perms = new Permissions();
perms.add(new FilePermission(path.toAbsolutePath().toString() + "/*", "read"));
ProtectionDomain domain = new ProtectionDomain(nullSource, perms);
AccessControlContext safeContext = new AccessControlContext(
new ProtectionDomain[]{domain});
AccessController.doPrivileged((PrivilegedAction) () -> {
try {
r.run();
} catch (Exception e) {
throw new IllegalStateException(e);
}
return null;
}, safeContext);