12

If I would like to lock a file as read-only. Even root can not use an editor to modify it, just allowing any program to open it read-only.

Any suggestions?

Niall C.
  • 10,878
  • 7
  • 69
  • 61
Denny
  • 449
  • 4
  • 17

3 Answers3

24

There is an "immutable" bit for files.

Programs (even running as root) won't be able to tamper with the file. Of course, root can un-do the bit, but most programs (especially non-malicious ones) won't get past it.

Set it with

sudo chattr +i file
Quanlong
  • 24,028
  • 16
  • 69
  • 79
BraveNewCurrency
  • 12,654
  • 2
  • 42
  • 50
  • 1
    You can undo this by doing `chattr -i file`. How would you make this "immutable" bit immutable itself? I had read in a book that you could remove the `cap_linux_immutable` capability to root, so that root couldn't change the immutable bit any longer without rebooting the computer. The file was thus not totally immutable but you had to reboot with a different capability setting if you wanted to use `chattr` to reverse the immutable bit. I wish I found a way to do this today but I can't find a way now, it seems the utility that permitted this (`lcap`) is no longer part of the main linux distros. – John Smith Optional Jan 21 '20 at 01:10
4

you should have root perms

sudo chattr +i file

Dharmanshu Kamra
  • 601
  • 3
  • 8
  • 18
0

You can use Perl or another language to create a file lock

How do I lock a file in perl

But, root could kill the process can gain access to the file.

Community
  • 1
  • 1
traxs
  • 306
  • 1
  • 5
  • 1
    `flock` and `lockf` etc. are just "informative" locks; files which ignore them are not affected by them. – glglgl Aug 01 '13 at 04:29