wrschneider
wrschneider

Reputation: 18780

Execute a method in Java with restricted permissions

Is there any way I can use AccessController.doPrivileged with a new AccessControlContext to restrict access to classes/methods? I'd like to have a subroutine that can call untrusted code without access to touch the file system or open sockets.

The specific use case is, allowing end users to provide fragments of code or scripts (for example, Javascript or Groovy) that can execute with limited permissions.

What I'm looking for is something like a normal security policy file, scoped to the user-provided code rather than the whole JVM.

Upvotes: 10

Views: 1192

Answers (3)

Lii
Lii

Reputation: 12132

The Java-Sandbox is a tool for exactly this. It can be used to allow access to only a set of white-listed classes and resources for restricted methods. It uses a system with a custom class loader and security manager to achieve this. No byte code manipulation or similar tricks are necessary.

I have not used it but it looks well designed and reasonably well documented.

Example code from its web site:

class Untrusted extends SandboxedEnvironment<Object>() {
    @Override
    public Object execute() {
       /* untrusted code */
       return null;
    }
};

service.runSandboxed(Untrusted.class, context);

Upvotes: 1

Dino Tw
Dino Tw

Reputation: 3321

If this is something you are looking for

@PreAuthorize("hasRole('ROLE_USER')")
public void create(Contact contact);

You might want to take a look on Spring Security, Expression-Based Access Control

Upvotes: 0

cdkrot
cdkrot

Reputation: 279

I don't now about AccessController way. But possibly you can control the situation using the following scheme. You will need to have multiple classloaders: first will load classes as-is. Second (or in ideal by the count of untrusted code sources) which will transform classes to patched or provide instead of normal classes its special patched edition. And last for System Classloader which will actually do routine.

Also don't forget to protect Classloader.getSystemClassLoader. And for transforming objects you may use java reflection API or objectweb asm library.

Upvotes: 1

Related Questions