How do I create a Java sandbox?
I want to make my application to run other people's code, aka plugins. However, what options do I have to make this secure so they don't write malicious code. How do I control what they can or can not do?
I have stumbled around that JVM has a "built in sandbox" feature - what is it and is this the only way? Are there third-party Java libraries for making a sandbox?
What options do I have? Links to guides and examples is appreciated!
You are looking for a security manager. You can restrict the permissions of an application by specifying a policy.
Defining and registering your own security manager will allow you to limit what the code does - see oracle documentation for SecurityManager.
Also, consider creating a separate mechanism for loading the code - i.e. you could write or instantiate another Classloader to load the code from a special place. You might have a convention for loading the code - for example from a special directory or from a specially formatted zip file (as WAR files and JAR files). If you're writing a classloader it puts you in the position of having to do work to get the code loaded. This means that if you see something (or some dependency) you want to reject you can simply fail to load the code. http://java.sun.com/javase/6/docs/api/java/lang/ClassLoader.html
Have a look at the java-sandbox project which allows to easily create very flexible sandboxes to run untrusted code.
For an AWT/Swing application you need to use non-standard AppContext
class, which could change at any time. So, to be effective you would need to start another process to run plug-in code, and deal with communication between the two (a little like Chrome). The plug-in process will need a SecurityManager
set and a ClassLoader
to both isolate the plug-in code and apply an appropriate ProtectionDomain
to plug-in classes.