Skip to content

Groovy Shell Sandboxing Best Practices

I am trying to set up a Groovy Shell sandbox that can execute untrusted code. These untrusted codes are provided by the end users (developers) as behaviour configurations, e.g. how to determine if a person is high net worth. So, they really are part of the main program. I need to make sure that I am not vulnerable to any bad code [e.g. infinite loop]/hacks.

I understand that there are two things at play here:

  1. The Java VM that provides the runtime.
  2. The Groovy Shell that interprets and executes the code.

Are there best practices to sandbox a Groovy Shell?



I ended up creating a Policy file. Something like this:

grant codeBase "file:/your jar file" {

grant codeBase "file:/groovy/shell" {

grant codeBase "file:/groovy/script" {

When Groovy is executed in interpreted mode, the codeBase is either file:/groovy/shell or file:/groovy/script. You can grant specific permission(s) for either context. These permissions (or lack thereof) are independent to what you give to your main program.

In addition to the policy file, there are many other considerations too.

  1. What do you put into the evaluation context? If you put a 3rd party library, they may not even have the properly permission check in place.

  2. Some System calls, say System.out.println() doesn’t have permission check either. So, maybe you also need a source code checker (Jenkins does that).

  3. To limit CPU, you may need to run the Groovy script in a separate thread.

  4. You probably want to limit what a Groovy script can import too. This can be achieved with a Groovy ImportCustomizer.

I wrote an article: Secure Groovy Script Execution in a Sandbox to summarize my findings. I hope it will help others too.