Linux下获取root权限的c程序

本文介绍了一种在Linux环境下通过C程序传递SUID权限给其他脚本的方法,解决了shell、Python等脚本无法直接获得SUID的问题。通过编写并设置特定C程序的SUID标志,可以将该程序的权限传递给指定的脚本。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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程序如下: 

/* # 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
原文地址:<a target=_blank href="http://blog.youkuaiyun.com/gaopenghigh/article/details/8600959">http://blog.youkuaiyun.com/gaopenghigh/article/details/8600959</a>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值