1.优化目标
| 维度 |
目标 |
| 性能 |
登录无卡顿(两大慢因) |
| 安全 |
收敛攻击面(禁用密码爆破面、限流) |
| 资源 |
防连接耗尽(MaxStartups 防爆破) |
| 审计 |
登录留痕、可追溯 |
2.性能优化
UseDNS no # 关键
GSSAPIAuthentication no # 关键
X11Forwarding no # 不转发 X11
CheckpointStateFile no # 不写 X11 检查点
| 参数 |
默认 |
为什么慢 |
| UseDNS |
yes |
登录前对客户端 IP 做反向DNS查询,内网/无 PTR 记录时卡 3~30s |
| GSSAPIAuthentication |
yes |
无KDC时每次连接等Kerberos协商超时 |
| X11Forwarding |
yes |
建连时做X11通道协商 |
3.安全加固
| 参数 |
默认 |
生产建议 |
说明 |
| PermitRootLogin |
yes |
no |
禁止root直登,普通用户 + sudo |
| PasswordAuthentication |
yes |
no(密钥铺好之后) |
密码爆破是最大风险,切纯密钥 |
| PermitEmptyPasswords |
no |
no |
永远保持 |
| MaxAuthTries |
6 |
3 |
单次连接尝试次数 |
| LoginGraceTime |
60 |
30 |
认证超时,超时断连 |
| AllowUsers / AllowGroups |
不限 |
白名单 |
只允许运维组登录 |
加密套件白名单(防弱算法降级攻击):
KexAlgorithms curve25519-sha256,diffie-hellman-group16-sha512
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com
MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com
⚠️ 大坑:加密套件收太严,旧客户端(老 Jenkins、Ansible、老脚本、Windows 旧版客户端)直接连不上。改之前先 sshd -T 对比,灰度验证。
SFTP 最小权限隔离(内网文件交换场景常用):
Match Group sftp
ChrootDirectory /data/sftp/%u
ForceCommand internal-sftp
X11Forwarding no
AllowTcpForwarding no
PermitTTY no
4.资源与防爆破
| 参数 |
建议 |
说明 |
| MaxStartups |
10:30:60 |
未认证并发 <10 全收;10~60 按 30% 概率丢弃;>60 全拒 —— 连接层防爆破 |
| MaxSessions |
10 |
单连接最多开几个会话 |
| ClientAliveInterval |
30 |
服务端发 keepalive |
| ClientAliveCountMax |
3 |
连续 3 次无响应(90s)断掉死连接 |
MaxStartups 10:30:60
配合客户端侧 ServerAliveInterval 30 双向保活,NAT/防火墙中间设备不会悄悄掐断长连接。
5.审计与日志
LogLevel VERBOSE # 记录每次认证成功/失败原因(日志量大,长期用 INFO)
SyslogIdentifier sshd # 日志前缀,方便 grep
journalctl -u sshd -f 实时看认证日志
- 生产常态:
fail2ban 监听认证失败自动封禁源 IP(5 次失败封 1h)
6.生产参考配置
# 性能
UseDNS no
GSSAPIAuthentication no
X11Forwarding no
CheckpointStateFile no
# 认证
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
MaxAuthTries 3
LoginGraceTime 30
AllowGroups ops devel
# 加密套件
KexAlgorithms curve25519-sha256,diffie-hellman-group16-sha512
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com
MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com
# 资源
MaxStartups 10:30:60
MaxSessions 10
ClientAliveInterval 30
ClientAliveCountMax 3
# 审计
LogLevel INFO
7.操作流程(防把自己锁在外面)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
sshd -t
systemctl reload sshd
ssh ops@10.0.0.61
sshd -T | egrep 'usedns|gssapi|permitrootlogin|passwordauthentication|maxstartups'
|