Java security: Sandboxing plugins loaded via URLClassLoader
Asked Answered
D

3

34

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;
    }
}
Disease answered 16/10, 2010 at 3:28 Comment(4)
This is a related question, it might help: #502718 :)Larkspur
Yes, I in fact linked to that question in my own. The problem is, the solution presented there is incomplete. It doesn't fully implement the SecurityManager, which is the critical part of this question. It also doesn't explain why you even need one in the first place, seeing as the URLClassLoader claims to handle this for you by default.Disease
You know the untrusted code could run code in another thread after run returns?Midcourse
I have a very similar question and i'm trying to come to grips with this solution. However, isn't there a big problem in the PluginThread.run method, that is changes the security manager for the whole System. If this is running using threads (lets say, two people uploading plugins at once), does this leave it open to concurrency problems? Thread 2 starts, sets the new security manager, just as thread 1 finishes and sets it to the "old" one.Reproval
Q
8

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.

Quicksilver answered 19/10, 2010 at 17:46 Comment(2)
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.Disease
What resources cant AccessControlContext access that the URLClassLoader can access?Quicksilver
S
7

I use the following approach while running some Groovy script within an application. I obviously want to prevent the script from running (intentionally or unintentionally) a System.exit

I install a java SecurityManager in the usual way:

-Djava.security.manager -Djava.security.policy=<policy file>

In the <policy file> I give my application all permissions (I do fully trust my application), i.e.:

grant {
    permission java.security.AllPermission;
};

I limit the capabilities in the part where the Groovy script is run:

list = AccessController.doPrivileged(new PrivilegedExceptionAction<List<Stuff>> () {
    public List<Stuff> run() throws Exception {
        return groovyToExecute.someFunction();
    }
}, allowedPermissionsAcc);

The allowedPermissionsAcc doesn't change and therefore I create them in a static block

private static final AccessControlContext allowedPermissionsAcc; 
static {    // initialization of the allowed permissions
    PermissionCollection allowedPermissions = new Permissions();
    allowedPermissions.add(new RuntimePermission("accessDeclaredMembers"));
    // ... <many more permissions here> ...

    allowedPermissionsAcc = new AccessControlContext(new ProtectionDomain[] {
        new ProtectionDomain(null, allowedPermissions)});
}

Now the tricky part is to find the right permissions.

If you want to allow access to certain libraries, you will quickly realize that they have not been written with a Security Manager in mind and don't handle one very gracefully, and finding out which permissions they need can be quite tricky. You will run into additional problems if you want to run UnitTests through the Maven Surefire plugin, or run on different platforms, like Linux/Windows, since the behavior can vary :-(. But those issues are another topic

Sanbenito answered 24/8, 2011 at 7:58 Comment(3)
I'm aware this is a late reply on your topic... But this initially helped me a lot, until I figured out that my code can still create new threads and then the AccessControlContext does not apply anymore, have you figured a way around that?Lorenlorena
If you call groovy (tested it with Java) code that calls AccessController.doPrivileged(...) to run it's malicious code, then the malicious code still gets executed.Lorenlorena
You gonna have to make sure you limit access to those functions, that's the second code block. Creating a fully Sandboxed solution is not easy :-(Sanbenito
H
5

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?

Hedger answered 18/10, 2010 at 1:48 Comment(3)
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.Disease
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.Disease
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.Disease

© 2022 - 2024 — McMap. All rights reserved.