Linux: Make File Undeletable / Immutable

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.

# lsattr /etc/hosts
-------------e-- /etc/hosts
# chattr +i /etc/hosts
# lsattr /etc/hosts
----i--------e-- /etc/hosts

Let’s check the file attributes again.

# 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.

# whoami
# 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.

# chattr -i /etc/hosts
# lsattr /etc/hosts
-------------e-- /etc/hosts
# rm /etc/hosts
# echo $?

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.

Ibrahim is a technology enthusiast with a keen interest in *NIX (Unix, Linux) systems, Android, open source and other tech related stuff. When his cpu load is low, you can probably find him online playing on his Xbox or PlayStation.