What do the SUID and SGID bits do on files and on directories?
On an executable, SUID runs it with the owner's rights and SGID with the group's rights; on a directory, SGID makes new files inherit the directory's group, while SUID does nothing on Linux.
Normally a program runs with the rights of the user who starts it. The special bits change that.
| Bit | On an executable file | On a directory |
|---|---|---|
| SUID (4) | Runs with the owner's UID (often root) | Ignored on Linux |
| SGID (2) | Runs with the file's group | New files and subdirectories get the directory's group instead of the creator's primary group |
Why SUID exists: passwd must write /etc/shadow, which only root may change, yet every user may change their own password. So /usr/bin/passwd is owned by root with SUID set (-rwsr-xr-x), and the program itself makes sure that you can only change your own entry.
Why SGID on directories is useful: in a shared project folder owned by group devs, every new file automatically belongs to devs, so team members can work on each other's files without anyone running chgrp.
In ls -l the bits replace the execute position: s means the bit is set together with x, a capital S means it is set without x (usually a mistake).
Go deeper:
Wikipedia: setuid — SUID and SGID on files and directories, with the passwd example.