문제

My task is to list all the groups that a user is a member of, for all users on the system. The idea is to go through /etc/passwd and for every user print its groups.

[EDIT] This did the trick:

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

Yet I'm still curious about the reason it's not working.

Output:

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

Code:

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

Any ideas?

도움이 되었습니까?

해결책

Once your program calls setuid() to switch to another user other than root, your program has given up its permission to switch users so subsequent calls will fail.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top