我该如何创建一个Java沙箱?

54

我希望我的应用能够运行其他人的代码,也就是插件。但是,我有什么选项可以让这个过程更加安全,以防止他们撰写恶意代码。我如何控制他们所能或不能做的事情?

我了解到JVM具有“内置沙盒”功能 - 这是什么,这是唯一的方法吗?是否有第三方Java库可以创建沙盒?

我有哪些选择?欢迎提供指南和例子的链接!

7个回答

27

19
  • 定义并注册自己的安全管理器可以限制代码的操作-请参阅Oracle文档中的SecurityManager

  • 此外,考虑创建一个单独的机制来加载代码-即您可以编写或实例化另一个类加载器以从特殊位置加载代码。您可能有一些公约来加载代码-例如从特殊目录或特殊格式的zip文件(如WAR文件和JAR文件)中加载。如果您正在编写类加载器,则需要做一些工作来获取要加载的代码。这意味着,如果您看到要拒绝的内容(或某些依赖项),可以简单地失败地加载代码。http://java.sun.com/javase/6/docs/api/java/lang/ClassLoader.html


7
请看Java沙箱项目,它可以轻松创建非常灵活的沙箱来运行不受信任的代码。

1
谢谢你发布那个库,它让我正在处理的事情变得更容易了。 - Brett Lempereur
该链接已失效。谷歌找到了这个,是同一个吗? - planetguy32
1
该项目可在SourceForge上找到:https://sourceforge.net/projects/dw-sandbox/ - Arno Mittelbach

4

对于AWT/Swing应用程序,您需要使用非标准的AppContext类,该类可能随时更改。因此,为了有效地运行插件代码,您需要启动另一个进程,并处理两个进程之间的通信(有点像Chrome)。插件进程将需要设置SecurityManagerClassLoader,以隔离插件代码并对插件类应用适当的ProtectionDomain


3
以下是关于如何使用SecurityManager解决问题的方法:

可以通过SecurityManager解决这个问题:

https://svn.code.sf.net/p/loggifier/code/trunk/de.unkrig.commons.lang/src/de/unkrig/commons/lang/security/Sandbox.java

package de.unkrig.commons.lang.security;

import java.security.AccessControlContext;
import java.security.Permission;
import java.security.Permissions;
import java.security.ProtectionDomain;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;

import de.unkrig.commons.nullanalysis.Nullable;

/**
 * This class establishes a security manager that confines the permissions for code executed through specific classes,
 * which may be specified by class, class name and/or class loader.
 * <p>
 * To 'execute through a class' means that the execution stack includes the class. E.g., if a method of class {@code A}
 * invokes a method of class {@code B}, which then invokes a method of class {@code C}, and all three classes were
 * previously {@link #confine(Class, Permissions) confined}, then for all actions that are executed by class {@code C}
 * the <i>intersection</i> of the three {@link Permissions} apply.
 * <p>
 * Once the permissions for a class, class name or class loader are confined, they cannot be changed; this prevents any
 * attempts (e.g. of the confined class itself) to release the confinement.
 * <p>
 * Code example:
 * <pre>
 *  Runnable unprivileged = new Runnable() {
 *      public void run() {
 *          System.getProperty("user.dir");
 *      }
 *  };
 *
 *  // Run without confinement.
 *  unprivileged.run(); // Works fine.
 *
 *  // Set the most strict permissions.
 *  Sandbox.confine(unprivileged.getClass(), new Permissions());
 *  unprivileged.run(); // Throws a SecurityException.
 *
 *  // Attempt to change the permissions.
 *  {
 *      Permissions permissions = new Permissions();
 *      permissions.add(new AllPermission());
 *      Sandbox.confine(unprivileged.getClass(), permissions); // Throws a SecurityException.
 *  }
 *  unprivileged.run();
 * </pre>
 */
public final
class Sandbox {

    private Sandbox() {}

    private static final Map<Class<?>, AccessControlContext>
    CHECKED_CLASSES = Collections.synchronizedMap(new WeakHashMap<Class<?>, AccessControlContext>());

    private static final Map<String, AccessControlContext>
    CHECKED_CLASS_NAMES = Collections.synchronizedMap(new HashMap<String, AccessControlContext>());

    private static final Map<ClassLoader, AccessControlContext>
    CHECKED_CLASS_LOADERS = Collections.synchronizedMap(new WeakHashMap<ClassLoader, AccessControlContext>());

    static {

        // Install our custom security manager.
        if (System.getSecurityManager() != null) {
            throw new ExceptionInInitializerError("There's already a security manager set");
        }
        System.setSecurityManager(new SecurityManager() {

            @Override public void
            checkPermission(@Nullable Permission perm) {
                assert perm != null;

                for (Class<?> clasS : this.getClassContext()) {

                    // Check if an ACC was set for the class.
                    {
                        AccessControlContext acc = Sandbox.CHECKED_CLASSES.get(clasS);
                        if (acc != null) acc.checkPermission(perm);
                    }

                    // Check if an ACC was set for the class name.
                    {
                        AccessControlContext acc = Sandbox.CHECKED_CLASS_NAMES.get(clasS.getName());
                        if (acc != null) acc.checkPermission(perm);
                    }

                    // Check if an ACC was set for the class loader.
                    {
                        AccessControlContext acc = Sandbox.CHECKED_CLASS_LOADERS.get(clasS.getClassLoader());
                        if (acc != null) acc.checkPermission(perm);
                    }
                }
            }
        });
    }

