为了在每个用户的基础上允许 ChrootDirectory 功能,请在 sshd_config 文件中使用有条件执行的 sshd 配置(使用“Match”关键字)。
在特定组上设置 ChrootDirectory 可确保该组的用户无法离开其主目录,从而确保其他用户不会受到影响。
- 为将被 chroot 的用户创建一个组。
# groupadd sftp_group
- 为SFTP组创建一个用户并设置密码。
# useradd sftp_test1
# passwd sftp_test1 Changing password for user sftp_test1. New password: Retype new password: passwd: all authentication tokens updated successfully.
- 将 sftp_test1 用户添加到 sftp_group 组。
让用户 shell 为 /bin/false 因为用户应该只被允许做 sftp 而不是 ssh/scp。
# usermod -g sftp_group -s /bin/false sftp_test1
# id sftp_test1 uid=1000(sftp_test1) gid=1001(sftp_test1) groups=1001(sftp_test1),1000(sftp_group)
注意:不在该组中的用户仍然可以通过 ssh 登录主机,否则与 openssh 正常交互。
- 编辑 sshd 配置以配置 sftp。
删除 /usr/libexec/openssh/sftp-server 行并添加 internal-sftp 行,如下所示:
删除或者散列该行:
# vi /etc/ssh/sshd_config Subsystem sftp /usr/libexec/openssh/sftp-server
添加以下行:
# vi /etc/ssh/sshd_config Subsystem sftp internal-sftp
- 在/etc/ssh/sshd_config文件末尾添加以下内容,添加sftp chroot环境:
# vi /etc/ssh/sshd_config Match Group sftp_group X11Forwarding no AllowTcpForwarding no ChrootDirectory /home ForceCommand internal-sftp
- 重启sshd服务使sftp配置生效。
# systemctl restart sshd
更多: zhilu jiaocheng
检查确认
- 现在尝试从其他客户端使用 SSH & SFTP 服务访问系统:
SSH
# ssh sftp_test1@x.x.x.x The authenticity of host 'x.x.x.x (x.x.x.x)' can't be established. ECDSA key fingerprint is 07:1c:34:30:f4:81:e1:e0:b3:13:30:b8:57:d9:d9:58. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added 'x.x.x.x' (ECDSA) to the list of known hosts. sftp_test1@x.x.x.x's password: Could not chdir to home directory /home/sftp_test1: No such file or directory This service allows sftp connections only. Connection to x.x.x.x closed.
如我们所见,连接已关闭且不允许登录 SSH。
SFTP
# sftp sftp_test1@x.x.x.x sftp_test1@x.x.x.x's password: Connected to x.x.x.x. sftp> pwd Remote working directory: / sftp> ls sftp_test1 sftp> cd /home Couldn't canonicalize: No such file or directory sftp>
结果上面的 sftp_test1 用户是通过 SFTP 登录的,由于 chroot 环境无法更改目录
- 我们也可以使用“WinSCP”或者“Filezilla”软件从windows客户端测试SFTP-Server功能。
日期:2020-09-17 00:12:19 来源:oir作者:oir