Derrick
Derrick

Reputation: 2366

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.

Upvotes: 2

Views: 758

Answers (2)

sth
sth

Reputation: 229754

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;
}

Upvotes: 1

user173973
user173973

Reputation:

More than you'll want to know http://www.eecs.berkeley.edu/~daw/papers/setuid-usenix02.pdf

Upvotes: 3

Related Questions