How-To: Make a file Immutable/Write protected
There might be time when you want to make sure that a file will be protected from accidental/automated change/deletion. While one can protect a file/directory in some ways by removing write permissions using standard file permission on Unix already can save you from some situations, there is more that can be done on Linux.
The e2fsprogs software suite comes with a bunch of file system utilities for the ext* filesystems. Amongst them, there is the chattr that will help us change attributes on a Linux File system.
While there is numerous attributes that can be changed, for the purpose of this post, we will look at the attribute that would make our file/directory immutable, even by root and whichever are the Unix filesystem permissions.
The attribute that we will modify is i as in immutable.
Making a file/directory immutable
To make a file or directory immutable, we will be using the following command (considering that the file we modify is called foo):
# chattr +i foo
Let’s play with 1 file and see how things go:
# ls -l foo
-rwxrwxrwx 1 user user 4 Jun 9 22:30 foo
# echo "foo" >> foo
# chattr +i foo
# echo "foo" >> foo
-su: foo: Permission denied
# rm foo
rm: cannot remove `foo': Operation not permitted
Removing immutable attribute from a file/directory
To remove that attribute, we need to use the -i version of the command:
# chattr -i foo
Now that we have remove the attribute, we can modify/remove the file:
# echo "foo" >> foo
# rm foo
Checking file attributes
lsattr command can be used to verify what attributes are set on a file/directory:
$ lsattr foo
----i--------e-- foo
There is more attributes available. To find more about it, refer to:
$ man chattr
Do mind that some attributes are not enabled on mainline Linux kernels.