如何让程序临时获得root权限代码

使用getuid()/setuid()函数,让程序临时获得root权限代码:

/* 
 * gcc -g -o test-uid test-uid.c
 * chown root.root ./test-uid
 * chmod 4755 ./test-uid
 * ls -al /var
 * */
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
int
main(int argc, char **argv)
{
  // save user uid
  uid_t uid = getuid();
  // get root authorities
  if(setuid(0)) {
        printf("test-uid: setuid error");
        return -1;
  }
  printf("test-uid: run as root, setuid is 0\n");
  system ("touch /var/testroot");

  // rollback user authorities
  if(setuid(uid)) {
        printf("test-uid: setuid error");
        return -1;
  }
  printf("test-uid: run as user, setuid is %d\n", uid);
  system ("touch /var/testuser");

  return 0;
}

编译后,使用socol用户,执行test-uid程序获取临时root权限在/var目录下建立testroot 文件:

[socol@localhost test]$ gcc -g -o test-uid test-uid.c

[socol@localhost test]$ ll

-rwx r-xr-x. 1 socol socol 6662 Nov  8 11:45 test-uid

[socol@localhost test]$ sudo chown root.root ./test-uid
[socol@localhost test]$ sudo chmod 4755 ./test-uid

[socol@localhost test]$ ll

-rws r-xr-x. 1 root root 6662 Nov  8 11:51 test-uid

[socol@localhost test]$ ls -al /var

total 92
drwxr-xr-x. 22 root root 4096 Aug  9 12:38 .
dr-xr-xr-x. 24 root root 4096 Nov  8 10:39 ..
drwxr-xr-x.  2 root root 4096 Aug  9 12:22 account
drwxr-xr-x. 17 root root 4096 Aug 11 14:41 cache
drwxr-xr-x.  2 root root 4096 Oct 16  2009 cvs
drwxr-xr-x.  3 root root 4096 Aug  9 12:22 db
drwxr-xr-x.  3 root root 4096 Aug  9 12:31 empty

... ...

[socol@localhost test]$ ./test-uid

[socol@localhost test]$ ls -al /var
total 92
drwxr-xr-x. 22 root root 4096 Nov  8 11:51 .
dr-xr-xr-x. 24 root root 4096 Nov  8 10:39 ..
drwxr-xr-x.  2 root root 4096 Aug  9 12:22 account
drwxr-xr-x. 38 root root 4096 Nov  8 11:45 run
drwxr-xr-x. 14 root root 4096 Aug  9 12:37 spool
-rw-rw-r--.  1 root socol    0 Nov  8 11:51 testroot
drwxrwxrwt.  4 root root 4096 Nov  8 11:29 tmp
... ...

猜你喜欢

转载自socol.iteye.com/blog/805472