We met the situation before that we want to execute a root command by a normal user, here is our solution (using setuid/SUID):
assume that:
- username:
Tom
- group:
gTom
- C program file:
my_pro.c
Step 1: Write a C code tool: my_sudo.c
...
int main(int args, char *argv[]) {
if (args < 2)
printf("Usage: my_sudo [cmd] [arg1 arg2 ...]");
// cmd here is the shell cmd that you want execute in "my_pro"
// you can check the shell cmd privilege here
// example: if (argv[1] != "yum") return; we just allow yum execute here
char cmd[MAX_CMD];
int i;
for ( i = 2; i < args; i ++) {
// concatenate the cmd, example: "yum install xxxxx"
strcat(cmd, " ");
strcat(cmd, argv[i]);
}
system(cmd);
}
Step 2: Compile my_sudo.c
to get a my_sudo
executable file
sudo chown root:gTom my_sudo // user root && gTom group
sudo chmod 4550 my_sudo // use SUID to get root privilege
#you will see my_sudo like this(ls -l)
#-r-sr-x--- 1 root my_sudo 9028 Jul 19 10:09 my_sudo*
#assume we put my_sudo to /usr/sbin/my_sudo
Step 3: In your C code
...
int main() {
...
system("/usr/bin/mysudo yum install xxxxx");
...
}
#gcc && ls -l
#-rwxr--r-- 1 Tom gTom 1895797 Jul 23 13:55 my_pro
Step 4: Execute./my_pro
You can execute the yum install
without sudo
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…