0

I have the following c program.

$ cat main.c
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc, char *argv[]) {
    int fd;
    if((fd = open(argv[1], O_RDONLY)) == -1) {
        perror("open");
        return 1;
    }

    if(close(fd) == -1) {
        perror("close");
        return 1;
    }
    return 0;
}

But I got the following error.

touch tmpfile
sudo chown root tmpfile
sudo chown root ./main_prog
sudo setcap cap_setuid+ep ./main_prog # There will be no error if I use sudo chmod u+s
./main_prog tmpfile
open: Permission denied

Could anybody show me how to use setcap for setuid?

1 Answers1

0

What you are trying to do is access a file you need privilege to access. The cap_setuid capability does not directly grant this privilege - it grants the process the privilege to change its own UID(s). You can get there via this path, but it requires more code in your program.

The capability you want for your use case is one to override the discretionary access control: cap_dac_override.

With your ./main_prog as written, try this instead:

$ touch tmpfile
$ sudo chown root.root tmpfile
$ sudo chmod go-r tmpfile
$ ls -l tmpfile
-rw------- 1 root root 0 Apr  9 08:02 tmpfile
$ cat tmpfile
cat: tmpfile: Permission denied
$ sudo setcap cap_dac_override=ep ./main_prog
$ ./main_prog tmpfile
$ echo $?
0

Note, with capabilities, there is no need for main_prog to be owned by root.

Tinkerer
  • 865
  • 7
  • 9