超级用户可以写入只读文件吗?

arr*_*owd 12 root permissions files

我在 FreeBSD 上偶然发现了令人惊讶的(对我而言)许可行为。假设我以非 root用户身份操作。我创建一个文件,将其权限设置为只读,然后尝试写入其中:

$ touch f
$ chmod 400 f
$ ls -l f
-r--------  1 user  wheel  f
$ echo a >> t
t: Permission denied.
Run Code Online (Sandbox Code Playgroud)

到现在为止还挺好。现在我和 root 做同样的事情,它写入文件:

# ls -l f2
-r--------  1 root  wheel  f2
# echo a >> f2
# echo $?
0
Run Code Online (Sandbox Code Playgroud)

这是一个错误还是预期的行为?我可以安全地假设这在任何 Unix 和 Linux 上都可以工作吗?

Ste*_*ris 14

root能够以这种方式覆盖权限是正常的。

另一个示例是root能够读取没有读取权限的文件:

$ 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
Run Code Online (Sandbox Code Playgroud)

一些系统具有不可变文件的概念。例如在 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.
Run Code Online (Sandbox Code Playgroud)

现在甚至root无法写入文件。但是,当然,root可以删除标志:

# chflags nosimmutable tst
# echo there >> tst
# cat tst
hello
there
Run Code Online (Sandbox Code Playgroud)

使用 FreeBSD,您可以更进一步并设置内核标志以防止root删除该标志:

# chflags simmutable tst
# sysctl kern.securelevel=1
kern.securelevel: -1 -> 1
# chflags nosimmutable tst
chflags: tst: Operation not permitted
Run Code Online (Sandbox Code Playgroud)

现在没有人,甚至root不能改变这个文件。

(系统需要重新启动以降低安全级别)。

  • FWIW,在 Linux 中`chattr +i tst` 设置 _immutable_ 属性。 (4认同)