I have a C program to demonstrate the capability leak attack regarding set-uid.

// cap_leak.c
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>

void main()
    int fd;  char *v[2];  
    /* Assume that /etc/zzz is an important system file, and it is owned by root with permission 0644. Before running this program, you should create the file /etc/zzz first. */  

    fd = open("/etc/zzz", O_RDWR | O_APPEND);

    // Print out the file descriptor value  
    printf("fd is %d\n", fd);    
    if (fd == -1) 
        printf("Cannot open /etc/zzz\n");     
    // Permanently disable the privilege by making the  
    // effective uid the same as the real uid  
    printf("Real user id is %d\n", getuid());    
    printf("Effective user id is %d\n", geteuid());    

    // Execute /bin/sh  
    v[0] = "/bin/sh"; v[1] = 0;  
    execve(v[0], v, 0);        

Originally, cat /etc/zzz gives:

this is a very important file

Now I compile this program:

gcc -o cap_leak cap_leak.c

Change the owner to root and turn the setuid bit on:

sudo chown root cap_root
sudo chmod 4755 cap_root

Now when I run the program from a normal user, I get a shell prompt:

fd is 3
Real user id is 1000
Effective user id is 1000
$echo bbbbbb >&3
$cat /etc/zzz
$this is a very important file

The last write to fd = 3 i.e, /etc/zzz is successful, although after opening the file the setuid() function is called which basically sets the real, effective and saved uid to the original uid. My question is, why the last write is successful even though it is performed after setuid() and to prevent capability leak in this case, where should the setuid() be placed and why?


There is no other place you should put the setuid(), you should not leave the file open for write.

The reason for that is that the permissions are checked when the file is opened, not at every write() call.

There is no reason to leave the file open with write access if the unprivileged shell is not supposed to write to that file.

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.