6

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?

Snorex
  • 904
  • 12
  • 29
mohangraj
  • 9,842
  • 19
  • 59
  • 94
  • 1
    Possible duplicate of [setuid vs seteuid function](http://stackoverflow.com/questions/33076543/setuid-vs-seteuid-function) –  Oct 31 '15 at 06:37

1 Answers1

12

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.

Community
  • 1
  • 1
legends2k
  • 31,634
  • 25
  • 118
  • 222
  • Do you have any example to verify this? – mohangraj Oct 12 '15 at 09:48
  • Nope, I'm not on a *nix machine. – legends2k Oct 12 '15 at 09:49
  • 2
    I have a doubt in the above man page reference. Using setuid we can set the effective user id of the process. For Ex: setuid(getuid()); After this statement is executed, the effective userid of the process is changed to current user. So, to regain the root permission, I am simply use, setuid(0); But why the man page reference shows `afterward cannot use setuid(). You can accomplish this with seteuid(2)`. – mohangraj Oct 12 '15 at 10:18