Thursday, July 30, 2009

chattr, lsattr linux command usage and examples

Take a scenario with 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.

Now you need to save your files or make other admins to know about your files.

Now you may thinks of sticky bit but it works between owner and group but not between users.

so ....

chattr is what compares to 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 /filename it makes the file “Immutable” 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.
(now if u want to remove use -i in the place)

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


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

# chattr +a /log_file

see [Ex. man chattr] more help.

Before changing attribute lsattr shows

--------------- ./temp
--------------- ./temp2
--------------- ./temp3

now do

chattr +i temp

do lsattr

----i---------- ./temp

--------------- ./temp2
--------------- ./temp3

and we have lot more

There are some other valid bits that chattr can set (see "man chattr"):

a = append-only mode
c = compressed storage
d = dump-omitted (omit this file, when using the dump command)
j = journaled
s = secret (zero out all its bits, if you delete the file)
S = synchronous-written
u = undeletable


No comments: