开发者

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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