setuid(0)无法为root拥有的程序执行

时间:2015-02-08 15:41:07

标签: c linux shell root setuid

我需要编写一些可以获得root权限并执行系统级操作的代码。这是我写的(这不是实际的代码,只是为了测试我是否正确地做事):

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(void)
{
    int current_uid = getuid();
    printf("My UID is: %d. My GID is: %d\n", current_uid, getgid());
    system("/usr/bin/id");
    if (setuid(0))
    {
        perror("setuid");
        return 1;
    }
    //I am now root!
    printf("My UID is: %d. My GID is: %d\n", getuid(), getgid());
    system("/usr/bin/id");
    //Time to drop back to regular user privileges
    setuid(current_uid);
    printf("My UID is: %d. My GID is: %d\n", getuid(), getgid());
    system("/usr/bin/id");
    return 0;
}

执行gcc -o setuid setuid.c后,我在此处运行ls -al以获得以下结果:

tarun@staging:~$ ls -al setuid
-rwxr-xr-x 1 tarun tarun 9792 2009-10-03 18:09 setuid
adam@staging:~$

尝试运行应用程序导致:

tarun@staging:~$ ./setuid
My UID is: 1000. My GID is: 1000
uid=1000(tarun) gid=1000(tarun) groups=1000(tarun),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),109(lpadmin),125(sambashare),999(bumblebee)
setuid: Operation not permitted

我将所有者更改为root并相应地设置粘滞位:

tarun@staging:~$ su - root
Password:
staging:~# cd /home/tarun
staging:/home/tarun# chown root.root setuid
staging:/home/tarun# chmod +s setuid
staging:/home/tarun# ls -al setuid
-rwsr-sr-x 1 root root 9792 2009-10-03 18:09 setuid
staging:/home/tarun# exit
logout
tarun@staging:~$

现在执行程序会给出:

adam@staging:~$ ./setuid
My UID is: 1000. My GID is: 1000
uid=1000(tarun) gid=1000(tarun) groups=1000(tarun),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),109(lpadmin),125(sambashare),999(bumblebee)
setuid: Operation not permitted

理想情况下,它应该已经完全执行并将我的uid更改为0.我做错了什么?

3 个答案:

答案 0 :(得分:4)

您的代码没问题,只需检查一下setuid /&#39; sgid&#39;序列:

sudo chmod 6775 setuid
sudo chown root:root setuid

您必须至少设置SUID,SGID和执行权限(6555掩码)。此情况下,设置用户/组写入(6775掩码)也很常见。当然,为了安全起见,您可以将其限制为用户写掩码(6755)。

请注意,在重新编译期间不要删除权限:

$ ls -al
-rwsrwsr-x 1 root  root  8772 Feb  8 17:52 setuid

万一你(或未来的读者)需要这样的指南: What is SUID and how to set SUID in Linux/Unix?

关于eCryptfs的问题:这篇文章可以帮助您:https://wiki.archlinux.org/index.php/ECryptfs

答案 1 :(得分:0)

更改

chown root.root setuid

chown root setuid

chown root.tarun setuid

答案 2 :(得分:0)

粘性位具有完全不同的功能。在一个文件中,它现在很大程度上是未定义的,而在目录上,它可以防止非所有者(除root之外)删除目录中的文件而不管目录权限。

您正在寻找设置的UID位:

  chown root setuid
  chmod +s setuid

显然,您必须是root用户才能为root拥有的文件设置SUID权限。但是,由于setUID位存在,我怀疑你可能会付出不需要的努力。

相关问题