XYCOVO CONSOLE KURISU · WEB 渗透 / AI 辅助攻防 ONLINE
#026 · 2025-01-30✓ PASS

SSH 安全加固

SSH 服务安全配置:密钥认证、端口变更、访问控制、Fail2Ban 防暴力破解及 sshd_config 硬化。
linux网络安全ssh安全加固AUTHOR: KURISU

SSH 是 Linux 服务器远程管理的标配,但默认配置存在安全风险。本文涵盖从基本加固到高级安全的完整方案。


一、安装与基础配置

dnf install -y openssh-server openssh-clients
systemctl enable --now sshd
systemctl status sshd
firewall-cmd --add-service=ssh --permanent && firewall-cmd --reload

二、安全加固配置

修改默认端口

echo 'Port 2222' >> /etc/ssh/sshd_config
semanage port -a -t ssh_port_t -p tcp 2222
firewall-cmd --add-port=2222/tcp --permanent
firewall-cmd --remove-service=ssh --permanent
firewall-cmd --reload

禁止 Root 远程登录

echo 'PermitRootLogin no' >> /etc/ssh/sshd_config

用户白名单

echo 'AllowUsers admin deployer' >> /etc/ssh/sshd_config
echo 'AllowGroups sshusers' >> /etc/ssh/sshd_config

连接限制

cat >> /etc/ssh/sshd_config << 'EOF'
MaxAuthTries 3
MaxSessions 10
ClientAliveInterval 300
ClientAliveCountMax 2
LoginGraceTime 30
Protocol 2
X11Forwarding no
PermitEmptyPasswords no
UseDNS no
EOF

强加密算法

cat >> /etc/ssh/sshd_config << 'EOF'
HostKeyAlgorithms ssh-ed25519
KexAlgorithms curve25519-sha256
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com
MACs hmac-sha2-512-etm@openssh.com
EOF

三、密钥认证(推荐)

# 生成 Ed25519 密钥
ssh-keygen -t ed25519 -C "admin@server"

# 部署公钥
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@server

# 设置正确权限
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys

# 确认密钥可用后,禁用密码登录
echo 'PasswordAuthentication no' >> /etc/ssh/sshd_config
echo 'ChallengeResponseAuthentication no' >> /etc/ssh/sshd_config
systemctl reload sshd

四、Fail2Ban 防护

dnf install -y fail2ban

cat > /etc/fail2ban/jail.local << 'EOF'
[sshd]
enabled = true
port = 2222
maxretry = 3
bantime = 3600
findtime = 600
EOF

systemctl enable --now fail2ban
fail2ban-client status sshd

五、SSH 高级功能

端口转发

ssh -L 8080:localhost:80 user@server      # 本地转发
ssh -R 9090:localhost:3000 user@server     # 远程转发
ssh -D 1080 user@server                    # SOCKS 代理

客户端配置

cat > ~/.ssh/config << 'EOF'
Host myserver
    HostName 47.100.49.228
    User root
    Port 2222
    IdentityFile ~/.ssh/id_ed25519
EOF
ssh myserver   # 使用别名

六、安全审计

who                   # 当前登录
last -n 20            # 登录历史
lastb -n 20           # 失败尝试
journalctl -u sshd -f # 实时日志
tail -f /var/log/secure

七、推荐生产配置

# 完整 /etc/ssh/sshd_config 安全基线
Port 2222
Protocol 2
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
MaxAuthTries 3
MaxSessions 5
ClientAliveInterval 300
ClientAliveCountMax 2
LoginGraceTime 30
AllowUsers admin
X11Forwarding no
AllowTcpForwarding no
PermitEmptyPasswords no
UseDNS no

验证并应用:sshd -t && systemctl reload sshd


← #025 Linux 计划任务…#027 SELinux 安全管理… →