Can super user write into read-only files

filespermissionsroot

I've stumbled upon surprising (for me) permission behavior on FreeBSD. Let's say I'm operating as non-root user. I create a file, set its permission on read-only and then try to write into it:

$ touch f
$ chmod 400 f
$ ls -l f
-r--------  1 user  wheel  f
$ echo a >> t
t: Permission denied.

So far so good. Now I do the same as root and it writes into the file:

# ls -l f2
-r--------  1 root  wheel  f2
# echo a >> f2
# echo $?
0

Is it a bug or intended behavior? Can I safely assume that this would work so on any Unix & Linux?

Best Answer

It's normal for root to be able to override permissions in this manner.

Another example is root being able to read a file with no read access:

$ echo hello > tst
$ chmod 0 tst
$ ls -l tst
---------- 1 sweh sweh 6 Aug 16 15:46 tst
$ cat tst
cat: tst: Permission denied
$ sudo cat tst
hello

Some systems have the concept of immutable files. eg on FreeBSD:

# ls -l tst
-rw-r--r--  1 sweh  sweh  6 Aug 16 15:50 tst
# chflags simmutable tst
# echo there >> tst
tst: Operation not permitted.

Now even root can't write to the file. But, of course, root can remove the flag:

# chflags nosimmutable tst
# echo there >> tst
# cat tst
hello
there

With FreeBSD you can go a step further and set a kernel flag to prevent root from removing the flag:

# chflags simmutable tst
# sysctl kern.securelevel=1
kern.securelevel: -1 -> 1
# chflags nosimmutable tst
chflags: tst: Operation not permitted

Now no one, not even root can change this file.

(The system needs rebooting to reduce the securelevel).