Linux下获取root权限的c程序

来源:互联网 发布:dr.jart 知乎 编辑:程序博客网 时间:2024/06/07 00:56

Linux下获取root权限的c程序

  传递euid和egid给脚本,使脚本具有特殊用户的权限 


使脚本实现类似于设置了stick位的效果 

  shell, python, perl等脚本、程序不能取得suid,因为这些脚本程序需要解释器-/bin/bash, /usr/bin/python等来执行,而这些解释器本身没有suid也不方便设置suid。碰到这种情况可以用c写一个外壳,对这个外壳设置suid,而在c程序里面把自身的uid,gid传递给实际执行任务的脚本。(这个方法是在读周鹏(Roc Zhou <roczhou.zhoup@alibaba-inc.com>)写的工具时学到的) 

c程序如下: 

[cpp] view plaincopy
  1. /* # ScriptName: transeuid.c 
  2. # Author: JH Gao <gaopenghigh@gmail.com> 
  3. # Create Date: 2012-06-05 
  4. # Function: transmit euid and egid to other scripts 
  5. #   since shell/python/... scripts can't get suid permission in Linux 
  6. #   usage: transeuid xxx.sh par1 par2 par3 
  7. #          xxx.sh will get the euid and egid from transeuid 
  8. # ******************************************************************** */  
  9.   
  10. #include <stdio.h>  
  11. #include <stdlib.h>  
  12. #include <unistd.h>  
  13. #define BUFFSIZE 1024  
  14.   
  15. /* 
  16.  * usually euid is the uid who run the program 
  17.  * but when stick is setted to the program 
  18.  * euid is the uid or the program's owner 
  19.  */  
  20. int main(int argc, char *argv[]) {  
  21.     char *cmd = malloc(BUFFSIZE);  
  22.     // set uid and gid to euid and egid  
  23.     setuid(geteuid());  
  24.     setgid(getegid());  
  25.     cmd = argv[1];  
  26.     int i = 0;  
  27.     for(i = 0;i < argc - 1;i++) {  
  28.         argv[i] = argv[i+1];  
  29.     }  
  30.     argv[argc-1] = NULL  
  31.     // search $PATH find this cmd and run it with pars:argv  
  32.     if (execvp(cmd, argv)) {  
  33.         printf("error");  
  34.         free(cmd);  
  35.         exit(1);  
  36.     }  
  37.     free(cmd);  
  38. }  

编译这个程序,在给这个程序设置希望取得的用户,再设置suid,然后就可以用这个用户的权限执行脚本或命令了: 

$ gcc -t transeuid transeuid.c$ sudo chown root transeuid$ sudo chmod +s transeuid$ ./transeuid ls /root /home/home:.  ..  data  .directory  gp_old  jh  jh_old  lost+found/root:.  ..  .bash_history  .bashrc  .cache  .dbus  .profile  .pulse  .pulse-cookie  .viminfo
 
0 0