Search code examples
linuxpermissions

setuid trouble understanding


I read about setuid and I did'nt understand the term in 100%. As I undetstand: setuid allow users to run an executable with the file system permissions of the executable's owner or group respectively and to change behaviour in directories. (from Wikipedia).

But, I can't see a difference between:

-rwsr--r-- ::: you set to owner (rws is the owner) the setuid, so in other words you set to owner the owner permissions. so there is no effect, right?

-rwxr--r-- ::: is equal to the previous example, beacuse as I said, already talk about the owner so it's does'nt matter to add the owner the owner permissions.

THANKS FOR HELPS!


Solution

  • When you run a executable with setuid bit enabled, it is run with the identity of the owner instead the user that is running the executable. Thus, if you has a executable which the owner is root and the setuid is enabled, the executable will run as root instead the user that is running the executable.

    From man:

       setuid() sets the effective user ID of the calling process.  If
       the calling process is privileged (more precisely: if the process
       has the CAP_SETUID capability in its user namespace), the real
       UID and saved set-user-ID are also set.
    
       Under Linux, setuid() is implemented like the POSIX version with
       the _POSIX_SAVED_IDS feature.  This allows a set-user-ID (other
       than root) program to drop all of its user privileges, do some
       un-privileged work, and then reengage the original effective user
       ID in a secure manner.
    
       If the user is root or the program is set-user-ID-root, special
       care must be taken: setuid() checks the effective user ID of the
       caller and if it is the superuser, all process-related user ID's
       are set to uid.  After this has occurred, it is impossible for
       the program to regain root privileges.
    
       Thus, a set-user-ID-root program wishing to temporarily drop root
       privileges, assume the identity of an unprivileged user, and then
       regain root privileges afterward cannot use setuid().  You can
       accomplish this with seteuid(2).
    

    You can verify this with the following code:

    #include <stdio.h>
    #include <unistd.h>
    #include <stdlib.h>
    
    int main(void){
    
        int val;
        printf("The real user ID is %d\n", getuid());
        printf("The effective user ID is %d\n", geteuid());
    
        return 0;
    
    }
    

    Compile and setuid:

    gcc uid.c -o uid
    sudo chown root.root uid
    ls -la uid
    -rwxr-xr-x 1 root root 16712 Jul 10 11:59 uid
    ./uid                   
    The real user ID is 1000
    The effective user ID is 1000
    sudo chmod 4755 uid     
    ls -la uid         
    -rwsr-xr-x 1 root root 16712 Jul 10 11:59 uid
    ./uid              
    The real user ID is 1000
    The effective user ID is 0