There are 3 ways to change user of a process in Unix.
2 system level ways to change user of a process
- if the process has capability CAP_SETUID, traditionally root has this capability (and all other capabilities), then it can use
setfsuid, system calls, to change to any other user. Any other user can shuffle uids: A process has 3 uids, it can move them around, at will: it can swap them, or remove them until it is down to one. It can not add
uids, unless it has capability CAP_SETUID. In general a process can only loose privileges or move them around, using these system calls. These calls allow the program to continue.
suid executable: If an executable file has its
suid bit set, and if it is of a valid type (not a scripts, not java, not …), then when it is run, its effective user id is changed to that of the files owner. (same can be done for group with
sgid bit). This is the only way to gain privileges. The current program ends when
exec is called, it is replaced with the new program, but it is the same process, it also inherits open files (e.g. stdin, stdout, stderr).
fork dose not change user.
A forked process is an exact duplicate of its parent, with a few exceptions (see
man fork). In particular the uid, gid, and capabilities are not changed.
These programs use the 2 system methods described above.
su will ask for the password of the other user.
sudo will ask for your password, but will only work if you are registered in the
cron etc use the 2 system methods. (And will create a new process. The other system methods do not create a new process.)
#↳ ll /usr/bin/sudo
-rwsr-xr-x 1 root root 155K Sep 9 2017 /usr/bin/sudo*
As use can see the
sudo executable is owned by root, and has the suid bit set (the
s, where you would expect to see the first
sudo is run, it runs as root (don't try this, unless you know what you are doing). It then does security checks. Then it uses
set??uid to become the required user, it then
execs (and maybe a fork) the required program.
Running a process, without logging in
Use some timed start service.
Send a network message, e.g. a web-server may run a task in response to a web request.
Use automated login: use
ssh to launch a process, via a script on another machine.