4

I am learning linux suid,so I have written a small c program with the following content to test it

#include<stdio.h>
int main(){
system("echo 100 >> test.txt");
return 0;
}
-rwsr-xr-x 1 root root 8004 Sep 10 16:19 test

test.txt is a file which can only be modified by root

-rw-r----- 1 root root 

If I run the test program with a user account, it should add 100 to the empty file. But, it comes out:

sh:test.txt:Permission denied

Why?

3
  • What happens when you run the program as root?
    – Mikel
    Jan 24, 2015 at 17:02
  • If you change echo 100 >> test.txt to id -u, what does that print?
    – Mikel
    Jan 24, 2015 at 17:06
  • What is the output when you type /bin/sh --version ? Jan 24, 2015 at 17:52

2 Answers 2

2

Your scenario works perfectly here for me.

$ ls -l test*
-rwsr-xr-x 1 root  root  6776 Jan 24 17:18 test
-rw-r--r-- 1 chris chris   74 Jan 24 17:18 test.c
-rw-r----- 1 root  root     0 Jan 24 17:20 test.txt
$ ./test
ls -l test.txt
-rw-r----- 1 root root 4 Jan 24 17:21 test.txt
$ sudo cat test.txt
100

Is it possible that you're testing your program on a filesystem that does not permit setuid executables? Run the mount command and look for nosuid against the filesystem, such as here:

tmpfs on /tmp type tmpfs (rw,nosuid,nodev,noexec,relatime)
2
  • Did you do this in root account or other user account?
    – John
    Jan 24, 2015 at 18:23
  • An ordinary non-root account
    – roaima
    Jan 24, 2015 at 18:38
-3

The problem is, you call the function system(), which calls a shell /bin/sh. And the shell /bin/sh has no suid bit set. Thats why is prints the Permission denied message.

You have to write the part in pure c code:

int main() {
  FILE *fd = fopen("test.txt", "a");
  fprintf(fd, "%s", "100");
  fclose(fd);
  return 0;
}
1
  • 2
    I believe it's not so much that /bin/sh doesn't have the suid bit set as it is that the shell explicitly sets its UID back to the caller's real UID. Jan 24, 2015 at 21:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .