简体   繁体   English

C中的setgid()调用不起作用

[英]setgid() call in C does not work

I am trying to drop privileges in a C program and whatever I do GID remains 0. After hours of research I am clueless :( 我试图在C程序中放弃特权,而我所做的一切GID仍然为0。经过数小时的研究,我一无所知:(

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

int main(int argc, char *argv[]) {

        initgroups("nobody", 65534);
        setresuid(65534,65534,65534);
        setresgid(65534,65534,65534);
        setegid(65534);
        printf("gid: %d\n", getegid());
        execv("/usr/bin/id", argv);

}

Returns this: 返回此:

gid: 0
uid=65534(nobody) gid=0(root) groups=65534(nogroup)

Why is GID 0 when I explicitly set all three (R,E and SGID) to 65534? 当我将所有三个(R,E和SGID)显式设置为65534时,为什么GID为0?

To set the GID values, the process needs an effective UID of 0 (root), but your code carefully throws away the root privileges by setting the UID values to 65534 before calling setresgid() , so the call fails — as you would have known had you tested the return values of the functions. 要设置GID值,该过程需要有效的UID为0(root),但是您的代码通过在调用setresgid()之前将UID值设置为65534来小心翼翼地放弃root特权,因此调用会失败—如您所知您是否测试了函数的返回值。

Reverse the order of the calls to setresuid() and setresgid() (and remove the superfluous setegid() too, of course, and the extra printf() ). 颠倒对setresuid()setresgid()的调用setresuid()当然setegid()删除多余的setegid()和多余的printf() )。

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>  // Archaic: shouldn't be needed (but Linux docs list it)
#include <grp.h>

int main(int argc, char **argv)
{
    if (initgroups("nobody", 65534) == 0 &&
        setresgid(65534, 65534, 65534) == 0 &&
        setresuid(65534, 65534, 65534))
        execv("/usr/bin/id", argv);
    fprintf(stderr, "Oops!\n");
    return 0;
}

You can be more careful in your error reporting if you wish. 如果需要,可以在错误报告中更加小心。 Remember, execv() does not return if it is successful; 记住,如果成功, execv()不会返回; there is no need to test its return value. 无需测试其返回值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM