Linux – Howto prevent chgrp from clearing “setuid bit”

chgrplinuxsetuid

We have RH based Linux images; on which I have to "apply" some "special archive" in order to upgrade them to the latest development version of our product.

The person creating the archive figured that within our base image, some permissions are wrong; so we were told to run

sudo chgrp -R nobody /whatever

We did that; and later on, when our application is running, obscure problems came up.

What I found later on: the call to chgrp will clear the setuid bit information on our binaries within /whatever.

And the actual problem is: some of our binaries must have that setuid bit set in order to function properly.

Long story short: is there a way to run that "chgrp" command without killing my setuid bits?

I just ran the following on my local Ubuntu; leading to the same result:

mkdir sticky
cd sticky/
touch blub
chmod 4755 blub 
ls -al blub 

–> shows me file name with red background –> so, yep, setuid

chgrp -R myuser .
ls -al blub 

–> shows me file name without red background –> setuid is gone

Best Answer

If you want to implement your chgrp -R nobody /whatever while retaining the setuid bit you can use these two find commands

find /whatever ! -type l -perm -04000 -exec chgrp nobody {} + \
                                      -exec chmod u+s {} +
find /whatever ! -type l ! -perm -04000 -exec chgrp nobody {} +

The find ... -perm 04000 option picks up files with the setuid bit set. The first command then applies the chgrp and then a chmod to reinstate the setuid bit that has been knocked off. The second one applies chgrp to all files that do not have a setuid bit.

In any case, you don't want to call chgrp or chmod on symlinks as that would affect their targets instead, hence the ! -type l.