Chattr command in linux

chattr (Change Attribute) is a command line Linux utility that is used to set/unset certain attributes to a file in Linux system to secure accidental deletion or modification of important files and folders, even though you are logged in as a root user.

In Linux native filesystems i.e. ext2, ext3, ext4, btrfs, etc. supports all the flags, though all the flags won’t support to all non-native FS. One cannot delete or modify file/folder once attributes are sets with chattr command, even though one have full permissions on it.

This is very useful to set attributes in system files like passwd and shadow files wherein user’s info are contains.

Syntax of chattr

$ chattr [operator] [flags] [filename]

Attributes and Flags

Following are the list of common attributes and associated flags can be set/unset using the chattr command.

  • If a file is accessed with ‘A‘ attribute set, its atime record is not updated.
  • If a file is modified with ‘S‘ attribute set, the changes are updates synchronously on the disk.
  • A file is set with ‘a‘ attribute, can only be open in append mode for writing.
  • A file is set with ‘i‘ attribute, cannot be modified (immutable). Means no renaming, no symbolic link creation, no execution, no writable, only superuser can unset the attribute.
  • A file with the ‘j‘ attribute is set, all of its information updated to the ext3 journal before being updated to the file itself.
  • A file is set with ‘t‘ attribute, no tail-merging.
  • A file with the attribute ‘d‘, will no more candidate for backup when the dump process is run.
  • When a file has ‘u‘ attribute is deleted, its data are saved. This enables the user to ask for its undeletion.

Operator

  • + : Adds the attribute to the existing attribute of the files.
  •  : Removes the attribute to the existing attribute of the files.
  • = : Keep the existing attributes that the files have.

Here, we are going to demonstrate some of the chattr command examples to set/unset attributes to a file and folders.

1. How to add attributes on files to secure from deletion

For demonstration purpose, we’ve used folder demo and file important_file.conf respectively. Before setting up attributes, make sure to verify that the existing files have any attributes set using ls -l command. Did you see the results, currently no attribute are set.

To set attribute, we use the + sign and to unset use the  sign with the chattr command. So, let’s set immutable bit on the files with +i flags to prevent anyone from deleting a file, even a root user don’t have permission to delete it.

Note: The immutable bit +i can only be set by superuser (i.e root) user or a user with sudo privileges can able to set.

After setting immutable bit, let’s verify the attribute with command ‘lsattr‘.

Now, tried to delete forcefully, rename or change the permissions, but it won’t allowed says “Operation not permitted“.

2. How to unset attribute on Files

In the above example, we’ve seen how to set attribute to secure and prevent files from a accidental deletion, here in this example, we will see how to reset (unset attribute) permissions and allows to make a files changeable or alterable using -i flag.

After resetting permissions, verify the immutable status of files using ‘lsattr‘ command.

You see in the above results that the ‘-i‘ flag removed, that means you can safely remove all the file and folder reside in folder.

3. How to Secure /etc/passwd and /etc/shadow files

Setting immutable attribute on files /etc/passwd or /etc/shadow, makes them secure from an accidental removal or tamper and also it will disable user account creation.

[ro**@kb*****.com]# chattr +i /etc/passwd
[ro**@kb*****.com]# chattr +i /etc/shadow

Now try to create a new system user, you will get error message saying ‘cannot open /etc/passwd‘.

[ro**@kb*****.com]# useradd tecmint
useradd: cannot open /etc/passwd

This way you can set immutable permissions on your important files or system configuration files to prevent from deletion.

4. Append data without Modifying existing data on a File

Suppose, you only want to allow everyone to just append data on a file without changing or modifying already entered data, you can use the ‘a‘ attribute as follows.

[ro**@kb*****.com]# chattr +a example.txt

[ro**@kb*****.com]# lsattr example.txt
-----a---------- example.txt

After setting append mode, the file can be opened for writing data in append mode only. You can unset the append attribute as follows.

[ro**@kb*****.com]# chattr -a example.txt

Now try to replace already existing content on a file example.txt, you will get error saying ‘Operation not permitted‘.

