Question

Lets add a new group and user and add it into system group video

$ sudo addgroup --system mydaemon
$ sudo adduser --system --no-create-home --ingroup mydaemon mydaemon
$ sudo adduser mydaemon video

Create a file and change its owner to root and group to video

$ touch video0
$ sudo chown root:video video0
$ sudo chmod 0660 video0

Now consider a simple application written in C using setgid() and setuid()

/* perms.c */
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <pwd.h>
#include <grp.h>


int main(int argc, char const *argv[])
{
    int ret;
    int gid;
    int uid;
    struct passwd *pw;
    struct group  *gr;

    pw = getpwnam("mydaemon");
    if (pw) {
        ret = setgid(pw->pw_gid);
        if (ret < 0) {
            printf("error with setgid\n");
            exit(1);
        }

        ret = setuid(pw->pw_uid);       
        if (ret < 0) {
            printf("error with setuid\n");
            exit(1);
        }
    }

    pw = getpwuid(getuid());
    gr = getgrgid(getgid());

    printf("gid: %d gr_name: %s\n", gr->gr_gid, gr->gr_name);
    printf("uid: %d user_name: %s\n", pw->pw_uid, pw->pw_name);

    ret = open("video0", O_RDWR);

    printf("open status: %d (errno %d)\n", ret, errno);

    return 0;
}

After compilation we can run it as normal user:

$ ./perms
error with setgid

It fails because we do not have permissions to setgid So run it directly as mydaemon:

$ sudo -u mydaemon ./perms
gid: 126 gr_name: mydaemon
uid: 116 user_name: mydaemon
open status: 3 (errno 0)

Fine, I can do setgid and setuid (I'm the same user) and I can open the file as expected

Now run it as root:

$ sudo ./perms
gid: 126 gr_name: mydaemon
uid: 116 user_name: mydaemon
open status: -1 (errno 13)

I can do setgid and setuid, getgid and getuid says that I'm running as mydaemon but I cant open the file. (errno 13 is EACCES: Permission denied)

Where is the problem?

Était-ce utile?

La solution

You should use initgroups() call to initialize groups according to group database.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top