csetuid

Set owner of the new created file in C


I have a program write.c, which creates a new file. I compiled that through root user and set the sticky bit for setuid using chmod u+s write.

Now, if a user2 executes this program. A new file is created with the root as owner, why ? The owner of the file should be user2. For that, I changed the uid using setuid() and seteuid() to user2. And then created the file. But this also creates the file with root as owner. I want to create the file as user2 as owner.


Solution

  • Post an mcve. What you describe works just fine on my system. This:

    #!/bin/sh -e
    
    cat > main.c <<EOF
    #define _GNU_SOURCE
    #include <unistd.h>
    #include <fcntl.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <stdio.h>
    #include <stdlib.h>
    int main(int argc, char** argv)
    {
    
        int fd;
        uid_t ruid,euid,suid;
        struct stat sb;
        getresuid(&ruid,&euid,&suid);
        printf("ruid=%ld euid=%ld suid=%ld\n", (long)ruid,(long)euid,(long)suid);
    
        if(0>(fd = open(argv[1], O_CREAT|O_RDWR, 0660))){
            perror(0); 
            exit(1);
        }
        fstat(fd,&sb);
        printf("owner=%ld\n", (long)sb.st_uid);
    
        close(fd);
        seteuid(ruid);
        getresuid(&ruid,&euid,&suid);
        printf("ruid=%ld euid=%ld suid=%ld\n", (long)ruid,(long)euid,(long)suid);
    
        if(0>(fd = open(argv[2], O_CREAT|O_RDWR, 0660))){
            perror(0); 
            exit(1);
        }
        fstat(fd,&sb);
        printf("owner=%ld\n", (long)sb.st_uid);
    
        close(fd);
    }
    EOF
    
    gcc main.c  
    sudo chown root a.out  
    sudo chmod u+s a.out
    rm -f roots mine  
    ./a.out roots mine
    

    gets me:

    ruid=1008 euid=0 suid=0
    owner=0
    ruid=1008 euid=1008 suid=0
    owner=1008
    

    i.e., the seteuid call succesfully resets my uid and the second file is no longer owner by root.