21

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

谢谢!

4

4 回答 4

26

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因此,当您需要依赖此功能时,请确保不要向用户授予命令。

于 2012-04-22T22:47:15.900 回答
3

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

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

session    required     pam_loginuid.so

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

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

于 2012-04-22T22:57:33.897 回答
2

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

  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 程序应该仔细编写。如果您只需要访问受保护的目录或文件,您可以将其设置为权限较低的用户。

于 2012-04-22T23:15:43.950 回答
1

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

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

或者

who am i | cut -f1 -d" "
于 2020-09-09T09:09:54.367 回答