62

I have a daemon which gets started as root (so it can bind to low ports). After initialisation I'd very much like to have it drop root privileges for safety reasons.

Can anyone point me at a known correct piece of code in C which will do this?

I've read the man pages, I've looked at various implementations of this in different applications, and they're all different, and some of them are really complex. This is security-related code, and I really don't want to reinvent the same mistakes that other people are making. What I'm looking for is a best practice, known good, portable library function that I can use in the knowledge that it's going to get it right. Does such a thing exist?

For reference: I'm starting as root; I need to change to run under a different uid and gid; I need to have the supplementary groups set up correctly; I don't need to change back to root privileges afterwards.

3
  • 7
    This varies quite a bit between unixes - are there any in particular ? If you need a "portable" solution, it's going to be messy, and you're best off grabbing e.g. the permanently_set_uid() function from OpenSSH - in the uidswap.c file
    – nos
    Jul 28, 2010 at 22:05
  • 1
    Maybe a better strategy, don't require root so it does not need to be dropped. Also see Allow non-root process to bind to port 80 and 443? A related topic is Setuid Demystified bye Chen, Dean and Wagner. Different flavors of Unix have slightly different behaviors. Its another reason to punt and allow your unprivileged process to bind to the port.
    – jww
    Jan 2, 2019 at 9:30
  • Also see Setuid Demystified on Usenix.
    – jww
    Jun 26, 2019 at 14:41

3 Answers 3

50

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("/") 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.

7
  • 1
    You'd want to set the gid as well - and this might vary slightly across unixes regarding wether setuid/setgid actually messes with the real and saved id's as well
    – nos
    Jul 28, 2010 at 22:06
  • 2
    This does indeed need to be a portable solution, so no Linux capability fu allowed, I'm afraid. And I have indeed tried the simple approach with setuid() and setgid(); it doesn't set the groups correctly (and if you don't call setgroups(), apparently you can end up still being a member of some of root's groups!). Jul 28, 2010 at 22:14
  • @nos Thanks. Expanded to cover groups. If the process is owned by root (as the OP mentioned) or if it is setuid-root, then setuid() and setgid() already set all IDs (real, effective and saved). This is in the specification. Otherwise, the implementation would not be POSIX-conforming.
    – Juliano
    Jul 28, 2010 at 22:59
  • 4
    You can use initgroups(3) to reset the supplementary groups, it's portable enough (at least BSD and GNU libc have it). Mar 18, 2012 at 13:57
  • 3
    Always clear the supplemental groups as well. initgroups exists on AIX, Solaris, HP-UX, FreeBSD, Darwin, Linux, and probably others. Include it so the build fails if it can't be found. Not dropping all groups can lead to serious system compromise and CVEs. I don't think chdir has any security implications at all, does it? Feb 22, 2013 at 23:04
19

You're looking for this article:

POS36-C. Observe correct revocation order while relinquishing privileges

Not sure how to best put some information there without duplicating the content of that page ...

3
3

This was what I could do best:

#define _GNU_SOURCE  // for secure_getenv()


int drop_root_privileges(void) {  // returns 0 on success and -1 on failure
    gid_t gid;
    uid_t uid;

    // no need to "drop" the privileges that you don't have in the first place!
    if (getuid() != 0) {
        return 0;
    }

    // when your program is invoked with sudo, getuid() will return 0 and you
    // won't be able to drop your privileges
    if ((uid = getuid()) == 0) {
        const char *sudo_uid = secure_getenv("SUDO_UID");
        if (sudo_uid == NULL) {
            printf("environment variable `SUDO_UID` not found\n");
            return -1;
        }
        errno = 0;
        uid = (uid_t) strtoll(sudo_uid, NULL, 10);
        if (errno != 0) {
            perror("under-/over-flow in converting `SUDO_UID` to integer");
            return -1;
        }
    }

    // again, in case your program is invoked using sudo
    if ((gid = getgid()) == 0) {
        const char *sudo_gid = secure_getenv("SUDO_GID");
        if (sudo_gid == NULL) {
            printf("environment variable `SUDO_GID` not found\n");
            return -1;
        }
        errno = 0;
        gid = (gid_t) strtoll(sudo_gid, NULL, 10);
        if (errno != 0) {
            perror("under-/over-flow in converting `SUDO_GID` to integer");
            return -1;
        }
    }

    if (setgid(gid) != 0) {
        perror("setgid");
        return -1;
    }
    if (setuid(uid) != 0) {
        perror("setgid");
        return -1;    
    }

    // change your directory to somewhere else, just in case if you are in a
    // root-owned one (e.g. /root)
    if (chdir("/") != 0) {
        perror("chdir");
        return -1;
    }

    // check if we successfully dropped the root privileges
    if (setuid(0) == 0 || seteuid(0) == 0) {
        printf("could not drop root privileges!\n");
        return -1;
    }

    return 0;
}
1
  • I think the first check should call geteuid() since getuid() returns the real uid. Sep 14, 2022 at 8:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.