umask, setuid, setgid and sticky bit

Linux · Practical · 10 min

These bits explain permissions you will see on real systems and are essential for shared directories and security audits.

New files are created with mode 666 and directories with 777, minus the bits in your umask. The common umask 022 removes write for group and others, giving 644 files and 755 directories; 077 makes everything private. Set it in a shell profile, or per service with systemd's UMask=.

Three special bits form a fourth, leading octal digit:

  • setuid (4000, s in the user triplet): an executable runs with its owner's privileges. /usr/bin/passwd is setuid root so ordinary users can update /etc/shadow. Setuid programs are prime attack targets; audit them with find / -perm -4000.
  • setgid (2000, s in the group triplet): on a directory, new files inherit the directory's group instead of the creator's primary group, which is ideal for team folders. On executables it runs with the file's group.
  • sticky bit (1000, t in the others triplet): on a directory, users may delete only their own files even if the directory is world-writable. That is why /tmp is 1777.

A capital S or T means the special bit is set without the underlying execute bit.

When owner/group/other is not expressive enough, ACLs (setfacl -m u:bob:rw file, getfacl) grant permissions to additional users and groups; a + after the mode in ls -l signals an ACL.

Example

cd "$(mktemp -d)"
umask                            # 0022 -> new files 644, directories 755
(umask 077; touch private.txt; stat -c '%a %n' private.txt)   # 600 private.txt
ls -l /usr/bin/passwd            # -rwsr-xr-x 1 root root ...  (setuid root)
ls -ld /tmp                      # drwxrwxrwt ...  (sticky)
mkdir team && chmod 2775 team
stat -c '%A %a' team             # drwxrwsr-x 2775  (setgid directory)
chmod +t team && stat -c '%a' team   # 3775
find /usr/bin -perm -4000 -type f 2>/dev/null | head -n 3   # setuid binaries
# sudo setfacl -m u:bob:rw report.txt && getfacl report.txt  # per-user ACL

Remember

  • umask subtracts bits from 666/777 for new files and directories
  • setuid runs as the file owner; setgid dirs share a group; sticky protects others' files
  • ACLs grant extra users or groups access

Watch out for

  • Setting setuid on a shell script or an interpreter, which opens an easy privilege escalation.

Check yourself

  1. Why is /tmp mode 1777?
  2. With umask 027, what mode does a new regular file get?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: man7.org/linux/man-pages/man1/chmod.1.html

Builds on

Unlocks

Nothing builds on this yet.