Limiting file access in Java

后端 未结 1 503
一个人的身影
一个人的身影 2020-12-24 02:56

Problem:
In my Java application (not an applet) I wish to limit certain file operations to all classes except a list/group/package of classes that shoul

相关标签:
1条回答
  • 2020-12-24 03:00

    Here is how you can do it using a policy file.

    Create a Java file that can act with privileges:

    package egPriv;
    
    import java.io.FileReader;
    import java.io.IOException;
    import java.io.Reader;
    import java.security.AccessController;
    import java.security.PrivilegedActionException;
    import java.security.PrivilegedExceptionAction;
    
    public class PrivCat {
        /** Cat a file with no privileges */
        public void cat(String file) throws IOException {
            cat(new FileReader(file));
        }
    
        private void cat(Reader r) throws IOException {
            int c;
            while( (c = r.read()) != -1 ) {
                System.out.print((char) c);
            }
            r.close();
        }
    
        /** Cat a file WITH privileges */
        public void catPriv(final String file) throws IOException {
            Reader r;
            try {
                r = AccessController.doPrivileged(new PrivilegedExceptionAction<Reader>() {
                    public Reader run() throws IOException {
                        return new FileReader(file);
                    }
                });
            } catch (PrivilegedActionException e) {
                throw (IOException) e.getCause();
            }
            cat(r);
        }
    }
    

    Create a regular file for demonstating

    package eg;
    
    import egPriv.PrivCat;
    
    import java.io.IOException;
    
    public class Cat extends PrivCat {
        public static void main(String[] args) throws IOException {
            Cat eg2 = new Cat();
            System.out.println("Processing with privilege:");
            eg2.catPriv(args[0]);
    
            System.out.println("Processing normally");
            eg2.cat(args[0]);
        }
    }
    

    Create sample.policy file:

    /* anyone can read write and execute within current working dir */
    grant {
      permission java.io.FilePermission "${user.dir}", "read,write,execute";
    };
    
    grant {
      permission java.io.FilePermission "${user.dir}/*", "read,write,execute,delete";
    };
    
    
    /* Only code from this jar can work outside of CWD */
    grant codebase "file:egPriv.jar" {
      permission java.io.FilePermission "<<ALL FILES>>", "read,write,execute,delete";
    };
    

    Compile and then Test:

    jar cvf egPriv.jar egPriv
    jar cvf eg.jar eg
    
    
    echo 'Restricted' > ..\file.txt
    java -cp eg.jar;egPriv.jar -Djava.security.manager -Djava.security.policy=sample.policy  eg.Cat ..\file.txt
    
    echo 'Open' > file.txt
    java -cp eg.jar;egPriv.jar -Djava.security.manager -Djava.security.policy=sample.policy  eg.Cat file.txt
    
    0 讨论(0)
提交回复
热议问题