Debian/Ubuntu Tips and Tricks

Debuntu

Debian/Ubuntu Tips and Tricks

How-To: Make a file Immutable/Write protected

Posted by chantra on June 10th, 2013

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.

2 Responses to “How-To: Make a file Immutable/Write protected”

  1. I have had a persistent problem with a hacker changing my .htaccess file to redirect people to a drug site. Is this a good way to make it so it is nearly impossible for them to change my .htaccess file? Changing file permissions and passwords,etc. have not worked.

    • That will prevent them from changing the file unless they make this file mutable again first.
      Nonetheless... the fact that they can modify this file either directly through a remote exploit or with a shell access to the server should be tackled

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>