c - setuid 和 seteuid 函数的区别

标签 c linux unix

程序 1:使用 setuid() 的示例

    #include<stdio.h>
    #include<sys/types.h>
    #include<unistd.h>
    void main()
    {
        printf("Real user id = %d, Effective User id = %d\n",getuid(),geteuid());
        setuid(1000);
        printf("Real user id = %d, Effective User id = %d\n",getuid(),geteuid());
        setuid(1014);
        printf("Real user id = %d, Effective User id = %d\n",getuid(),geteuid());
    }

输出:

    guest $ ./a.out 
    Real user id = 1000, Effective User id = 1014
    Real user id = 1000, Effective User id = 1000
    Real user id = 1000, Effective User id = 1014
    guest $

程序 2:seteuid() 示例

    #include<stdio.h>
    #include<sys/types.h>
    #include<unistd.h>
    void main()
    {
        printf("Real user id = %d, Effective User id = %d\n",getuid(),geteuid());
        seteuid(1000);
        printf("Real user id = %d, Effective User id = %d\n",getuid(),geteuid());
        seteuid(1014);
        printf("Real user id = %d, Effective User id = %d\n",getuid(),geteuid());
    }

输出:

    guest $ ./a.out 
    Real user id = 1000, Effective User id = 1014
    Real user id = 1000, Effective User id = 1000
    Real user id = 1000, Effective User id = 1014
    guest $

两个程序给出相同的输出。那么,这两个函数有什么区别呢?根据引用资料(手册页),这两个函数都用于设置进程的有效用户 ID。这两个程序的功能有何不同?

最佳答案

The documentation很清楚区别:

If the user is root or the program is set-user-ID-root, special care must be taken. The setuid() function checks the effective user ID of the caller and if it is the superuser, all process-related user ID's are set to uid. After this has occurred, it is impossible for the program to regain root privileges.

Thus, a set-user-ID-root program wishing to temporarily drop root privileges, assume the identity of an unprivileged user, and then regain root privileges afterward cannot use setuid(). You can accomplish this with seteuid.

关于c - setuid 和 seteuid 函数的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33077818/

相关文章:

c - 为什么将我的输入分配给枚举会导致段错误?

c - 为什么即使我没有返回值,我也会得到总和作为输出?

c++ - P线程问题

linux - 如何根据需要将所有文件合并为一个文件

linux - 我怎样才能使我的 Makefile 更好?

linux - Kprobe:将返回探针与入口探针相关联

java - 如何从java代码在unix终端中执行外部工具?

c++ - 按位 NOT 运算符返回意外的负值?

linux - Unix 中的无缓冲 I/O

ruby - 使用不同版本的 Ruby 的 UNIX `system` 命令