从 setuid root C 程序调用脚本 - 脚本不以 root 身份运行 [英] Calling a script from a setuid root C program - script does not run as root

查看:22
本文介绍了从 setuid root C 程序调用脚本 - 脚本不以 root 身份运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以 root 身份运行 bash 脚本(无密码 sudo 或 su 不可行),并且由于您无法在 Linux 中 setuid 脚本,我想从可执行文件中调用它并使 it setuid:

I need to run a bash script as root (passwordless sudo or su not viable) and since you cannot setuid a script in Linux, I thought about calling it from an executable and making it setuid:

$ cat wrapper.c
int main(void)
{
        system("/bin/bash ./should_run_as_root.sh");
}
$ gcc -o wrapper wrapper.c
$ sudo chown root wrapper
$ sudo chmod ug+s wrapper
$ ll wrapper
-rwsr-sr-x 1 root users 6667 2009-02-17 11:11 wrapper
$

这有效 - 就像正确运行脚本一样 - 但脚本以执行./wrapper"的用户身份运行.

This works - as in runs the script correctly - but the script runs as the user who executes "./wrapper".

为什么?以及如何正确实现这一点?

Why? And how to correctly implement this?

谢谢!

推荐答案

由于可执行文件上的 suid 位只会更改可执行文件将作为其运行的有效 UID (EUID),而不是真正的 UID (getuid() 返回的 RUID),除了限制 suid 解释脚本(任何以#!"开头的可执行文件),在这种情况下,一些像 bash 这样的 shell 作为额外的安全措施会将 EUID 设置回 RUID,您将需要在 C 代码中使用调用 setuid(0)在执行脚本之前.

Since the suid bit on executables only changes the effective UID (EUID) the executable will run as, and not the real UID (RUID) which getuid() returns, and in addition to the restriction on suid interpreted scripts (any executable beginning with "#!"), some shells like bash as an extra safety measure will set the EUID back to the RUID in this case, you will need to use the call setuid(0) in the C code before executing the script.

查看setuidseteuidgetuidgeteuidman页代码>学习真实有效的 UID 的确切语义.

See the man pages of the setuid, seteuid, getuid, and geteuid to learn the exact semantics of the real and effective UIDs.

(WARNING) 当然,这是一个恰当的观点,在许多 Unix 系统、shell 和解释器中对 suid 脚本的限制是有原因的,也就是说,如果脚本在执行时没有非常小心地清理其输入和环境状态,则它们是危险的,并且可以被利用来进行安全升级.因此,在执行此操作时要非常小心.尽可能严格地设置对脚本和包装器的访问,只允许执行您打算执行的非常具体的脚本,并在启动脚本之前清除 C 程序中的环境,设置环境变量,例如 PATH 以正确的顺序包含必要的内容,并且没有其他人可写的目录.

(WARNING) Of course, this is an appropriate point to mention that the restriction on suid scripts in many Unix systems, shells and interpreters, are there for a reason, which is that if the script is not very careful about sanitizing its input and the state of environment when it is executed, they are dangerous and can be exploited for security escalation. So be very careful when doing this. Set the access to your script and wrapper as strict as you can, only allow this very specific script which you intend to be executed, and clear the environment within your C program before starting the script, setting environment variables such as PATH to contain exactly what is necessary in the right order and no directories that are writable to others.

这篇关于从 setuid root C 程序调用脚本 - 脚本不以 root 身份运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