2

The students in my beginning Java class are beginning to learn about file I/O, and one of their projects involves deleting and renaming files. I can think of dozens of ways this can go wrong.

Therefore, it would be useful to use Java's security framework to restrict their programs from renaming, deleting, or writing over files that are not contained in a specific directory. Reading outside the directory is fine, and the policy doesn't need to be super-bulletproof -- this is more about preventing accidental damage than protecting against maliciousness on the part of my students.

However, I haven't done any real Java work outside the domain of programming courses at school, so I don't know how to write or activate policy files. What is a simple policy file I can use to achieve this, and how would I activate it when running my students' code?

LeafStorm
  • 2,777
  • 3
  • 21
  • 26
  • See [See the Policy File Effects](http://docs.oracle.com/javase/tutorial/security/tour2/step4.html) for applying the policy. As for writing it, I have no idea, since I never use them. – Andrew Thompson Mar 18 '13 at 15:39

1 Answers1

3

Here is a dirt simple policy file that you can use for restricting file writes to a certain directory.

grant codeBase "file:/some/root/path/sandbox/-" {
    permission java.io.FilePermission "*", "read";
    permission java.io.FilePermission "/tmp/*", "read, write";
};

It assumes you will be staging and launching your code from /some/root/path/sandbox, and that you will be granting write permission only to the /tmp folder. You can add additional read and write permissions as required. To invoke, launch your code with the following command line:

java -Djava.security.manager -Djava.security.policy=student.policy YourClassName

This presumes you stored the policy in a file called student.policy, in the same folder as where you are launching the code from

Perception
  • 75,573
  • 19
  • 170
  • 185
  • This looks like it will do the trick. (Though I'm a bit confused about the purpose of the "-" on the end of the path.) Thanks! – LeafStorm Mar 18 '13 at 16:10
  • @LeafStorm - the `-` indicates that the policy should apply recursively in the specified directory. You can reference the [Signed By, Principal, and CodeBase Fields](http://docs.oracle.com/javase/6/docs/technotes/guides/security/PolicyFiles.html#FileSyntax) section of [Default Policy Implementation and Policy File Syntax](http://docs.oracle.com/javase/6/docs/technotes/guides/security/PolicyFiles.html) for detailed information. – Perception Mar 18 '13 at 16:15
  • Ah, OK. Thanks for the link, as well. – LeafStorm Mar 18 '13 at 16:27