Java security: Sandboxing plugins loaded via URLClassLoader

后端 未结 3 849
遥遥无期
遥遥无期 2020-12-02 13:36

Question summary: How do I modify the code below so that untrusted, dynamically-loaded code runs in a security sandbox while the rest of the application remains unrestricte

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-02 13:45

    I use the following approach while running some Groovy script within an application. I obviously want to prevent the script from running (intentionally or unintentionally) a System.exit

    I install a java SecurityManager in the usual way:

    -Djava.security.manager -Djava.security.policy=
    

    In the I give my application all permissions (I do fully trust my application), i.e.:

    grant {
        permission java.security.AllPermission;
    };
    

    I limit the capabilities in the part where the Groovy script is run:

    list = AccessController.doPrivileged(new PrivilegedExceptionAction> () {
        public List run() throws Exception {
            return groovyToExecute.someFunction();
        }
    }, allowedPermissionsAcc);
    

    The allowedPermissionsAcc doesn't change and therefore I create them in a static block

    private static final AccessControlContext allowedPermissionsAcc; 
    static {    // initialization of the allowed permissions
        PermissionCollection allowedPermissions = new Permissions();
        allowedPermissions.add(new RuntimePermission("accessDeclaredMembers"));
        // ...  ...
    
        allowedPermissionsAcc = new AccessControlContext(new ProtectionDomain[] {
            new ProtectionDomain(null, allowedPermissions)});
    }
    

    Now the tricky part is to find the right permissions.

    If you want to allow access to certain libraries, you will quickly realize that they have not been written with a Security Manager in mind and don't handle one very gracefully, and finding out which permissions they need can be quite tricky. You will run into additional problems if you want to run UnitTests through the Maven Surefire plugin, or run on different platforms, like Linux/Windows, since the behavior can vary :-(. But those issues are another topic

提交回复
热议问题