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

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


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

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

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)
  • Did you do this in root account or other user account?
    – John
    Jan 24 '15 at 18:23
  • An ordinary non-root account
    – roaima
    Jan 24 '15 at 18:38

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");
  return 0;
  • 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.
    – Scott
    Jan 24 '15 at 21:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.