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.

Let’s check the file attributes again.

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.

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.

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 = { interested_in(unix, linux, android, open_source, reverse_engineering); coding(c, shell, php, python, java, javascript, nodejs, react); plays_on(xbox, ps4); linux_desktop_user(true); }