Linux – removing write permission does not prevent root from writing to the file

linuxpermissionsrootunix

I just noticed on my Ubuntu machine (ext3 filesystem) that removing write permissions from a file does not keep root from writing to it.

Is this a general rule of UNIX file permissions? Or specific to Ubuntu? Or a misconfiguration on my machine?

# touch abc
# chmod ugo-w abc
# python
Python 2.6.4 (r264:75706, Dec  7 2009, 18:45:15) 
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> open('abc','w').write('AAA\n')
>>> 
# cat abc
AAA

Writing to the file fails (as expected) if I do this from my normal user account.

  1. Is this normal behavior?

  2. Is there a way to prevent root from accidentally writing to a file? (Preferably using normal filesystem mechanisms, not AppArmor, etc.)

Please teach me about something that I most definitely don't understand.

NOTE: I understand that root has total control over the system and can, eg, change the permissions on any file. My question is whether currently set permissions are enforced on code running as root. The idea is the root user preventing her/himself from accidentally writing to a file.

NOTE: I also understand that one should not be logged in as root for normal operations. I just noticed this behavior and am asking you about it.

Best Answer

1) This is a normal behaviour. root has rw access on all files at all times.

2) You can protect a file even from root (not deliberate action, but accidental, anyway) by using

chattr +i filename.ext

That is "change attributes add immutable". To remove the protection:

chattr -i filename.ext

have a look at man chattr for more info

Related Question