如果程序是用sudo运行的,如何让用户获得真正的uid?

cha*_*m15 15 c ubuntu

我运行的程序需要root权限,因此运行sudo,但它也需要知道用户正在运行它.getuidgeteuid都返回root.如何获取实际用户的用户名(或uid)?

谢谢!

sar*_*old 18

sudo 提供了一些环境变量来帮助您完成这种情况:

   SUDO_UID        Set to the user ID of the user who invoked
                   sudo

   SUDO_USER       Set to the login of the user who invoked sudo
Run Code Online (Sandbox Code Playgroud)

steveayre在评论中指出用户可以在某些情况下设置这些环境变量; 该sudo(8)联机帮助页包括:

The sudoers policy subjects variables
passed on the command line to the same restrictions as normal
environment variables with one important exception.  If the
setenv option is set in sudoers, the command to be run has the
SETENV tag set or the command matched is ALL, the user may set
variables that would otherwise be forbidden.  See sudoers(5)
for more information.
Run Code Online (Sandbox Code Playgroud)

因此,ALL当您需要依赖此功能时,请确保不向用户授予命令.

  • 环境变量应该是可以安全信任的——你必须完全信任 `sudo` 才能以这种方式使用它。任何针对“sudo”的攻击,允许边缘信任的用户使用修改后的环境变量执行程序,都将引起全球数十个安全团队的关注,以修复该缺陷(如果无法修复,则删除该功能)。至于兼容性,这比我刚刚想到的另一个选项更便携——单独回答它自己的评论。这可能比编写自己的 setuid-root 程序更安全。 (2认同)
  • 只有具有`CAP_SYS_PTRACE`功能的进程才能连接到执行程序 - 用户进程将不具备该功能 - 并修改环境变量.无论此环境变量如何,具有"CAP_SYS_PTRACE"的进程都已经能够进行大量破坏.:) (2认同)