-1

I have the following program:

$ cat cat.c
#include <err.h>
#include <stdlib.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
  char buf[32];

  if(argc == 1) {
    errx(1, "please specify an argument.");
  }

  sprintf(buf, "cat %s", argv[1]);
  system(buf);
  return 0;
}
$ gcc cat.c -o mycat
$ chmod +s mycat; sudo chown root mycat
$ ls -lth mycat
-rwsr-sr-x 1 root ... 11:12 mycat
$ ls -lth secret
-rw------- 1 root ... 11:10 secret

I thought ./mycat secret should be able to read the secret file because mycat is a setuid program, and its owner is root. However, here is what I get:

$ ./mycat secret
cat: secret: Permission denied
$ sudo chown user1 secret
$ ./mycat secret
4ea6f17dd6818

Anything I misunderstood?

xiaogw
  • 653
  • 8
  • 18
  • It does have the privilege to execute `system()`. It is `cat` that doesn't have the privilege to read `secret`. Read the error message. – user207421 Aug 28 '23 at 00:30
  • @user207421 Permissions aren't associated with programs, they're associated with users and groups. Running setuid root should give it privilege to read the file. – Barmar Aug 28 '23 at 02:34
  • 1
    The reason is that `/bin/sh` drops its setuid privileges. – Barmar Aug 28 '23 at 02:34
  • This is similar to https://stackoverflow.com/questions/33565729/why-do-my-setuid-root-bash-shell-scripts-not-work – Barmar Aug 28 '23 at 02:36

1 Answers1

2

This program demonstrates what's working and what doesn't :

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
  char buf[64];
  if (fork() == 0){
    char *newargv[] = { "cat", argv[1], NULL };
    execve("/usr/bin/cat", newargv, NULL); // This call directly `cat` without spawning a `shell`, so works as expected.
    return 0;
  }
  sprintf(buf, "cat %s", argv[1]);
  system(buf); // `system` spawns a shell which then calls `cat`, as the `shell` lost setuid privilaege, `cat` fails with `Permission denied`.
  return 0;
}
Philippe
  • 20,025
  • 2
  • 23
  • 32
  • I found if I execve("/bin/sh", ...); and use setuid to the program, the launched shell is not in root privileged. Is this because setuid cannot be applied to any shell-related programs? – xiaogw Aug 29 '23 at 03:11