[ro**@kb*****.com]# echo "replace contain on file." > example.txt
-bash: example.txt: Operation not permitted

Now try to append new content on a existing file example.txt and verify it.

[ro**@kb*****.com]# echo "replace contain on file." >> example.txt
[ro**@kb*****.com]# cat example.txt

Here is the example to test ‘a’ attribute mean append only.
replace contain on file.

5. How to Secure Directories

To secure entire directory and its files, we use ‘-R‘ (recursively) switch with ‘+i‘ flag along with full path of the folder.

[ro**@kb*****.com]# chattr -R +i myfolder

After setting recursively attribute, try to delete the folder and its files.

[ro**@kb*****.com]# rm -rf myfolder/
rm: cannot remove 'myfolder/': Operation not permitted

To unset permission, we use same ‘-R’ (recursively) switch with ‘-i’ flag along with full path of the folder.

[ro**@kb*****.com]# chattr -R -i myfolder

That’s it! To know more about chattr command attributes, flags and options use the man pages.

Knowledge Base Linux
Knowledge Base Linux

Kblinux is an abbreviation for the phrase "Knowledge Base Linux." The website shares instructional articles related to the Linux system. I hope my small blog will reach many people who share the same passion for Linux.

Articles: 36

9 Comments

  1. Greate post. Keep posting such kind of info on your site.
    Im really impressed by your site.
    Hey there, You’ve done a fantastic job. I’ll definitely digg it and personally suggest to my friends.
    I am sure they’ll be benefited from this site.

  2. Каждый фанат автотранспорта осведомлён что для хорошей и безвредной дороги на автомобиле целеобразны на все сто запаски. Шины допускаются разнообразные, но, в целом, все они подразделяются на летние, зимние и всесезонные. Ответственные автоводители прекрасно знают что их есть необходимость менять вытекая от сезона. Про это не логично забывать, а то последствия будут трагичные. Итак, вы нуждаетесь в идеальных покрышках? Думаете сменить летние покрышки на зимние или наоборот? Или же нравиться больше всесезонный вариант? Элементарно! У нас сможете найти всё!
    В нашем магазине преогромный спектр: низкопрофильные шины, без проколов шины, внедорожные покрышки, с симметричным рисунком или с асимметричным. Всё что пожелаете! Ещё, в нашей компании очень прикольная услуга. Мы имеем возможность хранить ваши автопокрышки на складе нашего магазина, а вы приходите, только лишь, поменять их исходя от времени года. В итоге, вы сохраните достаточно свободного места в вашем доме, и недорого. Классно, не так ли? А также, мы предлагаем вероятность замены шин не только в центре или вообще за городом. Требуется, не более как, позвать наших специалистов.
    https://forum.benzclub.md/index.php?showtopic=3330

    Круче шин не бывает – мы вас уверяем!

    Вы всё ещё ни сном ни духом в каком автосервисе обеспечить себе высококачественные покрышки? Не можете с выбором определиться? Ну что же, напряжёмся вас отговорить! Богаче набора чем в в нашей компании нет возможности себе передать! Вы cможете найти шины любого размера и марки для каждой марки автомашин. Эти автошины можно скупить по самым доступным ценам. У вас есть возможность найти себе что-то подходящее по вкусу и кощельку. В нашем магазине исполняют обязанности одни мастаки! Они помогут вам приметить правильный для вас вариант, будьте в этом уверенны! Для нашей команды тот или иной клиент ключевой, исходя из всего этого мы находим индивидуальный подход для всех! Так что не упустите из виду, а приезжайте, живей, к нам в сервис, для того чтобы совершить самую величайшую сделку из вашей жизни! До скорой встречи!

  3. Психологические факты о человеке интересные Интересное в психологии человека Психология человека темы
    Факты О Психологии Человека Интересные Короткие https://russianmanagement.com Факты который
    должен знать каждый образованный
    человек Статья про интересного человека

Leave a Reply

Your email address will not be published. Required fields are marked *