    // --------------------------

    /**
     * All future actions that are executed through the given {@code clasS} will be checked against the given {@code
     * accessControlContext}.
     *
     * @throws SecurityException Permissions are already confined for the {@code clasS}
     */
    public static void
    confine(Class<?> clasS, AccessControlContext accessControlContext) {

        if (Sandbox.CHECKED_CLASSES.containsKey(clasS)) {
            throw new SecurityException("Attempt to change the access control context for '" + clasS + "'");
        }

        Sandbox.CHECKED_CLASSES.put(clasS, accessControlContext);
    }

    /**
     * All future actions that are executed through the given {@code clasS} will be checked against the given {@code
     * protectionDomain}.
     *
     * @throws SecurityException Permissions are already confined for the {@code clasS}
     */
    public static void
    confine(Class<?> clasS, ProtectionDomain protectionDomain) {
        Sandbox.confine(
            clasS,
            new AccessControlContext(new ProtectionDomain[] { protectionDomain })
        );
    }

    /**
     * All future actions that are executed through the given {@code clasS} will be checked against the given {@code
     * permissions}.
     *
     * @throws SecurityException Permissions are already confined for the {@code clasS}
     */
    public static void
    confine(Class<?> clasS, Permissions permissions) {
        Sandbox.confine(clasS, new ProtectionDomain(null, permissions));
    }

    // Code for 'CHECKED_CLASS_NAMES' and 'CHECKED_CLASS_LOADERS' omitted here.

}

我已经在这里发布了代码: http://commons.unkrig.de/commons-lang/apidocs/de/unkrig/commons/lang/security/Sandbox.html 只需将此Maven模块添加到依赖项中即可: http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22de.unkrig.commons%22%20AND%20a%3A%22commons-lang%22 - Arno Unkrig

0

这个问题的讨论启发了我开始自己的沙盒项目。

https://github.com/Black-Mantha/sandbox

在编程中,我遇到了一个重要的安全问题:“如何允许沙盒外的代码绕过SecurityManager?”

我将沙盒代码放入其自己的ThreadGroup中,并始终在该组外授予权限。如果您需要在该组中运行特权代码(例如,在回调中),可以使用ThreadLocal仅为该线程设置标志。类加载器将防止沙盒访问ThreadLocal。此外,如果您这样做,需要禁止使用finalizers,因为它们在ThreadGroup之外的专用线程中运行。


0
在深入研究Java安全API一天后,我发现了一个惊人简单的解决方案,可以在权限限制下的沙盒中执行不受信任的代码:

https://github.com/janino-compiler/janino/blob/master/commons-compiler/src/main/java/org/codehaus/commons/compiler/Sandbox.java

这是(简化后的)源代码:

package org.codehaus.commons.compiler;

import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.Permission;
import java.security.PermissionCollection;
import java.security.Policy;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.security.ProtectionDomain;

public final
class Sandbox {

    static {

        if (System.getSecurityManager() == null) {

            // Before installing the security manager, configure a decent ("positive") policy.
           Policy.setPolicy(new Policy() {

                @Override public boolean
                implies(ProtectionDomain domain, Permission permission) { return true; }
            });

            System.setSecurityManager(new SecurityManager());
        }
    }

    private final AccessControlContext accessControlContext;

    /**
     * @param permissions Will be applied on later calls to {@link #confine(PrivilegedAction)} and {@link
     *                    #confine(PrivilegedExceptionAction)}
     */
    public
    Sandbox(PermissionCollection permissions) {
        this.accessControlContext = new AccessControlContext(new ProtectionDomain[] {
            new ProtectionDomain(null, permissions)
        });
    }

    /**
     * Runs the given <var>action</var>, confined by the permissions configured through the {@link
     * #Sandbox(PermissionCollection) constructor}.
     *
     * @return The value returned by the <var>action</var>
     */
    public <R> R
    confine(PrivilegedAction<R> action) {
        return AccessController.doPrivileged(action, this.accessControlContext);
    }

    public <R> R
    confine(PrivilegedExceptionAction<R> action) throws Exception {
        try {
            return AccessController.doPrivileged(action, this.accessControlContext);
        } catch (PrivilegedActionException pae) {
            throw pae.getException();
        }
    }
}

2
不错,但要注意JEP411(https://openjdk.java.net/jeps/411),它遗憾地弃用了安全管理器。像Apache River(曾经的神奇Jini)这样的项目将在绕过此JEP方面遇到深刻的问题。 - apr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接