setgid():不允许操作

时间:2014-05-11 12:00:56

标签: c unix

我的任务是列出系统中所有用户的所有用户所属的组。我们的想法是通过/etc/passwd并为每个用户打印其组。

[编辑]这就是诀窍:

if( getgrouplist(passwd->pw_name, passwd->pw_gid,
                    groups, &ngroups) < 0)
  error_fatal ("getgrouplist ()");

然而,我仍然对它不工作的原因感到好奇。

输出:

User root is a member of: root
User daemon is a member of: root
setgid(): Operation not permitted

代码:

while ((passwd = getpwent ()) != NULL) {
    uid = passwd->pw_uid;
    gid = passwd->pw_gid;

    if (setgid(gid) < 0)
        error_fatal ("setgid()");

    if (setuid(uid) < 0)
        error_fatal ("setuid()");

    if((ngroups = getgroups (0, NULL)) < 0)
        error_fatal ("getgroups ()");

    if((groups = (gid_t *) malloc (sizeof (gid_t) * ngroups)) < 0)
        error_fatal ("malloc ()");

    if (getgroups (ngroups, groups) < 0)
        error_fatal ("getgroups ()");

    printf ("User %s is a member of: ", passwd->pw_name);
    for (i = 0; i < ngroups; i++) {
        gid = groups[i];
        if((group = getgrgid (gid)) == NULL)
            error_fatal ("getgrgid ()");
        printf ("%s ", group->gr_name);
    }
    putchar ('\n');
}

有什么想法吗?

1 个答案:

答案 0 :(得分:3)

一旦您的程序调用{​​{1}}切换到setuid()以外的其他用户,您的程序就会放弃切换用户的权限,以便后续调用失败。