Question summary: How do I modify the code below so that untrusted, dynamically-loaded code runs in a security sandbox while the rest of the application remains unrestricted? Why doesn't URLClassLoader just handle it like it says it does?
EDIT: Updated to respond to Ani B.
EDIT 2: Added updated PluginSecurityManager.
My application has a plug-in mechanism where a third party can provide a JAR containing a class which implements a particular interface. Using URLClassLoader, I am able to load that class and instantiate it, no problem. Because the code is potentially untrusted, I need to prevent it from misbehaving. For example, I run plug-in code in a separate thread so that I can kill it if it goes into an infinite loop or just takes too long. But trying to set a security sandbox for them so that they can't do things like make network connections or access files on the hard drive is making me positively batty. My efforts always result in either having no effect on the plug-in (it has the same permissions as the application) or also restricting the application. I want the main application code to be able to do pretty much anything it wants, but the plug-in code to be locked down.
Documentation and online resources on the subject are complex, confusing and contradictory. I've read in various places (such as this question) that I need to provide a custom SecurityManager, but when I try it I run into problems because the JVM lazy-loads the classes in the JAR. So I can instantiate it just fine, but if I call a method on the loaded object which instantiates another class from the same JAR, it blows up because it's denied the right to read from the JAR.
Theoretically, I could put a check on FilePermission in my SecurityManager to see if it's trying to load out of its own JAR. That's fine, but the URLClassLoader documentation says: "The classes that are loaded are by default granted permission only to access the URLs specified when the URLClassLoader was created." So why do I even need a custom SecurityManager? Shouldn't URLClassLoader just handle this? Why doesn't it?
Here's a simplified example that reproduces the problem:
Main application (trusted)
PluginTest.java
package test.app;
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import test.api.Plugin;
public class PluginTest {
public static void pluginTest(String pathToJar) {
try {
File file = new File(pathToJar);
URL url = file.toURI().toURL();
URLClassLoader cl = new URLClassLoader(new java.net.URL[] { url });
Class<?> clazz = cl.loadClass("test.plugin.MyPlugin");
final Plugin plugin = (Plugin) clazz.newInstance();
PluginThread thread = new PluginThread(new Runnable() {
@Override
public void run() {
plugin.go();
}
});
thread.start();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Plugin.java
package test.api;
public interface Plugin {
public void go();
}
PluginSecurityManager.java
package test.app;
public class PluginSecurityManager extends SecurityManager {
private boolean _sandboxed;
@Override
public void checkPermission(Permission perm) {
check(perm);
}
@Override
public void checkPermission(Permission perm, Object context) {
check(perm);
}
private void check(Permission perm) {
if (!_sandboxed) {
return;
}
// I *could* check FilePermission here, but why doesn't
// URLClassLoader handle it like it says it does?
throw new SecurityException("Permission denied");
}
void enableSandbox() {
_sandboxed = true;
}
void disableSandbox() {
_sandboxed = false;
}
}
PluginThread.java
package test.app;
class PluginThread extends Thread {
PluginThread(Runnable target) {
super(target);
}
@Override
public void run() {
SecurityManager old = System.getSecurityManager();
PluginSecurityManager psm = new PluginSecurityManager();
System.setSecurityManager(psm);
psm.enableSandbox();
super.run();
psm.disableSandbox();
System.setSecurityManager(old);
}
}
Plugin JAR (untrusted)
MyPlugin.java
package test.plugin;
public MyPlugin implements Plugin {
@Override
public void go() {
new AnotherClassInTheSamePlugin(); // ClassNotFoundException with a SecurityManager
doSomethingDangerous(); // permitted without a SecurityManager
}
private void doSomethingDangerous() {
// use your imagination
}
}
UPDATE: I changed it so that just before the plugin code is about to run, it notifies the PluginSecurityManager so that it will know what class source it's working with. Then it will only allow file accesses on files under that class source path. This also has the nice advantage that I can just set the security manager once at the beginning of my application, and just update it when I enter and leave plugin code.
This pretty much solves the problem, but doesn't answer my other question: Why doesn't URLClassLoader handle this for me like it says it does? I'll leave this question open for a while longer to see if anyone has an answer to that question. If so, that person will get the accepted answer. Otherwise, I'll award it to Ani B. on the presumption that the URLClassLoader documentation lies and that his advice to make a custom SecurityManager is correct.
The PluginThread will have to set the classSource property on the PluginSecurityManager, which is the path to the class files. PluginSecurityManager now looks something like this:
package test.app;
public class PluginSecurityManager extends SecurityManager {
private String _classSource;
@Override
public void checkPermission(Permission perm) {
check(perm);
}
@Override
public void checkPermission(Permission perm, Object context) {
check(perm);
}
private void check(Permission perm) {
if (_classSource == null) {
// Not running plugin code
return;
}
if (perm instanceof FilePermission) {
// Is the request inside the class source?
String path = perm.getName();
boolean inClassSource = path.startsWith(_classSource);
// Is the request for read-only access?
boolean readOnly = "read".equals(perm.getActions());
if (inClassSource && readOnly) {
return;
}
}
throw new SecurityException("Permission denied: " + perm);
}
void setClassSource(String classSource) {
_classSource = classSource;
}
}