`
gaopenghigh
  • 浏览: 244837 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

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

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

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

作者:高鹏 <gaopenghigh@gmail.com>

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

c程序如下:
/* # ScriptName: transeuid.c
# Author: JH Gao <gaopenghigh@gmail.com>
# Create Date: 2012-06-05
# Function: transmit euid and egid to other scripts
#   since shell/python/... scripts can't get suid permission in Linux
#   usage: transeuid xxx.sh par1 par2 par3
#          xxx.sh will get the euid and egid from transeuid
# ******************************************************************** */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define BUFFSIZE 1024

/*
 * usually euid is the uid who run the program
 * but when stick is setted to the program
 * euid is the uid or the program's owner
 */
int main(int argc, char *argv[]) {
    char *cmd = malloc(BUFFSIZE);
    // set uid and gid to euid and egid
    setuid(geteuid());
    setgid(getegid());
    cmd = argv[1];
    int i = 0;
    for(i = 0;i < argc - 1;i++) {
        argv[i] = argv[i+1];
    }
    argv[argc-1] = NULL
    // search $PATH find this cmd and run it with pars:argv
    if (execvp(cmd, argv)) {
        printf("error");
        free(cmd);
        exit(1);
    }
    free(cmd);
}


编译这个程序,在给这个程序设置希望取得的用户,再设置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
1
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics