How to Prevent File Modification Even by Root in Ubuntu
In Linux Ubuntu, standard file permissions often fail to stop the root user from altering critical system files. This guide explains how to use the immutable attribute to lock files down completely. You will learn the specific commands required to make a file unchangeable and how to reverse the process when edits are needed.
Understanding the Immutable Flag
Standard Linux permissions control access for users, groups, and
others, but the root user can override these restrictions. To bypass
root privileges, you must use the chattr command to set the
immutable flag on a file. This flag tells the kernel to reject any write
operations, deletions, or renames, regardless of user status.
How to Lock a File
To prevent any modifications to a specific file, open your terminal and run the following command using sudo privileges:
sudo chattr +i /path/to/your/fileReplace /path/to/your/file with the actual location of
the file you wish to protect. Once executed, even the root user cannot
edit, delete, or rename this file until the flag is removed.
How to Verify Protection
You can confirm that the immutable attribute is active by using the
lsattr command. Run the following in your terminal:
lsattr /path/to/your/fileIf the file is locked, you will see an i character in
the list of attributes, indicating that the immutable flag is set.
How to Unlock a File
If you need to modify or delete the file later, you must remove the immutable flag first. Use the following command to unlock the file:
sudo chattr -i /path/to/your/fileAfter removing the flag, standard permissions apply, and the file can be edited or deleted by the root user as normal. Always exercise caution when locking system files, as preventing modifications to critical configurations can cause system instability.