简体   繁体   中英

Difference between setuid and seteuid function

Program 1: Example with setuid()

    #include<stdio.h>
    #include<sys/types.h>
    #include<unistd.h>
    void main()
    {
        printf("Real user id = %d, Effective User id = %d\n",getuid(),geteuid());
        setuid(1000);
        printf("Real user id = %d, Effective User id = %d\n",getuid(),geteuid());
        setuid(1014);
        printf("Real user id = %d, Effective User id = %d\n",getuid(),geteuid());
    }

Output:

    guest $ ./a.out 
    Real user id = 1000, Effective User id = 1014
    Real user id = 1000, Effective User id = 1000
    Real user id = 1000, Effective User id = 1014
    guest $

Program 2: Example with seteuid()

    #include<stdio.h>
    #include<sys/types.h>
    #include<unistd.h>
    void main()
    {
        printf("Real user id = %d, Effective User id = %d\n",getuid(),geteuid());
        seteuid(1000);
        printf("Real user id = %d, Effective User id = %d\n",getuid(),geteuid());
        seteuid(1014);
        printf("Real user id = %d, Effective User id = %d\n",getuid(),geteuid());
    }

Output:

    guest $ ./a.out 
    Real user id = 1000, Effective User id = 1014
    Real user id = 1000, Effective User id = 1000
    Real user id = 1000, Effective User id = 1014
    guest $

Both programs give the same output. So, what is the difference between these two functions? As per the reference (man page), both functions are used to set the effective user ID of the process. Where does the functionality differ between these two programs?

The documentation is pretty clear about the difference:

If the user is root or the program is set-user-ID-root, special care must be taken. The setuid() function 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM