Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
import java.security.Permissions;
import java.util.PropertyPermission;
import org.codehaus.janino.ScriptEvaluator;
import de.unkrig.commons.lang.security.Sandbox;

public class SandboxDemo {

    public static void
    main(String[] args) throws Exception {

        // Create a JANINO script evaluator. The example, however, will work as fine with ExpressionEvaluators,
        // ClassBodyEvaluators and SimpleCompilers - or with any class you do not trust, e.g. a third-party
        // library.
        ScriptEvaluator se = new ScriptEvaluator();

        // Compile a simple script which reads two system variables - 'foo' and 'bar'.
        se.cook(
            "System.getProperty(\"foo\");\n" +
            "System.getProperty(\"bar\");\n"
        );

        // Now we create a 'Permissions' object which permitsallows to read the system variable 'foo', and forbids
        // everything else.
        Permissions permissions = new Permissions();
        permissions.add(new PropertyPermission("foo", "read"));

        // Before we evaluate the script, we confine the permissions on all classes loaded through the
        // ScriptEvaluator's class loader. Each *Evaluator creates a new class loader exclusively for loading the
        // classes it generates.
        Sandbox.confine(se.getMethod().getDeclaringClass().getClassLoader(), permissions);

        // Finally we evaluate the script. Getting system property 'foo' will succeed, and getting 'bar' will
        // throw an InvocationTargetException caused by
        //    java.security.AccessControlException: access denied (java.util.PropertyPermission bar read)
        se// Et voila!
        se.evaluate(null);
    }
}

"de.unkrig.commons.lang.security.Sandbox" lives in is available on "de.unkrig.commons".