Java SecurityManager with custom policy file does not work as expected

56 views Asked by At

I am trying to understand how SecurityManager works so I made example to test it. however I am getting exceptions

this is class file


public class FilePermissionChecker2 {
    public static void main(String[] args) {
        String filePath = "c:\\file.txt";
        Permission perm = new FilePermission(filePath, "read,write");
        PermissionCollection perms = perm.newPermissionCollection();

        perms.add(perm);

        boolean hasPermission = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
            @Override
            public Boolean run() {
                // Check file permissions here
                File file = new File(filePath);
                if (file.exists() && file.canRead() && file.canWrite()) {
                    return true;
                } else {
                    return false;
                }
            }
        }, new AccessControlContext(
                new ProtectionDomain[]{
                        new ProtectionDomain(null, perms)
                }
        ));

        if (hasPermission) {
            System.out.println("You have the necessary file permissions.");
        } else {
            System.out.println("You do not have the necessary file permissions.");
        }

    }
}

this is my custom policy file

grant {
    permission java.io.FilePermission "c:\\file.txt", "read, write";
};

and this is my VM options which I added in intellij as VM options parameter -Djava.security.manager -Djava.security.policy=...pathToPolicy...\policy\custom.policy

I would expect this code to work I tried different variations but I am still getting this exception Exception in thread "main" java.security.AccessControlException: access denied ("java.io.FilePermission" "c:\file.txt" "read")

does anyone have idea what is wrong?

  • I tried different combinations in custom policy
  • I tried different combinations in FilePermissions
  • I would expect that securityManager would check what permissions I have based on custom policy and FilePermission would add intersection of these permissions. which means if there is read and write in policy and read and write in FilePermission I would be able to read and write. but If there would be only read in FilePermission I would have only read permissions
0

There are 0 answers