views:

89

answers:

2

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;
    }
}
+2  A: 

Implementing a SecurityManager is probably the best way to go. You would have to override checkPermission. That method would look at the Permission object passed to it, and determine if a certain action is dangerous. This way you can allow some permissions and disallow other permissions.

Can you describe the custom SecurityManager you used?

Ani B
You are right to ask to see the SecurityManager; I accidentally left it (and the thread class that applies it) out of the question. I've added them.
Robert J. Walker
While I *could* make a SecurityManager that prohibits all operations except reading out of the same JAR, the URLClassLoader documentation seems to indicate that I shouldn't have to. I'd like to know why URLClassLoader doesn't seem to be working as described. I've added those details to the question, as well.
Robert J. Walker
I wish I could mark two answers correct. Woot4Moo explained why it wasn't working, and you gave a workaround. They both deserve answer credit. In any case, I voted you up, at least.
Robert J. Walker
Thanks for giving credit to both of us.
Ani B
+2  A: 

From the docs:
The AccessControlContext of the thread that created the instance of URLClassLoader will be used when subsequently loading classes and resources.

The classes that are loaded are by default granted permission only to access the URLs specified when the URLClassLoader was created.

The URLClassLoader is doing exactly as its says, the AccessControlContext is what you need to be looking at. Basically the thread that is being referenced in AccessControlContext does not have permissions to do what you think it does.

Woot4Moo
You are right; the AccessControlContext from the thread that created the class loader permits all operations, so the URLClassLoader will, too. The latter statement from the docs seems to contradict the former, so I'm still feeling like there's something I'm not understanding, but for answering the "Why?" question, I'll credit you with the answer.
Robert J. Walker
What resources cant AccessControlContext access that the URLClassLoader can access?
Woot4Moo