为什么像 su 这样的程序可以访问 /etc/shadow

Kri*_*itz 8 root permissions shadow

通常只有 root 可以访问/etc/shadow. 但是程序喜欢su并且sudo可以在不以 root 身份运行的情况下检查密码。那么问题来了:为什么这些程序可以/etc/shadow无权限访问?我试图通过带有spwd模块的python 没有权限访问它,但我没有获得访问权限(如预期的那样)。这些程序使用哪种机制?

Rah*_*til 11

为什么像 su 这样的程序可以访问 /etc/shadow

因为程序喜欢su并且passwd已经设置了SetUID. 您可以使用以下方法进行检查:

[root@tpserver tmp]#  ls -l /usr/bin/passwd
-r-s--x--x  1 root root 21200 Aug 22  2013 /usr/bin/passwd
Run Code Online (Sandbox Code Playgroud)

当您查看文件权限时,您会看到“s”。如果有人试图运行该passwd程序,默认情况下它会获得文件所有者(此处为 root)的特权。这意味着任何用户都可以得到root权限执行passwd的程序,因为只有root用户可以编辑或更新/etc/passwd/etc/shadow文件。其他用户不能。当普通用户passwd在他的终端上运行程序时,passwd程序以“root”身份运行,因为有效的 UID 设置为“root”。所以普通用户可以轻松更新文件。

您可以使用chmod带有u+sg+s参数的命令分别在可执行文件上设置 setuid 和 setgid 位


长答案:Set-User_Id (SUID):电源片刻:

默认情况下,当用户执行文件时,导致执行的进程具有与用户相同的权限。实际上,进程继承了他的默认组和用户标识。

如果在可执行文件上设置 SUID 属性,则导致其执行的进程不使用用户标识,而是使用文件所有者的用户标识。

由丹尼斯·里奇 (Dennis Ritchie) 发明的 SUID 机制存在潜在的安全隐患。它允许用户通过运行 root 拥有的此类文件来获得隐藏的权力。

$ ls -l /etc/passwd /etc/shadow /usr/bin/passwd
-rw-r--r-- 1 root root 2232 Mar 15 00:26 /etc/passwd
-r-------- 1 root root 1447 Mar 19 19:01 /etc/shadow
Run Code Online (Sandbox Code Playgroud)

The listing shows that passwd is readable by all, but shadow is unreadable by group and others. When a user running the program belongs to one of these two categories (probably, others), so access fails in the read test on shadow. Suppose normal user wants to change his password. How can he do that? He can do that by running /usr/bin/passwd. Many UNIX/Linux programs have a special permission mode that lets users update sensitive system files –like /etc/shadow --something they can't do directly with an editor. This is true of the passwd program.

$ ls -l /usr/bin/passwd
-rwsr-xr-x 1 root root 22984 Jan 6 2007 /usr/bin/passwd
Run Code Online (Sandbox Code Playgroud)

The s letter in the user category of the permission field represents a special mode known as the set-user-id (SUID). This mode lets a process have the privileges of the owner of the file during the instance of the program. Thus when a non privileged user executes passwd, the effective UID of the process is not the user's, but of root's – the owner of the program. This SUID privilege is then used by passwd to edit /etc/shadow.

Reference Link

  • `S` 实际上与 `s` 不同。`s` 的意思是:execute + setuid,而 `S` 的意思就是 setuid 不执行。这确保您可以判断相应用户是否仍然具有执行权限,因为 `s`/`S` 标志使用了通常由 `x` 标志使用的空间。 (2认同)