Special Permissions — setuid, setgid, sticky bit
rwx for owner, group and others covers most files. Three more bits handle what they can't:
| Bit | On a program | On a folder | In ls -l | Number |
|---|---|---|---|---|
| setuid | runs as the file's owner | — | s in the owner's x | 4000 |
| setgid | runs with the file's group | new files get the folder's group | s in the group's x | 2000 |
| sticky | — | only a file's owner may delete it | t in the others' x | 1000 |
setuid: how passwd writes /etc/shadow
You can change your own password — but passwords live in /etc/shadow, which only root may write. How?
ls -l /usr/bin/passwd
-rwsr-xr-x 1 root root 118168 Oct 2 16:08 /usr/bin/passwd
The s where the owner's x would be is setuid: whoever starts passwd, it runs as its owner — root. Every such program is a door into root, so admins keep an eye on the list:
find /usr/bin -perm -4000
⚠️ Never put setuid on a script or on a program you wrote. A capital
Smeans the bit is set butxisn't — usually a mistake.
setgid on a folder: a team folder
Normally a new file gets the group of whoever made it. In a team folder that's wrong: everything there should belong to the team. With setgid on the folder, everything made inside gets the folder's group:
sudo groupadd devs
sudo mkdir /srv/shared
sudo chgrp devs /srv/shared
sudo chmod 2775 /srv/shared
ls -ld /srv/shared
drwxrwsr-x 2 root devs 4096 Nov 1 10:00 /srv/shared
2775 is setgid (2) in front of rwxrwxr-x; with letters it's chmod g+s. Now:
sudo touch /srv/shared/plan.txt
ls -l /srv/shared
-rw-r--r-- 1 root devs 0 Nov 1 10:01 plan.txt
root made it — but its group is devs, the folder's. New subfolders get the setgid bit too, so it works all the way down.
The sticky bit: /tmp
Everyone may write in /tmp. So what stops one user from deleting another's files?
ls -ld /tmp
drwxrwxrwt 9 root root 4096 Nov 1 09:58 /tmp
The t at the end: in a sticky folder only a file's owner (or the folder's owner, or root) may delete or rename it. chmod +t sets it.
In numbers
The extra digit goes in front: chmod 4755 (setuid), chmod 2775 (setgid), chmod 1777 (sticky), chmod 3775 (setgid + sticky).
💡
chmod 755on a folder keeps its setgid bit — chmod protects it on purpose. To take it off:chmod g-s.