Class Sandbox

java.lang.Object
org.codehaus.commons.compiler.Sandbox

@Deprecated public final class Sandbox extends Object
Deprecated.
The security manager, on which this class relies, cannot be used on Java 24 and later (and on Java 18 through 23 only with -Djava.security.manager=allow). Use a SandboxPolicy (see ICookable.setSandboxPolicy(org.codehaus.commons.compiler.sandbox.SandboxPolicy)) and a SandboxExecutor instead, which work on all JREs from Java 8 on
Executes a PrivilegedAction or PrivilegedExceptionAction in a context with restricted permissions. This is useful for executing "untrusted" code, e.g. user-provided expressions or scripts that were compiled with JANINO.

Code example:

    Permissions noPermissions = new Permissions();
    Sandbox sandbox = new Sandbox(noPermissions);
    sandbox.confine(new PrivilegedExceptionAction<Object>() {
        @Override public Object run() throws Exception { new java.io.File("xxx").delete(); return null; }
    });

The sandbox relies on the security manager, which is not available on all JVMs:

  • Java 8 through 17: Supported.
  • Java 18 through 23: Supported only if the JVM was started with -Djava.security.manager=allow, or if a security manager is already installed.
  • Java 24 and later: Not supported (the security manager was permanently disabled).

Use isSupported() to check whether the sandbox can be used on the running JVM. If it cannot, the constructor throws an UnsupportedOperationException.

Notice: Code that is confined by the sandbox can call AccessController.doPrivileged() itself, and then runs with the permissions of its own protection domain. By default, JANINO defines the generated classes with the protection domain of the compiler, and the policy that this class installs grants all permissions to that domain, so that the confined code can escape from the sandbox. To prevent that, define the generated classes with the same permissions as the sandbox, through a protection domain with static permissions:

    Sandbox sandbox = new Sandbox(permissions);
    scriptEvaluator.setProtectionDomain(new ProtectionDomain(null, permissions));
    scriptEvaluator.cook(script);
    sandbox.confine(...);

See ICookable.setProtectionDomain(ProtectionDomain), and, for the AbstractJavaSourceClassLoader, AbstractJavaSourceClassLoader.setProtectionDomainFactory(AbstractJavaSourceClassLoader.ProtectionDomainFactory). Alternatively, a SandboxPolicy rejects such code already at compile time.

See Also: