How to prevent a user from deleting a file that is used by the JVM

I have a piece of JAVA code that reads several files and stores them in memory for a while. After reading, the files are saved. My problem is that I want to limit the user to deleting these files using the DEL or rm command.

I could achieve the same in windows by saving file descriptors, and on Unix rm does not comply with file locking. I even tried Filechannel.lock() , but that didn't help either.

Any suggestions are welcome.

+4
source share
3 answers

While you open the descriptor, they can delete the file from the directory, but they cannot delete the file. that is, the file is not deleted until you close the file or your process dies.

I even tried Filechaanel.lock (), but that didn't help either.

This is because it is a directory and not a file that is being modified. for example, if they have write access to a file, but not a directory that they cannot delete.

+5
source

You can also see a chattr that you can use to lock a file.

 chattr +i filename 

Must make the file invulnerable. Then you can delete it again with ...

 chattr -i filename 
+3
source

There is no pure Java solution for this. In fact, I do not think that there is a solution that does not have potentially unpleasant consequences. The main problem is that UNIX / LINUX does not have the ability to temporarily set the required file lock. (The Linux script to lock the file is flock , but the start style locks are discretionary. An application that does not bother the flock file will not be affected by other application locks in the file.)

The best you can do is use chattr +i to set the immutable attribute to the file. Unfortunately, this has other effects:

  • An immutable file cannot be written to or linked to.

  • If your application crashes without disabling this attribute, the user has a file that he / she mysteriously cannot modify or delete. Not even with sudo or su.

+1
source

All Articles