[icon type=”linux”]You can make a file immutable on Linux with the help of utility called chattr. One can changes the file attributes on a Linux second extended file system. The operator + causes the selected attributes to be added to the existing attributes of the files; - causes them to be removed; and = causes them to be the only attributes that the files have.
What is an immutable attribute on a Linux?
A file with an immutable attribute can not be:
- No soft or hard link created by anyone including root user.
Only the root (superuser) or a process possessing the CAP_LINUX_IMMUTABLE capability can set or clear this attribute. Use the lsattr command to list file attributes on a Linux second extended file system that you set with the chattr command.
How to make a file immutable on Linux
First, you need to login as root user. Only root user can set and remove immutable flag on a file. The syntax is:
chattr +i file chattr +i /path/to/filename
Type the following command to write protect /etc/shadow file on a Linux:
# chattr +i /etc/shadow
Now, login as the normal user (say vivek) and type the passwd command to change password:
Changing password for user vivek. Changing password for vivek (current) UNIX password: OLDPASSWED New password: NEWPASSWD Retype new password:NEWPASSWD passwd: all authentication tokens updated successfully.
Logout and try to login with the new password. However, system will not accept your new password. You still need to use the old password.
To get the list of Linux second extended file system using the lsatter command (run as the root user ):
# lsattr /etc/shadow
Please note that even root user is not allowed to change the password. You can remove the attribute using the following command (again must be run as the root user):
chattr -i /etc/shadow lsattr /etc/shadow
Securing mount points on a Linux
Want to write protect the entire mount point so that no one can add or delete files including root user? Try:
# secure partition mounted at /securebackup location ## chattr +i -R /securebackup lsattr -d /securebackup lsattr -l /securebackup cd /securebackup ## Try to add or delete something ## echo "test" > foo.txt mkdir foo ls -l rm SeaToolsDOS223ALL.ISO ## Remove it again ## cd / chattr -i -R /securebackup lsattr -d /securebackup
The -R option recursively change attributes of directories and their contents. This is useful to protect web server DocumentRoot or other publicly accessible directory over sftp/ftp.
Protecting important files
You can protect important files such as:
- /etc/group and more
A note about FreeBSD or Apple OS X Unix-like users
Try the chflags command. This command modifies the file flags of the listed files as specified by the args including the user immutable flag.
To see all Linux second extended file system attributes read the man page by typing the following command: