Dropping root privileges

In order to drop all privileges (user and group), you need to drop the group before the user. Given that userid and groupid contains the IDs of the user and the group you want to drop to, and assuming that the effective IDs are also root, this is accomplished by calling setuid() and setgid():

if (getuid() == 0) {
    /* process is running as root, drop privileges */
    if (setgid(groupid) != 0)
        fatal("setgid: Unable to drop group privileges: %s", strerror(errno));
    if (setuid(userid) != 0)
        fatal("setuid: Unable to drop user privileges: %S", strerror(errno));
}

If you are paranoid, you can try to get your root privileges back, which should fail. If it doesn’t fail, you bailout:

 if (setuid(0) != -1)
     fatal("ERROR: Managed to regain root privileges?");

Also, if you are still paranoid, you may want to seteuid() and setegid() too, but it shouldn’t be necessary, since setuid() and setgid() already set all the IDs if the process is owned by root.

The supplementary group list is a problem, because there is no POSIX function to set supplementary groups (there is getgroups(), but no setgroups()). There is a BSD and Linux extension setgroups() that you can use, it this concerns you.

You should also chdir("https://stackoverflow.com/") or to any other directory, so that the process doesn’t remain in a root-owned directory.

Since your question is about Unix in general, this is the very general approach. Note that in Linux this is no longer the preferred approach. In current Linux versions, you should set the CAP_NET_BIND_SERVICE capability on the executable, and run it as a normal user. No root access is needed.

Leave a Comment