FreeBSD: How to write protect important file ( even root can NOT modify / delete file )

by on June 29, 2005 · 3 comments· LAST UPDATED November 26, 2007

in , ,

The chflags utility modifies the file flags of the listed files as specified by the flags operand.

FreeBSD offers write protection, you need to to set special bit call immutable. Once this bit is setup no one can delete or modify file including root. And only root can clear the File immutable bit.

You must be a root user to setup or clear the immutable bit.

Setup file immutable bit

Use chflags command as follows:
# chflags schg /tmp/test.doc
Try to remove or moify file file with rm or vi:
# rm -f /tmp/test.doc
Output:

rm: /tmp/test.doc: Operation not permitted

Now root user is not allowed to remove or modify file. This is useful to protect important file such as /etc/passwd, /etc/master.passwd etc.

Display if file immutable bit is on or off

ls -lo /tmp/test.doc
Output:

-rw-r--r--  1 root  wheel  schg 19 Jun 29 22:22 /tmp/test.doc

Clear or remove file immutable bit

#chflags noschg /tmp/test.doc
Now you can remove or modify file. Please note that immutable flag can be set by root user only. chflags also supports few other interesting flags.

  • arch: set the archived flag
  • nodump: set the nodump flag
  • sappnd: set the system append-only flag
  • schg: set the system immutable flag
  • sunlnk: set the system undeletable flag
  • uappnd: set the user append-only flag
  • uchg: set the user immutable flag
  • uunlnk: set the user undeletable flag

Putting the letters no before an option causes the flag to be turned off.

Please note Linux also supports immutable flag to write protect files using chattr command.

See man page chflags and ls commands for more information.

TwitterFacebookGoogle+PDF versionFound an error/typo on this page? Help us!

{ 3 comments… read them below or add one }

1 Anonymous June 30, 2005 at 7:38 pm

Hey thanks for this tip :D

Reply

2 Bob May 28, 2007 at 2:05 am

Two questions:

How to write protect
Is it legal

Reply

3 weng fu July 22, 2013 at 1:16 am

How can I do this using Visual Basic 6? Thank you.

Reply

Leave a Comment

Tagged as: , , , , ,

Previous post:

Next post: