Search code examples
cunixbindrootsetuid

What's the proper way to drop to a lower privilege level with setuid?


I'm writing a program in C that binds to a port < 1024. I'd like it to run at non-root privileges thereafter.

I know I need to call setuid(), but with what argument? UID's vary from system to system.


Solution

  • You can use getpwnam() to look up a users uid/gid by name:

    #include <sys/types.h>
    #include <unistd.h>
    #include <pwd.h>
    
    int changepriv(const char *user) {
      struct passwd *pw;
      int rv;
    
      pw = getpwnam(user);
      if (!pw)
        return -1;
    
      rv = setgid(pw->pw_gid);
      if (rv == -1)
        return -2;
    
      rv = setuid(pw->pw_uid);
      if (rv == -1)
        return -3;
    
      return 0;
    }