javasandbox

Create java sandbox based on security policies


I need to create environment to run potentially untrusted code. Program allowed to connect to preconfigured address:port and nothing else (even read the system time). I have compiled the class whitelist. I'd searched similar questions, but found only template that based on SecurityManager which AFAIK is deprecated. Can anybody give me a simple sample how to run code in sandbox based on security policies and AccessController?


Solution

  • IMPORTANT — since Java 17 policy files and security manager have been deprecated and marked for removal. Here is a blog post explaining how to handle sanboxing post security manager.


    As far as I know it's still SecurityManager that runs the security checks. But it seems to delegate to the AccessController nowadays.

    First you'll need to switch on the security manager:

    -Djava.security.manager

    If you omit this argument there'll be no sandbox whatsoever.

    Second you'll need to tell where to find the policy file:

    -Djava.security.policy=

    This will add your permissions to the ones already defined in your java home. The original sandbox rules in .../jre/lib/security/java.policy. However, if you want your policy to be the only one you'll need to use a double "=". This way you control completely what's allowed.

    For example:

    -Djava.security.policy==

    I would advise you to use the "policytool" shipped with the Java. It's fairly basic but it helps you to write quickly a policy file with the correct syntax.

    I hope this helps...