如何编辑文件并保留其访问控制列表/SELinux 安全上下文?

Ala*_*lan 8 acl selinux

我在 CentOS 6.2 上,并且有一个文件,其中备用访问方法字符显示为一个点。

ls -l myfile
-rwxr-x---. 1 me mygroup   172 Aug 13 10:03 myfile
          ^ 
          This dot.
Run Code Online (Sandbox Code Playgroud)

从显示为 ls 的帮助信息 coreutils 'ls invocation'

Following the file mode bits is a single character that specifies
whether an alternate access method such as an access control list
applies to the file.  When the character following the file mode
bits is a space, there is no alternate access method.  When it is
a printing character, then there is such a method.

GNU `ls' uses a `.' character to indicate a file with an SELinux
security context, but no other alternate access method.

A file with any other combination of alternate access methods is
marked with a `+' character.
Run Code Online (Sandbox Code Playgroud)

所以这个文件有一些分配给它的SELinux 安全上下文。使用getfaclgetfattr这些命令显示:

getfacl myfile
# file: myfile
# owner: me
# group: mygroup
user::rwx
group::r-x
other::---

getfattr -m - myfile
# file: myfile
security.selinux

getfattr -n security.selinux myfile
# file: myfile
security.selinux="unconfined_u:object_r:usr_t:s0"
Run Code Online (Sandbox Code Playgroud)

我已经备份了原始文件:

cp --preserve=all myfile myfile.ORIG
Run Code Online (Sandbox Code Playgroud)

然后编辑原文:

vi myfile
:wq
Run Code Online (Sandbox Code Playgroud)

它吹走了它所拥有的任何上下文:

ls -l myfile
-rwxr-x---  1 me mygroup   172 Aug 13 10:06 myfile
          ^ 
          The dot is gone.

getfattr -n security.selinux myfile
myfile: security.selinux: No such attribute

getfacl myfile
# file: myfile
# owner: me
# group: mygroup
user::rwx
group::r-x
other::---
Run Code Online (Sandbox Code Playgroud)

编辑此文件并保留其扩展属性和备用访问方法设置的推荐过程是什么?

Gil*_*il' 4

保存文件时,编辑者可以遵循两种策略之一。

\n\n
    \n
  • 创建一个新文件,然后将其移动以替换旧文件。主要优点是始终存在有效文件:旧版本会自动被新版本替换。缺点是创建了一个新文件,因此编辑者必须尽其所能手动复制旧文件的所有权和权限。此方法也会破坏硬链接。
  • \n
  • 写入现有文件。这保留了硬链接和权限。此外,这不需要任何额外的磁盘空间,但强烈建议先进行备份,这使得这一点毫无意义。这样做的主要缺点是,如果程序在保存文件时尝试读取该文件,它将看到一个被截断的文件;如果保存中断(例如由于电源故障),则会保留部分文件。
  • \n
\n\n

编辑者通常倾向于第一种方法,如果他们检测到无法复制现有文件的权限或现有文件具有硬链接,则转而使用第二种方法。

\n\n

大多数编辑者可能没有意识到额外 SELinux 属性的存在,因此应用第一种方法。使用最新版本的 GNU coreutils (\xe2\x89\xa5 8.6),您可以将cp --preserve=context --attributes-only一个文件的 SELinux 上下文复制到另一个文件上,而无需更改目标文件的内容。

\n\n

或者,指示您的编辑器就地编辑文件。对于 Vim,将 \nbackupcopy选项设置为yes,如果这不是系统上的默认设置。使用 Emacs,将backup-by-copying变量设置为t

\n