I see such logic in many open source projects:
if (setuid() == 0) {
if (setgid(ccf->group) == -1) {
...
if (initgroups(ccf->username, ccf->group) == -1) {
I have 2 questions on this:
- What’s the benifit to change to another gid and uid?
- And what’s
initgroupsfor? IMO,to change gid and uid,setuid()andsetgid()will be enough.
Most of the time, system daemons are spawned by init scripts and therefore run as
root. Callingsetuid()andsetgid()allows them to drop their superuser privileges and impersonate another user on the system (generally far less powerful thanroot). That way, bugs and security holes become less lethal to the system.Concerning the second part of your question, initgroups() is called to reinitialize the group access list and add
ccf->groupto the list of groups thatccf->usernamebelongs to. That’s probably done because callingsetgid()is not sufficient for the access rights associated with the new group to be propagated to the process.