Tuesday, June 11, 2019

How to Make File undeletable Even By Root in Linux ?

On Unix-like operating systems including Linux, root is the account or user name that by default can
modify all directories and files on a system. In this article, we’ll show how to make directories or
files unremovable even by the root user in Linux.

To make a file undeletable by any system user, including root, you need to make it unmodifiable
using using the chattr command. This command changes file attributes on a Linux file system.

How to Make File Undeletable in Linux

The command below makes test.txt file immutable (or undeletable). This implies that the file can’t
be modified in any way: it can’t be deleted or renamed. You can’t even create a link to it and no data
can be written to the file as well.

Note that you need superuser privileges to set or remove this attribute, using the sudo command:

chattr - change file attributes on a Linux file system

DESCRIPTION
      chattr changes the file attributes on a Linux file system.

      The format of a symbolic mode is +-=[acdeijstuACDST].

      The operator `+' causes the selected attributes to be added to the existing attributes of the files;
`-' causes them to be removed; and `=' causes
      them to be the only attributes that the files have.

      The letters `acdeijstuACDST' select the new attributes for the files: append only (a), compressed
(c), no dump (d), extent  format (e), immutable (i), data  journalling (j),  secure deletion (s), no
tail-merging (t), undeletable (u), no atime
updates (A), no copy on write (C), synchronous
      directory updates (D), synchronous updates (S), and top of directory hierarchy (T).

      The following attributes are read-only, and may be listed by lsattr(1) but not modified by chattr:
huge file (h), compression  error (E), indexed
      directory (I), compression raw access (X), and compressed dirty file (Z).

OPTIONS
      -R Recursively change attributes of directories and their contents.

      -V Be verbose with chattr's output and print the program version.

      -f Suppress most error messages.

      -v version
             Set the file's version/generation number.



$ sudo chattr +i test.txt
OR
$ sudo chattr +i -V test.txt

Output:
sudo chattr +i -V test.txt
chattr 1.42.9 (4-Feb-2014)
Flags of test.txt set as ----i--------e--



To view attributes of a file, use the lsattr command as shown.

$ lsattr test.txt

Output:

lsattr test.txt
----i--------e-- test.txt




Now try to remove the immutable file, both as a normal user and as a root.

$ rm test.txt
$ sudo rm test.txt

Output:

sudo rm -rf test.txt
rm: cannot remove ‘test.txt’: Operation not permitted

use -i sign to remove the attribute

sudo chattr -i -V test.txt
chattr 1.42.9 (4-Feb-2014)
Flags of test.txt set as -------------e--

Now we can delete the file.

No comments:

Post a Comment