javajava-securitysecuritymanager

Enable the Java SecurityManager with AllPermission


I'm trying to get myself familiar with the SecurityManager but even this simple scenario fails. When I run the following from inside my IDE or from command line I get the following exception;

access denied ("java.util.PropertyPermission" "java.home" "read")

I thought I allowed everything with this code:

Policy.setPolicy(new Policy() {

    @Override
    public PermissionCollection getPermissions(CodeSource codesource) {
        Permissions perm = new Permissions();
        perm.add(new AllPermission());
        return perm;
    }
});
System.setSecurityManager(new SecurityManager());
System.out.println(System.getProperty("java.home"));

Has this something to-do with the derived policy from the JVM? How can I cleanly setPolicy()?

The same misunderstanding seems to happen for the following code:

System.setSecurityManager(new SecurityManager());
final Permissions allPermission = new Permissions();
allPermission.add(new AllPermission());
AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
    System.out.println(System.getProperty("java.home"));
    return null;
}, new AccessControlContext(new ProtectionDomain[]{new ProtectionDomain(null, allPermission)}));

Update: the second case is understandable as the provided permission is only a further restriction: (javadoc) The action is performed with the intersection of the permissions possessed by the caller's protection domain, and those possessed by the domains represented by the specified AccessControlContext


Solution

  • I was able to recreate your case with an extra Policy.getPolicy() before the Policy.setPolicy() call, the reason why it affects the behaviour is that with the get policy call, you trigger a default policy creation, and permissions from java.policy are set, but without a setSecurityManager() they are not activated, that is the reason when you do a custom AllPermission policy set, you still get a "java.util.PropertyPermission" "java.home" "read" issue, for many of such default policies are not overridden with the set policy. Very confusing structure indeed.

    Policy.getPolicy();
    Policy.setPolicy(policyWithAllPermission);
    System.setSecurityManager(new SecurityManager());
    System.out.println(System.getProperty("java.home"));
    // results in 'access denied ("java.util.PropertyPermission" "java.home" "read")'
    

    But if you use the following custom policy;

    Policy allPermissionPolicy = new Policy() {
    
        @Override
        public boolean implies(ProtectionDomain domain, Permission permission) {
            return true;
        }
    };
    

    It overrides all permission definitions, and lets all actions through, a possible fix for this confusion.