温馨提示×

Ubuntu SFTP如何禁用密码登录

小樊
155
2025-11-17 10:51:30
栏目: 智能运维

Ubuntu SFTP禁用密码登录的安全配置指南

一 核心配置步骤

  • 在 Ubuntu 上,SFTP 基于 OpenSSH,禁用密码登录需在 /etc/ssh/sshd_config 中调整认证参数,并确保公钥已部署,然后重启服务。
  • 建议的操作顺序:
    1. 备份配置:sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
    2. 编辑配置:sudo nano /etc/ssh/sshd_config
    3. 确保启用公钥认证并禁用密码:
      • PubkeyAuthentication yes
      • PasswordAuthentication no
      • (可选,更严格)KbdInteractiveAuthentication no(禁用键盘交互式认证,防止键盘交互式密码尝试)
    4. 如需限制为仅 SFTP 且禁 shell 登录,可在文件末尾加入 Match 段(示例见第二部分)。
    5. 保存并使配置生效:sudo systemctl restart ssh(或 sudo systemctl restart sshd)。
    6. 注意:某些系统存在全局与 Match 段的配置继承/覆盖关系,务必确认没有其它 Match 段把 PasswordAuthentication 改回 yes。

二 为 SFTP 用户启用密钥登录与目录权限

  • 生成密钥对(客户端):ssh-keygen -t rsa -b 4096,得到私钥 id_rsa 与公钥 id_rsa.pub
  • 部署公钥到服务器对应用户(以用户 sftpuser 为例):
    • 创建 .ssh 目录与授权文件:
      • mkdir -p /home/sftpuser/.ssh
      • nano /home/sftpuser/.ssh/authorized_keys(将 id_rsa.pub 内容粘贴)
    • 设置权限(关键):
      • chown -R sftpuser:sftpusers /home/sftpuser/.ssh
      • chmod 700 /home/sftpuser/.ssh
      • chmod 600 /home/sftpuser/.ssh/authorized_keys
  • 若使用 ChrootDirectory(常见于仅 SFTP 场景),需保证被限制的目录由 root 拥有,且权限为 755;可给用户可写子目录(如 uploads):
    • chown root:root /home/sftpuser
    • mkdir /home/sftpuser/uploads
    • chown sftpuser:sftpusers /home/sftpuser/uploads
    • chmod 755 /home/sftpuser/uploads
  • 说明:Chroot 仅限制访问范围,不会自动禁用密码;仍需在 sshd_config 中关闭密码认证。

三 仅允许 SFTP 并禁用 Shell 登录(可选)

  • 在 /etc/ssh/sshd_config 末尾添加(按需选择用户或用户组):
    • Match Group sftpusers
      • ChrootDirectory /home/%u
      • ForceCommand internal-sftp
      • X11Forwarding no
      • AllowTcpForwarding no
  • 如需禁止该用户使用 SSH 登录 shell,可将其登录 shell 设为 /usr/sbin/nologin/bin/false(创建用户时或 usermod -s)。注意:仅设置 shell 并不能阻止密码尝试,仍需关闭 PasswordAuthentication。

四 防火墙与防护加固

  • 防火墙仅放通必要来源(示例为 UFW):
    • 放通特定 IP:sudo ufw allow from <client_ip> to any port 22
    • 或放通所有来源(不推荐生产):sudo ufw allow 22/tcp && sudo ufw enable
  • 防暴力破解:安装并启用 Fail2ban
    • 安装:sudo apt install fail2ban -y
    • 启用 SSH 保护(/etc/fail2ban/jail.local 或 jail.d/sshd.local):
      • [sshd]
      • enabled = true
      • port = 22
      • filter = sshd
      • logpath = /var/log/auth.log
      • maxretry = 5
      • bantime = 3600
    • 重启:sudo systemctl restart fail2ban。

五 验证与回滚

  • 验证公钥登录:sftp sftpuser@<server_ip>,应无需密码即可登录;若失败,检查 authorized_keys 内容、权限与属主,以及 sshd_config 中 PubkeyAuthentication/PasswordAuthentication 的取值与生效范围。
  • 验证密码被拒:使用 ssh -o PreferredAuthentications=password sftpuser@<server_ip> 应被拒绝;若仍能用密码,说明配置未生效或被其它 Match 段覆盖。
  • 查看日志定位问题:tail -f /var/log/auth.log(Ubuntu/Debian)。
  • 紧急回滚:将 /etc/ssh/sshd_config 恢复为备份并重启服务:sudo cp /etc/ssh/sshd_config.bak /etc/ssh/sshd_config && sudo systemctl restart ssh。

0