Previous Section  < Day Day Up >  Next Section

Recipe 9.7. Setting Up a Shared Directory with setgid and the Sticky Bit

9.7.1 Problem

Your users need a directory for sharing files, and you want all the shared files to belong to the same group.

9.7.2 Solution

Use the setgid bit to automatically set the shared group ownership on files.

This is how to set it with octal notation:

# chmod -v 2775 /shared-directory

You can also use symbolic notation:

# chmod -v +s /shared-directory

Keep in mind that +s sets both the setgid and setuid bits, which could be a security problem if executables or scripts are stored in this directory. chmod 2775 sets only the setgid bit.

setuid is a big fat security hole. Do not use it on executables. Programs that use it, such as /usr/bin/passwd, have safeguards built in to prevent privilege escalation and other mischief. If there are scripts that you want users to run, create a group for that purpose.


Add the sticky bit to prevent anyone but the file owner from deleting the file, by using:

# chmod +t /shared-directory

or:

# chmod 3775 /shared-directory

9.7.3 Discussion

Any files created in the directory will have the same group owner as the directory. Any files copied into the directory will retain their original group ownership. Users must belong to a common group to access the directory. Files created in the directory will have permissions as determined by the umasks of the file owners.

A classic example of a directory making canny use of the sticky bit is /tmp:

$ stat /tmp

...

Access: (1777/drwxrwxrwt)  Uid: (  0/  root)  Gid: (  0/    root)

/tmp needs to be world-readable and writable, but we do not want users or processes deleting temp files that do not belong to them. So the sticky bit takes care of that.

The setuid bit lets users run a command with the same permissions as the file owner. This is how ordinary users are able to change their own passwords, even though /etc/passwd can only be written to by root:

$ stat /usr/bin/passwd

  File: `/usr/bin/passwd'

  Size: 26584    Blocks: 56    IO Block: 4096   regular file

...

Access: (4755/-rwsr-xr-x) Uid: ( 0/ root) Gid: ( 0/  root)

9.7.4 Discussion

Sticky bits have one other use. A long time ago, setting the sticky bit on an executable kept it in memory after execution had finished. In the olde Unix days of less sophisticated memory management and feebler hardware, this made programs start faster. These days, don't bother—it won't do a thing.

9.7.5 See Also

    Previous Section  < Day Day Up >  Next Section