Objective: Make a file undeletable or immutable on Linux.
Extended file attributes allow a user to set certain attributes of a file residing on a Linux file system. Extended file attributes support is based on the file system and on Linux, the default ext
(ext2
, ext3
, ext4
) file systems have support for extended file attributes. File systems like XFS, Btrfs and JFS also support extended file attributes. The file attributes can be managed using the lsattr
and chattr
commands.
Some of the common extended file attributes are:
- Attribute:
i
immutable
– file cannot be modified, deleted, renamed or hard linked to - Attribute:
a
append
– append only, existing file contents cannot be modified, cannot be deleted, useful for audit trail logs
The list of extended file attributes are not standardised and you cannot expect similar attributes to be supported on other UNIX variants like Solaris, AIX or HP-UX.
To make a file undeletable on Linux, we will need to enable the immutable attribute using the +i
option. Let’s turn on the immutable attribute for the /etc/hosts
file. Take note that only the superuser can set or clear this attribute.
1 2 3 4 5 |
# lsattr /etc/hosts -------------e-- /etc/hosts # chattr +i /etc/hosts # lsattr /etc/hosts ----i--------e-- /etc/hosts |
Let’s check the file attributes again.
1 2 |
# lsattr /etc/hosts ----i--------e-- /etc/hosts |
The i
flag indicates that the immutable attribute is now turned on for the /etc/hosts
file. Let’s try deleting the file as root
.
1 2 3 4 |
# whoami root # rm -rf /etc/hosts rm: cannot remove /etc/hosts: Operation not permitted |
The immutable attribute has to be cleared before the file can be deleted. To clear the immutable flasg, we will need to use the -i
option.
1 2 3 4 5 6 |
# chattr -i /etc/hosts # lsattr /etc/hosts -------------e-- /etc/hosts # rm /etc/hosts # echo $? 0 |
Take note that only the superuser or a process possessing the CAP_LINUX_IMMUTABLE
capability can set or clear this immutable attribute on Linux. BSD has support for user immutable flag where either the file owner or the superuser can set the uimmutable
flag.