The task is achieved with the chattr command, which is used in order to change the attributes of a file. The option which is relevant in our case is the "i" option: "+i" to activate and "-i" to deactivate the protection for the file. The "i" stands for "immutable", which means "can't be changed".
The following commands should be entered as root.
Protecting the file (adding the "i" attribute):
# chattr +i
Removing protection for the file (removing the "i" attribute):
# chattr -i
In both cases above, if the action is performed on directories: the "-R" option can be added, to execute the commands recursively (on sub-dirs and on their files as well).
To list the attributes of a file (including the "i" attribute):
# lsattr
Examples
We're logged-in as root. Lets create the file important.txt, and add some text to it:
# echo "This is a very important file." >important.txt
Currently, root can of course continue modifying the contents of the file, and can also rename it or delete it, at will.
Lets see what happens when we add the "i" attribute to the file:
# chattr +i important.txt
# lsattr important.txt
We can see that the "i" attribute was added to the file.
Can root modify the file?
# echo "This is an additional line of text." >>important.txt
Can root rename the file?
# mv important.txt important2.txt
Finally, can root delete the file?
# rm important.txt
As can be seen, the answer to all questions above is - no. The file is fully protected from: modification of its contents, renaming and deleting. This is true even while logged-in as root. This will change only after we issue the opposite command: # chattr -i important.txt - which will remove the special protection measures we've added to the file, and will return its state to normal.
No comments:
Post a Comment