Re: Prevent chown to remove the setuid bit
You can't prevent that behavior without changing the kernel itself.
chown(2)
When the owner or group of an executable file is changed by an unprivi-
leged 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.
As for work-around, you can add suid and/or sgid after chown(2).
Or if you first clear execute, looks like for group that prevents sgid
from being
cleared, but looks like that doesn't hold for suid.
So, you can note permissions first, and reset them after.
# ls -l test
-rwSr--r-- 1 test test 0 Nov 29 12:34 test
# (p="$(stat -c '%a' test)" && chown root:root test && chmod "$p" test
&& ls -ld test)
-rwSr--r-- 1 root root 0 Nov 29 12:34 test
#
On Wed, Nov 26, 2025 at 11:40 AM Franco Martelli <martellif67@gmail.com> wrote:
>
> Hi everyone,
>
> Running these commands:
>
> ~$ touch test
> ~$ chmod 4644 test
> ~$ ls -l test
> -rwSr--r-- 1 frank frank 0 26 nov 19.56 test
>
> ~$ sudo chown root:root /home/frank/test
> ~$ ls -l test
> -rw-r--r-- 1 root root 0 26 nov 19.56 test
>
> As you can see the setuid bit of the "test" file has gone after running
> the "chown" command. The reason is explained here ¹ I'm interested in a
> workaround to prevent this behavior.
> Is it possible to change the group owner keeping the permissions of the
> file in its place?
>
> Thanks in advance, kind regards.
>
> ¹ https://unix.stackexchange.com/a/772336
> --
> Franco Martelli
>
Reply to: