سؤال

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