msgbartop
Adam Palmer MBCS CITP, Linux, PHP Programmer, MySQL Developer, Embedded Hardware, Security Consultant
Did my blog help you? Please link to me!
  dns test
 
RSS Feed
msgbarbottom

03 Oct 09 Linux C setuid setgid tutorial

Here’s a very brief example of how to use setuid() and setgid() functions in your C program.

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main(void)
{

int current_uid = getuid();
printf(”My UID is: %d. My GID is: %d\n”, current_uid, getgid());
system(”/usr/bin/id”);

if (setuid(0))
{

perror(”setuid”);
return 1;

}

//I am now root!
printf(”My UID is: %d. My GID is: %d\n”, getuid(), getgid());
system(”/usr/bin/id”);

//Time to drop back to regular user priviledges
setuid(current_uid);
printf(”My UID is: %d. My GID is: %d\n”, getuid(), getgid());
system(”/usr/bin/id”);

return 0;

}

The program above should be pretty self explainatory, now:

adam@staging:~$ gcc -O2 -ggdb -o setuid setuid.c
adam@staging:~$ ls -al setuid
-rwxr-xr-x 1 adam adam 9792 2009-10-03 18:09 setuid
adam@staging:~$


Trying to run the application now will result in:

adam@staging:~$ ./setuid
My UID is: 1000. My GID is: 1000
uid=1000(adam) gid=1000(adam) groups=20(dialout),24(cdrom),25(floppy),29(audio),44(video),46(plugdev),1000(adam)
setuid: Operation not permitted

The setuid(0) call fails, as the application does not have permission to gain root access.

adam@staging:~$ su – root
Password:
staging:~# cd /home/adam
staging:/home/adam# chown root.root setuid
staging:/home/adam# chmod +s setuid
staging:/home/adam# ls -al setuid
-rwsr-sr-x 1 root root 9792 2009-10-03 18:09 setuid
staging:/home/adam# exit
logout
adam@staging:~$

And now:

adam@staging:~$ ./setuid
My UID is: 1000. My GID is: 1000
uid=1000(adam) gid=1000(adam) euid=0(root) egid=0(root) groups=20(dialout),24(cdrom),25(floppy),29(audio),44(video),46(plugdev),1000(adam)
My UID is: 0. My GID is: 1000
uid=0(root) gid=1000(adam) egid=0(root) groups=20(dialout),24(cdrom),25(floppy),29(audio),44(video),46(plugdev),1000(adam)
My UID is: 1000. My GID is: 1000
uid=1000(adam) gid=1000(adam) egid=0(root) groups=20(dialout),24(cdrom),25(floppy),29(audio),44(video),46(plugdev),1000(adam)
adam@staging:~$

Works just as expected!

Now:

adam@staging:~$ rm -f setuid setuid.c

We don’t want to leave things like that lying around…

Tags: , , , , ,



Leave a Comment