Secure File from Removal in Linux and Unix

Protecting files from unwanted deletion is very important security on the tasklist of Unix Administrators. On Linux boxes you can use the chattr command and that works  ine on all my Ubuntu based servers. On FreeBSD, this command doesn’t exist. An alternative we use is the chflags command.

Let’s give  you some examples how chattr work under Linux:

Making a folder undeletable in Linux

To make a folder undeletable, run:

sudo chattr +i -R foldername

After that, you can’t delete, rename or do anything with this folder.

But if you don’t need this folder anymore or you’ve got to apply some changes to it run:

sudo chattr -i -R foldername

Making a file undeletable

To make a file undeletable, run:

sudo chattr +i filename

To be able to change or delete the file, run:

sudo chattr -i filename

How it works On FreeBSD

FreeBSD offers another way of protection, you need to set a special bit call immutable to the file. If you setup this bit, you will not be able to remove or edit this file, only root can clear the files immutable bit.

Let’s give some examples:

[email protected]:/root # ls -lh
total 24
-rw-r--r-- 2 root wheel 1k Dec 4 10:34 .cshrc
-rw------- 1 root wheel 62B Apr 1 21:33 .history
-rw-r--r-- 1 root wheel 151B Dec 4 10:34 .k5login
-rw-r--r-- 1 root wheel 299B Dec 4 10:34 .login
-rw-r--r-- 2 root wheel 256B Dec 4 10:34 .profile
-rw-r--r-- 1 root wheel 8B May 20 23:24 important-file

Setup file immutable bit:

chflags schg important-file

Trying to remove or edit the file


[email protected]:/root # rm important-file 
override rw-r--r-- root/wheel schg for important-file?


[email protected]:/root # mv important-file important-file2
mv: rename important-file to important-file2: Operation not permitted


[email protected]:/root # echo text > important-file
important-file: Operation not permitted.

Display if file immutable bit is on or off:

[email protected]:/root # ls -lo important-file 
-rw-r--r-- 1 root wheel schg 8 May 20 23:24 important-file

Remove file immutable bit:

[email protected]:/root # chflags noschg important-file

Display if file immutable bit is on or off:

[email protected]:/root # ls -lo important-file
-rw-r--r-- 1 root wheel - 8 May 20 23:24 important-file

Delete the file:

[email protected]:/root # rm important-file

Please enjoy!