openssh服务端安装后须立即安全加固:禁用root密码登录、限制用户/组、关闭sshv1及弱算法、配置防火墙与fail2ban,并定期更新。

OpenSSH 服务端(sshd)是 Linux 系统远程管理的核心组件,安装后必须立即进行基础安全加固,否则默认配置存在明显风险(如允许 root 直接登录、使用弱加密算法、未限制登录尝试等)。以下操作基于主流发行版(RHEL/CentOS 7+/Rocky/AlmaLinux、Ubuntu 20.04+),兼顾可用性与合规要求(参考等保2.0、CIS Benchmark v8.1 基线)。
一、安装 OpenSSH 服务端并确认运行状态
大多数服务器系统已预装 openssh-server,但需验证并确保服务启用:
- RHEL/CentOS/Rocky/AlmaLinux:
yum install -y openssh-server或dnf install -y openssh-server
启动并设为开机自启:systemctl enable --now sshd - Ubuntu/Debian:
apt update && apt install -y openssh-server
服务通常自动启动,检查状态:systemctl status sshd - 验证监听端口(默认 22):
ss -tlnp | grep :22或netstat -tlnp | grep sshd
二、修改主配置文件 /etc/ssh/sshd_config 实现基础合规
编辑前建议先备份:cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak.$(date +%Y%m%d)
以下参数需明确设置(非注释行),覆盖默认值。每改一项后执行 systemctl restart sshd 生效(注意:远程操作时建议保留一个活跃会话以防锁死):
-
禁用 root 密码登录,强制密钥认证:
PermitRootLogin no
PasswordAuthentication no
(部署前请确保普通用户已配置好 SSH 公钥,并能成功登录) -
限制登录用户或组(最小权限原则):
AllowUsers deploy admin(指定用户名,空格分隔)
或 AllowGroups sshusers(需提前创建组并加用户:groupadd sshusers; usermod -aG sshusers alice) -
关闭不安全协议和弱算法:
Protocol 2(禁用 SSHv1)
KexAlgorithms curve25519-sha256,ecdh-sha2-nistp256,diffie-hellman-group16-sha384,diffie-hellman-group18-sha512
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com,aes256-ctr,aes192-ctr,aes128-ctr
MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com,umac-128-etm@openssh.com -
增强访问控制与时效性:
MaxAuthTries 3(单次连接最多尝试 3 次密码/密钥)
LoginGraceTime 60(登录超时 60 秒)
ClientAliveInterval 300
ClientAliveCountMax 2(5 分钟无响应断开,共容忍 2 次失联)
三、配套系统级加固(非 sshd_config 内容但同等重要)
仅改 SSH 配置不够,还需结合系统机制提升整体安全性:
-
使用防火墙限制源 IP:
如用firewalld(RHEL系):firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="203.0.113.10" port port="22" protocol="tcp" accept'firewall-cmd --reload
Ubuntu 可用ufw:ufw allow from 203.0.113.10 to any port 22 -
启用失败登录保护(防暴力破解):
安装并启用fail2ban:yum install -y fail2ban或apt install -y fail2ban
启用 jail:systemctl enable --now fail2ban -
审计 SSH 登录行为:
确保rsyslog正常工作,检查/var/log/secure(RHEL)或/var/log/auth.log(Debian)是否有sshd日志;
可添加日志轮转策略,避免日志膨胀。
四、验证与持续维护
每次调整后务必验证效果,避免误配导致失连:
- 用新用户+密钥测试登录:
ssh -i ~/.ssh/id_rsa_deploy user@server_ip - 检查是否禁用了密码登录:
尝试ssh -o PubkeyAuthentication=no user@server_ip,应拒绝连接 - 用
ssh -vvv查看协商的密钥交换、加密算法,确认符合配置 - 定期更新 OpenSSH:
yum update openssh*或apt upgrade openssh-server
关注 CVE 公告,尤其涉及sshd的远程代码执行类漏洞(如 CVE-2024-6387)










