I was asked, what is the correct way to drop privileges in Linux.
So here is a list of things I usually do, when implementing unprivileged sub process:
- fork
- in some cases you would also want to do these:
- clear the environment(leave only the required variables)
- close all file descriptors(except the ones you need)
- clear memory regions that are not supposed to be accessible by the child
- change the inheritable capabilities
- change namespaces or control groups
- clear all groups
- chroot, if it is used(I suggest using it)
- setgid
- setuid
In certain cases it may be a good idea to also call setsid() in the child, so your child will become a session leader.