Categories
Snippets

Sandboxing

Every now and then somebody pops up and wants to know how sandboxing is done in Java. So, a couple of years ago I sat down and spent two weeks figuring out how it actually works.

Basically, you need to set a Policy and a SecurityManager. The Policy is responsible for assigning (or not assigning) Permissions to a CodeSource.

if (!codeSource.getLocation().toString().endsWith("/rogue.jar")) {
  p.add(new AllPermission());
}

This simple example uses the URL associated with a code source to determine whether the code source should have a certain set of permissions or not. For the policy to be in effect you have to set a security manager because by default Java applications do not have one.

Policy.setPolicy(new PluginPolicy());
System.setSecurityManager(new SecurityManager());

The source code for a complete example can be downloaded from pterodactylus.net/…/security-test.tar.bz2. It contains five source files; one application (Main.java), one plugin interface, one plugin policy, and two plugin implementations which are packed into different JAR files using the supplied Ant build file. The authorized JAR is allowed to access the system properties, the rogue JAR is not.

One reply on “Sandboxing”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.