我正在运行的程序需要root权限,因此使用sudo
运行,但它也需要知道用户正在运行它。 getuid
和geteuid
都返回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)
只会被安装在“主”守护进程( sshd
, login
, gdm
等)上,所以当sudo(8)
执行时,审计uid将保持不变。
这将需要一点点配置; 加:
session required pam_loginuid.so
到/etc/pam.d/sshd
文件 – 以及您允许用户使用的其他服务。
确保/etc/pam.d/sudo
配置文件中未加载pam_loginuid.so
。
你有两个不错的选择
更新:
setuid位是文件模式下的访问权标志,它使程序以可执行文件所有者的能力运行。 这是如何sudo(1)能够以root身份运行的东西… sudo程序本身有这种模式。
$ ls -l /usr/bin/sudo -rs--x--x 1 root wheel 272384 Jun 22 2009 /usr/bin/sudo*
要制作一个程序setuid root可能会:
$ chown root a.out $ chmod +s a.out
不用说,setuid根程序应该仔细写。 如果您只需要访问受保护的目录或文件,则可以设置为权限较低的用户。