Java-Sandbox is a library for executing Java code with a limited set of permissions. It can be used to access only the set of classes and resources listed in the white list. It does not seem to be able to restrict access to individual methods. It uses a system with a custom class loader and to achieve this.
I have not used it, but it looks well thought out and well documented enough.
@waqas gave a very interesting answer explaining how this can be implemented independently. But itβs much safer to leave a critical and complex security code to experts.
Please note that the project has not been updated since 2013, and the creators describe it as "experimental." His homepage has disappeared, but the Source Forge record remains.
Sample code adapted from the project website:
SandboxService sandboxService = SandboxServiceImpl.getInstance(); // Configure context SandboxContext context = new SandboxContext(); context.addClassForApplicationLoader(getClass().getName()); context.addClassPermission(AccessType.PERMIT, "java.lang.System"); // Whithout this line we get a SandboxException when touching System.out context.addClassPermission(AccessType.PERMIT, "java.io.PrintStream"); String someValue = "Input value"; class TestEnvironment implements SandboxedEnvironment<String> { @Override public String execute() throws Exception { // This is untrusted code System.out.println(someValue); return "Output value"; } }; // Run code in sandbox. Pass arguments to generated constructor in TestEnvironment. SandboxedCallResult<String> result = sandboxService.runSandboxed(TestEnvironment.class, context, this, someValue); System.out.println(result.get());
Lii Nov 17 '13 at 21:13 2013-11-17 21:13
source share