Unix & Linux
linux c chown chgrp
Updated Tue, 13 Sep 2022 05:54:06 GMT

why chgrp or chown command causes file loss xattr


[root@localhost ~]# getfattr -m - -d /bin/tcpm
getfattr: Removing leading '/' from absolute path names
# file: bin/tcpm
security.capability=0sAQAAAgAUAAAAAAAAAAAAAAAAAAA=
security.selinux="system_u:object_r:bin_t:s0"
[root@localhost ~]# chgrp 951 /bin/tcpm
[root@localhost ~]# getfattr -m - -d /bin/tcpm
getfattr: Removing leading '/' from absolute path names
# file: bin/tcpm
security.selinux="system_u:object_r:bin_t:s0"

after chown uid /bin/tcpm or chgrp gid /bin/tcpm/bin/tcpm loss xattr(security.capability)

#/bin/tcpm provides by tcpm-kmod




Solution

The coreutils.info documentation on chown says:

The chown command sometimes clears the set-user-ID or set-group-ID permission bits. This behavior depends on the policy and functionality of the underlying chown system call, which may make system-dependent file mode modifications outside the control of the chown command. For example, the chown command might not affect those bits when invoked by a user with appropriate privileges, or when the bits signify some function other than executable permission (e.g., mandatory locking). When in doubt, check the underlying system behavior.

So it's time to look at the chown() system call (i.e. man 2 chown):

When the owner or group of an executable file is changed by an unprivileged user, the S_ISUID and S_ISGID mode bits are cleared. POSIX does not specify whether this also should happen when root does the chown(); the Linux behavior depends on the kernel version, and since Linux 2.2.13, root is treated like other users. In case of a non-group-executable file (i.e., one for which the S_IXGRP bit is not set) the S_ISGID bit indicates mandatory locking, and is not cleared by a chown().

When the owner or group of an executable file is changed (by any user), all capability sets for the file are cleared.

In other words: whenever the owner or group of an executable file is changed, the system will automatically remove any special privileges from the file. This includes not only the SUID/SGID bits, but also capabilities.

The removal of special privileges is not done by the chown or chgrp command, but by the system call those commands use to do their job, so any other way to change the group or owner of a file should also cause its special privileges to be removed.

The reason for removal of special privileges is not stated, but I would guess it blocks a class of attacks that would allow an user to gain extra privileges by manipulating another user and/or a root-owned process to change the group or owner of a privileged program.