Linux Command: chattr

I had a student ask if there was a way to protect files from being deleted by root.  The scenario I was told is that they have a Linux server and share SUDO access with several administrators.  The problem is that sometimes files are getting clobbered when other admins are running installs, updates or try to clean up disk space on the server.

I asked if he used the chattr command before?  It works like chmod but has a few extra features.  The one that would work for his problem is the + i attribute.  When you run the command chattr + i /file/name it makes the file “Immutable” since I’m working on another post about programming I’ll skip the detailed description for now but it sets the file permission so that it can’t be modified or deleted even by root.  For example if someone logs in as root and runs my favorite command “rm -rf *” the files set with + i would still be on the disk.

I use this to protect the important files on the Linux servers.  You can use it on the /etc/passwd file, various configuration files, you can even use it for log files.  If you really know your system, and want to harden it, you can even use it on the /sbin, /bin, /usr/sbin, /usr/lib and other sensitive directories.

I have only used it for protecting directories a few times and I have a script that I run that will perform a few tasks and make the files editable.  After I finish running updates or installing new software.  I then run the script again and it “locks” all the files again.

I also use this for protecting the configuration and log files I create with the scripts that I write.  You can use the +a attribute which makes the file append only.

So if you have privilege access (root or sudo) to a Linux server that has the ext2/ext3 type file system you can use the following commands:

To prevent a user or root from accidentally modifying or deleting a file.

# chattr +i /file/name

or

To prevent a user, root or a process from deleting a file but still be able to write to it.

# chattr +a /log/file

Don’t forget to check your man page for all the other useful stuff chattr can do. [Ex. man chattr]

Let me know if you found this Linux command useful.  I don’t think I’ve seen it posted online before so I hope I helped you learn something new today.

If you have a cool Linux commnad that is off the beaten path post it in the comments.

2 Responses to “Linux Command: chattr”

  1. Linux Command: chattr…

    I had a student ask if there was a way to protect files from being deleted by root. The scenario I was told is that they have a Linux server and share SUDO access with several administrators. The problem is that sometimes files are getting clobbered …

  2. a very useful command
    thanks you

Leave a Reply