SSH是管理Linux服务器的关键工具,但也是攻击者的主要目标。以下是保护SSH服务免受常见漏洞和攻击的综合指南。
问题:直接以root身份登录会暴露最高权限账户。
解决方案:
# 编辑SSH配置文件
sudo nano /etc/ssh/sshd_config
# 找到并修改以下行
PermitRootLogin no
问题:密码容易受到暴力破解和字典攻击。
解决方案:
# 生成SSH密钥对(在客户端)
ssh-keygen -t ed25519 -a 100 # 或使用rsa -b 4096
# 将公钥复制到服务器
ssh-copy-id -i ~/.ssh/id_ed25519.pub username@server_ip
# 在服务器上禁用密码认证
sudo nano /etc/ssh/sshd_config
PasswordAuthentication no
问题:默认22端口是自动化攻击的主要目标。
解决方案:
# 编辑SSH配置文件
sudo nano /etc/ssh/sshd_config
# 修改端口号(选择1024-65535之间的端口)
Port 2222 # 示例端口
# 更新防火墙规则
sudo ufw allow 2222/tcp
sudo ufw deny 22/tcp
问题:暴力破解攻击尝试大量组合。
解决方案:
# 安装fail2ban
sudo apt install fail2ban # Debian/Ubuntu
sudo yum install fail2ban # CentOS/RHEL
# 配置SSH防护
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
sudo nano /etc/fail2ban/jail.local
# 修改以下参数(示例)
[sshd]
enabled = true
port = 2222 # 与SSH端口匹配
maxretry = 3
bantime = 1h
问题:不必要的广泛访问权限。
解决方案:
# 只允许特定用户
sudo nano /etc/ssh/sshd_config
AllowUsers user1 user2
# 或允许特定用户组
AllowGroups sshusers
# 限制IP访问(使用防火墙)
sudo ufw allow from 192.168.1.100 to any port 2222
问题:旧版本和弱加密算法存在漏洞。
解决方案:
# 更新系统
sudo apt update && sudo apt upgrade # Debian/Ubuntu
sudo yum update # CentOS/RHEL
# 配置强加密算法
sudo nano /etc/ssh/sshd_config
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com
KexAlgorithms curve25519-sha256,curve25519-sha256@libssh.org
MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com
问题:单一认证因素不足。
解决方案:
# 安装Google Authenticator
sudo apt install libpam-google-authenticator # Debian/Ubuntu
sudo yum install google-authenticator # CentOS/RHEL
# 配置PAM
sudo nano /etc/pam.d/sshd
auth required pam_google_authenticator.so
# 配置SSH
sudo nano /etc/ssh/sshd_config
ChallengeResponseAuthentication yes
AuthenticationMethods publickey,keyboard-interactive
问题:缺乏对异常活动的监控。
解决方案:
# 查看SSH登录尝试
sudo grep 'sshd' /var/log/auth.log # Debian/Ubuntu
sudo grep 'sshd' /var/log/secure # CentOS/RHEL
# 使用工具如logwatch或OSSEC进行监控
sudo apt install logwatch
问题:不必要的功能增加攻击面。
解决方案:
sudo nano /etc/ssh/sshd_config
X11Forwarding no
AllowTcpForwarding no
PermitTunnel no
AllowAgentForwarding no
问题:长期使用相同密钥增加风险。
解决方案:
# 客户端生成新密钥
ssh-keygen -t ed25519 -a 100 -f ~/.ssh/id_ed25519_new
# 将新公钥添加到服务器
ssh-copy-id -i ~/.ssh/id_ed25519_new.pub username@server_ip
# 测试成功后,删除旧密钥
通过实施这些措施,您可以显著提高SSH服务的安全性,保护服务器免受大多数常见攻击。记得在应用任何更改后重启SSH服务:sudo systemctl restart sshd
。