Gregg's MOTD

Tips & Tricks that I've Encountered Over the Years...

Make a File Immutable

July 31, 2023 — Gregg Szumowski

You can use the chattr command (as root) to make a file “unalterable” so that even the root user cannot modify or delete it without using the chattr command to revert the change. This is done by using chattr’s +i and -i flags.

chattr changes a file’s attributes on a Linux file system.

Set the flag as root:

# chattr +i xrdp-notes.txt
# lsattr xrdp-notes.txt
----i---------e------- xrdp-notes.txt

A normal user can’t delete it:

$ rm xrdp-notes.txt
rm: cannot remove 'xrdp-notes.txt': Operation not permitted

Even root cannot delete it without changing the file attribute back:

# rm xrdp-notes.txt
rm: cannot remove 'xrdp-notes.txt': Operation not permitted

Once the flag is unset it can be deleted:

# chattr -i xrdp-notes.txt
# lsattr xrdp-notes.txt
--------------e------- xrdp-notes.txt
# exit
$ rm xrdp-notes.txt
$

Tags: cli, chattr, lsattr, motd