Part 6 of 7 · 3 min read
Dropping privilege
Dropping privilege
Think of a surgeon who scrubs, uses a sharp tool for one cut, and puts it away at once. Keeping the tool in hand would be dangerous. The analogy stops in one place: a surgeon can pick the tool up again, while a process that drops root for good cannot.
In plain words: A program that starts with high rights should do only what needs them and then give them up. The calls setuid, setgid and setgroups change the IDs. A process running as root that calls setuid(n) for a non-zero n drops all of its root rights for good: the real, effective and saved IDs all change, so it cannot get back. A process that only calls seteuid can switch back, because the saved user ID still holds root. The order also matters: change the group first, then the user, since after the user ID is dropped the process may lack the right to change groups. The test program of section 2 follows this order: setgroups, then setgid, then setuid.
A worked example (made up to show the idea). A web server starts as root to open port 80. It then calls setgroups(0, NULL), setgid(33) and setuid(33), in that order, and from then on serves requests as user 33. A flaw in the request code now gives an attacker the rights of user 33 only. If the server had kept root, the same flaw would give the attacker the whole machine.
The key lines. The check after dropping is simple and worth keeping: try to call setuid(0) and make sure it fails. Tests like this catch the common error of dropping the effective ID but not the saved one.
Dropping privilege
Dropping privilege is the practice of giving up unneeded rights early in a process's life, by switching to an unprivileged user and group, in the order groups, then group ID, then user ID. A complete drop changes the real, effective and saved user IDs so that the rights cannot be regained.
Example: setgroups(0, NULL); setgid(33); setuid(33); in a server that has opened its port.
Check yourself:
1. In which order are the groups, the group ID and the user ID dropped?
2. Why is seteuid not a complete drop?
3. What check proves that a drop was complete?
Words you will meet
| Word | Meaning |
|---|---|
| uid / gid | Numbers that name a user and a group. |
| Mode | The permission bits of a file. |
| umask | Bits removed from the mode of new files. |
| Sticky bit | Only the owner may delete files in the directory. |
| Setuid | Run with the file owner's user ID. |
Quick notes
- The kernel uses numbers. Root has uid 0.
- A mode has nine bits: owner, group, other. The kernel applies only the first class that matches.
- New mode = requested AND NOT umask.
- On directories: r lists, w changes entries, x lets you pass through. Sticky protects other users' files.
- Setuid sets the effective user ID to the file owner's.
no_new_privsswitches it off. - Drop privilege early: groups, then gid, then uid.
setuiddrops for good,seteuiddoes not.