How to make a file or Folder/Directory un-deletable on Linux?
The linux operating as we know if famous for the phrase “Everything is a file”, In such circumstances it is interesting to explore the possibilities of making a file undeletable, even by the owner of the file and for that matter even the root user, In the Linux Ecosystem the root is the poweruser.
This section we will see the potential of such feature.
As we have already seen the section on deleting files on Linux (removing the files in Linux).
We will now demonstrate the power of Linux where you can restrict the deletion of a file on Linux.
Linux offers a
chattr commandline utility which generally modifies the file attributes as the name suggests, but the practical use is to make a file undeletable.
Sample command syntax:
[vamshi@linuxcent ~]$ chattr +i <samplefile>
vamshi@linuxcent delete-dir]$ sudo chattr +i samplefile2.txt
Now we do ls -l samplefile2.txt
[vamshi@linuxcent ~]$ sudo chattr +i samplefile2.txt [vamshi@linuxcent ~]$ ls -l samplefile2.txt -rw-rw-r--. 1 vamshi vamshi 4 Apr 8 15:42 samplefile2.txt
Now we shall try to write some content to this file and see no change in the basic file permissions(see changing ownership of files).
[vamshi@linuxcent delete-dir]$ echo "New content" > samplefile2.txt -bash: samplefile2.txt: Permission denied
Deleting file forcefully with the
--force option ?
[vamshi@linuxcent delete-dir]$ sudo /bin/rm -f samplefile2.txt /bin/rm: cannot remove ‘samplefile2.txt’: Operation not permitted
lsattr offers the ability to view the permissions set by the
The current File attributes can be listed using
lsattr followed by the filename [/code]samplefile2.txt[/code] as below
[vamshi@linuxcent delete-dir]$ lsattr samplefile2.txt ----i----------- samplefile2.txt
Even the root user on the host is unable to delete the file or modify its contents.
The file can be deleted only when the attributes are unset, It is demonstrated as follows:
[vamshi@linuxcent delete-dir]$ sudo chattr -i samplefile2.txt [vamshi@linuxcent delete-dir]$ lsattr samplefile2.txt ---------------- samplefile2.txt
As we can see the
lsattr doesn’t hold true anymore attributes on our file
samplefile2.txt and is now being treated as any other normal file with basic file attributes.
- operation removes the special linux file attributes on the mentioned file.
chattr / lsattr linux commandline utilities currently supports the popular filesystems such as ext3,ext4,xfs, btrfs etc,.