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.
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.
More than you'll want to know http://www.eecs.berkeley.edu/~daw/papers/setuid-usenix02.pdf
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;
}