在本教程中,我们将讨论如何将SFTP用户限制在其主目录或特定目录中。这意味着用户只能访问自己的主目录,而不能访问整个文件系统。
限制用户主目录对于共享服务器环境至关重要,这样未经授权的用户就无法窥视其他用户的文件和文件夹。
重要提示:还请注意,本文的目的是仅提供SFTP访问权限,而不是SSH登录,按照本文操作将具有进行文件传输的权限,但不允许进行远程SSH会话。
建议阅读: 使用Chrooted Jail限制SSH用户访问特定目录
实现这一目的的最简单方法是为SFTP访问创建一个chrooted jail环境。这种方法适用于所有Unix/Linux操作系统。使用chrooted环境,我们可以将用户限制在其主目录或特定目录中。
将用户限制在主目录中
在本节中,我们将创建一个名为sftpgroup的新组,并为用户帐户分配正确的所有权和权限。有两种选择将用户限制在主目录或特定目录中,我们将在本文中看到这两种方式。
创建或修改用户和组
让我们限制现有用户,例如tecmint
,到名为/home/tecmint
的家目录。为此,您需要使用如下所示的groupadd命令创建一个新的sftpgroup组:
# groupadd sftpgroup
接下来,将用户‘tecmint’分配到sftpgroup组。
# usermod -G sftpgroup tecmint
您还可以使用useradd命令创建一个新用户,例如senthil
,并将用户分配到sftpusers组。
# adduser senthil -g sftpgroup -s /sbin/nologin # passwd tecmint
修改SSH配置文件
打开并添加以下行到/etc/ssh/sshd_config
配置文件。
Subsystem sftp internal-sftp Match Group sftpgroup ChrootDirectory /home ForceCommand internal-sftp X11Forwarding no AllowTcpForwarding no
保存并退出文件,重新启动sshd服务以使新更改生效。
# systemctl restart sshd OR # service sshd restart
如果您将多个用户chroot到同一目录,您应更改每个用户的家目录权限,以防止所有用户浏览其他用户的家目录。
# chmod 700 /home/tecmint
验证SSH和SFTP用户登录
现在,是时候从本地系统检查登录情况了。尝试从本地系统ssh到远程系统。
# ssh [email protected]
这里,
- tecmint – 远程系统的用户名。
- 192.168.1.150 – 远程系统的IP地址。
示例输出:
[email protected]'s password: Could not chdir to home directory /home/tecmint: No such file or directory This service allows sftp connections only. Connection to 192.168.1.150 closed.
然后,使用SFTP访问远程系统。
# sftp [email protected]
示例输出:
[email protected]'s password: Connected to 192.168.1.150. sftp>
让我们检查当前工作目录:
sftp> pwd Remote working directory: / sftp> ls tecmint
这里,tecmint
是主目录。Cd 到 tecmint 目录并创建您选择的文件或文件夹。
sftp> cd tecmint Remote working directory: / sftp> mkdir test tecmint
限制用户访问特定目录
在我们之前的示例中,我们限制现有用户访问主目录。现在,我们将看到如何将新用户限制到自定义目录。
创建组和新用户
创建一个新组 sftpgroup
。
# groupadd sftpgroup
接下来,为 SFTP 组创建一个目录,并为根用户分配权限。
# mkdir -p /sftpusers/chroot # chown root:root /sftpusers/chroot/
接下来,为每个用户创建新目录,他们将拥有完全访问权限。例如,我们将使用以下一系列命令创建 tecmint
用户及其新主目录,并使用正确的组权限。
# adduser tecmint -g sftpgroup -s /sbin/nologin # passwd tecmint # mkdir /sftpusers/chroot/tecmint # chown tecmint:sftpgroup /sftpusers/chroot/tecmint/ # chmod 700 /sftpusers/chroot/tecmint/
为 SFTP 访问配置 SSH
在文件末尾修改或添加以下行:
#Subsystem sftp /usr/libexec/openssh/sftp-server Subsystem sftp internal-sftp Match Group sftpgroup ChrootDirectory /sftpusers/chroot/ ForceCommand internal-sftp X11Forwarding no AllowTcpForwarding no
保存并退出文件。重新启动 sshd 服务以使保存的更改生效。
# systemctl restart sshd OR # service sshd restart
就是这样,您可以通过使用上面提供的步骤登录到远程 SSH 和 SFTP 服务器来进行检查 验证 SSH 和 SFTP 登录。
请注意,此方法将禁用 shell 访问,即您无法使用 SSH 访问远程系统的 shell 会话。您只能通过 SFTP 访问远程系统,并在本地系统和远程系统之间进行文件传输。
结论;
现在您知道如何在Linux中使用Chroot环境限制用户的主目录。如果您发现这篇文章有用,请在您的社交网络上分享这篇文章,并在下面的评论部分告诉我们是否有其他方法来限制用户的主目录。
Source:
https://www.tecmint.com/restrict-sftp-user-home-directories-using-chroot/