Part 5 of 7 · 3 min read
Setuid
Think of a bank clerk who has a key to the vault. A customer cannot enter, but the clerk will fetch one item for the customer and no more. The customer gains no key. The analogy stops in one place: a clerk is a person who can refuse, while a setuid program does what its code says, including by mistake.
In plain words: Some tasks need more rights than the user who asks, such as changing one's own password in a file that only root can write. For this Unix has the setuid bit. When a program whose file has this bit is executed, the process gets the file owner's user ID as its effective user ID, while its real user ID stays that of the caller. The kernel uses the effective ID for permission checks. The s in -rwsr-xr-x shows the bit, and /usr/bin/passwd on the test machine has it, owned by root. The same exists for groups as setgid.
A worked example. This program prints its real and effective IDs.
#include <stdio.h>
#include <unistd.h>
int main(void) {
printf("real uid %u, effective uid %u\n", getuid(), geteuid());
return 0;
}
I ran it as the user nobody before and after making it setuid root:
plain: real uid 65534, effective uid 65534
setuid root: real uid 65534, effective uid 0
setuid root, no_new_privs: real uid 65534, effective uid 65534
With the bit set, the process runs with effective user 0 although the caller is nobody. The third run used setpriv --no-new-privs. This sets the kernel flag no_new_privs, which tells the kernel never to give a process more rights through execve, so the setuid bit had no effect. The flag cannot be cleared once set. It is the base of many sandboxes (page 6).
The key lines. A setuid program is a part of the system's boundary, and any flaw in it is a flaw in the system. It must trust nothing from the caller: environment variables, arguments, the current directory and open files. Good setuid programs do their privileged work and drop the extra rights as early as possible, for example with seteuid(getuid()).
Setuid
The setuid bit on an executable file makes a process that executes it run with the file owner's user ID as its effective user ID, while its real user ID stays that of the caller. The kernel uses the effective ID for permission checks, so the program can do what only its owner could do.
Example: /usr/bin/passwd is owned by root with the setuid bit, so an ordinary user can use it to change a password stored in a root-only file.
Interview angle
A common question is "What is the difference between the real and the effective user ID, and why does setuid exist?" A good answer says that the real ID is who started the process and the effective ID is who the kernel checks, that setuid sets the effective ID to the file owner, and that it is a risk that is cut by least privilege and no_new_privs.
Check yourself:
1. What does the s in -rwsr-xr-x mean?
2. Which ID does the kernel use for permission checks?
3. What does no_new_privs change in the example?