如何使文件不可修改?

use*_*130 38 linux permissions files readonly

登录后,我可以执行以下操作:

mkdir foo
touch foo/bar
chmod 400 foo/bar 
chmod 500 foo
Run Code Online (Sandbox Code Playgroud)

然后我可以打开 vim (不是 as root),编辑bar,用 强制写入w!,然后修改文件。

如何让操作系统禁止任何文件修改?

2017 年 3 月 2 日更新

  1. chmod 500 foo是一个红鲱鱼:目录的写权限与修改文件内容的能力无关——只有创建和删除文件的能力。

  2. chmod 400 foo/bar实际上确实可以防止文件的内容被更改。但是,它并不能阻止更改文件的权限——文件的所有者始终可以更改其文件的权限(假设他们可以访问该文件,即对所有祖先目录具有执行权限)。事实上,strace(1) 揭示了这就是 vim (7.4.576 Debian Jessie) 正在做的事情——vim 调用 chmod(2) 来临时添加文件所有者的写权限,修改文件,然后调用 chmod( 2)再次删除写权限。这就是为什么使用chattr +i作品——只有 root 可以调用chattr -i. 理论上,如果以 root 身份运行,vim(或任何程序)可以对 chattr 执行与对不可变文件中的 chmod 执行相同的操作。

jor*_*anm 61

您可以为 Linux 中的大多数文件系统设置“不可变”属性。

chattr +i foo/bar
Run Code Online (Sandbox Code Playgroud)

要删除不可变属性,请使用-代替+

chattr -i foo/bar
Run Code Online (Sandbox Code Playgroud)

要查看文件的当前属性,可以使用 lsattr:

lsattr foo/bar
Run Code Online (Sandbox Code Playgroud)

chattr命令(1)手册页提供了所有可用的属性的描述。以下是对 的描述i

   A  file with the `i' attribute cannot be modified: it cannot be deleted
   or renamed, no link can be created to this file  and  no  data  can  be
   written  to  the  file.  Only the superuser or a process possessing the
   CAP_LINUX_IMMUTABLE capability can set or clear this attribute.
Run Code Online (Sandbox Code Playgroud)

  • 在 Linux 上,该不可变标志在许多文件系统上都可用,而不仅仅是 ext2/3/4(至少 btrfs、hfsplus、jfs、nilfs2、xfs、ocfs2、ubifs、gfs2、reiserfs AFAICT 通过快速浏览代码) (3认同)