繁体   English   中英

如果程序使用 sudo 运行,我如何获得用户的真实 uid?

[英]How do I get the users real uid if the program is run with sudo?

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

谢谢!

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

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.

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

审计系统提供的特定audit_getloginuid() Linux 的audit_getloginuid()函数可能会有所帮助; 由于pam_loginuid(8)只会为“主要”守护进程( sshdlogingdm等)安装,因此审计 uid 在sudo(8)执行时将保持不变。

这将需要一些配置; 添加:

session    required     pam_loginuid.so

/etc/pam.d/sshd文件 - 以及您允许用户使用的任何其他服务。

确保/etc/pam.d/sudo配置文件中未加载pam_loginuid.so

你有两个不错的选择...

  1. 信任 sudo 并使用它的环境
  2. 使您的程序 setuid-on-execution 然后 geteuid 等就可以正常工作

更新:

setuid 位是文件模式中的访问权限标志,它使程序以可执行文件所有者的能力运行。 这就是 sudo(1) 能够以 root 身份运行事物的方式……sudo 程序本身具有这种模式。

$ ls -l /usr/bin/sudo
-r-s--x--x  1 root  wheel  272384 Jun 22  2009 /usr/bin/sudo*

要使程序 setuid root 可以:

$ chown root a.out
$ chmod +s a.out

不用说,setuid root 程序应该仔细编写。 如果您只需要访问受保护的目录或文件,您可以将 uid 设置为权限较低的用户。

更简单的方法是使用我是谁

who am i | awk '{print $1}'

要么

who am i | cut -f1 -d" "

暂无
暂无

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

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