How to remove setgid (linux/unix)?

Well would just like to add few points to clarify the approach of working with the numerical way for both files and directories.

  • Adding individual special permissions for either user/group/others.

chmod "X"755 file

Where X is the specific octal numeric mode for special permissions.

  • If you want to add multiple special permissions at a time, e.g. for both suid(4) and sgid(2) i.e. 4+2=6.

chmod "6"755 file

for suid(4), sgid(2) and sticky bit(1), i.e. 4+2+1=7

chmod "7"755 file

  • Deleting all special permissions (only applicable for a file)

chmod 00"0"755 file

Well, the trailing zeros before 4 digits doesn't add any values while changing the permission for a file but it does add values while changing permission for a directory.

The above numeric code will change the permission to 755 from 7755 only for a file but if you do the same for a directory it will be 6755 as it will only remove the sticky bit for others.

To remove all the special permissions for a directory.

chmod "000"755 file

  • Similarly, to remove suid permission and having sgid(2) and sticky bit(1) i.e. 2+1=3.

chmod 00"3"755 file

And solution using letters(r,w,x,X,s,,t) and operators(+/-) were already discussed and approved in the earlier answers.


Regarding: "you can set (but not clear) the bits with a numeric mode"

On RHEL 7 chmod 0644 $filename did not remove the setuid(4),setgid(2) or sticky(1).

However precedeing with an extra 0 did the trick:

chmod 00644 $filename


Change the + for adding a permission into a - to remove it:

sudo chmod g-s filename

If you want to do this programatically, you’ll need to use some bitwise operators. Normally it’s

mode_without_suid = bitwise_and(existing_mode, bitwise_not(S_ISUID))

where S_ISUID is 0o4000, a constant that uses mode bits above the typical rwx ones of something like 0644.

For example, in python

import os
import stat

def mode_details(m):
    return f"mode={oct(m)} = {stat.filemode(m)}"

mode = os.stat('foo').st_mode
print("old mode", mode_details(mode))

new_mode = mode & ~stat.S_ISUID

os.chmod('foo', new_mode)
print("new mode", mode_details(new_mode))

which prints

old mode mode=0o104654 = -rwSr-xr--
new mode mode=0o100654 = -rw-r-xr--

To remove setgid the numerical way the command is

sudo chmod 0664 $filename

The assumption here is the permission on file is 664 and we are not changing it. The left most bit in the above command represents setuid(4),setgid(2) and sticky(1). Now to represent these symbolically setuid is u+s, setgid is g+s and sticky is o+t

Example 1:-chmod u+s filename This will setuid for the filename mentioned that is rwsr_xr_x

Example 2: chmod 2770 directory This will set gid for the directory mentioned that is rwxr_sr_x

Tags:

Linux

Unix