为了防止 CentOS 系统上的 SSH 服务被攻击,你可以采取以下措施:
- 更新系统:确保你的 CentOS 系统已更新到最新版本,以便修复已知的安全漏洞。
sudo yum update
- 更改默认 SSH 端口:将默认的 SSH 端口从 22 更改为其他端口,以减少自动攻击工具的成功率。
编辑 /etc/ssh/sshd_config
文件:
sudo vi /etc/ssh/sshd_config
找到 #Port 22
这一行,取消注释并更改端口号,例如:
Port 2222
保存文件并重启 SSH 服务:
sudo systemctl restart sshd
- 禁用 root 登录:编辑
/etc/ssh/sshd_config
文件,找到PermitRootLogin
这一行,将其更改为prohibit-password
或no
。
PermitRootLogin prohibit-password
保存文件并重启 SSH 服务:
sudo systemctl restart sshd
- 使用公钥认证:禁用密码认证,改为使用 SSH 密钥对进行身份验证。这将提高安全性,因为攻击者需要获取你的私钥才能登录。
在客户端生成 SSH 密钥对(如果尚未生成):
ssh-keygen
将公钥复制到服务器的 ~/.ssh/authorized_keys
文件中:
ssh-copy-id -p 2222 your_username@your_server_ip
确保 sshd_config
文件中的以下设置已启用:
PubkeyAuthentication yes PasswordAuthentication no
保存文件并重启 SSH 服务:
sudo systemctl restart sshd
- 使用防火墙限制访问:使用 firewalld 或 iptables 限制可以访问 SSH 服务的 IP 地址。
例如,使用 firewalld 仅允许特定 IP 地址访问 SSH:
sudo firewall-cmd --permanent --zone=public --add-rich-rule='rule family="ipv4" source address="your_ip_address" port protocol="tcp" port="2222" accept' sudo firewall-cmd --reload
- 使用 Fail2ban:安装并配置 Fail2ban 以阻止多次尝试登录失败的 IP 地址。
安装 Fail2ban:
sudo yum install fail2ban
创建一个新的 Fail2ban 配置文件 /etc/fail2ban/jail.local
,并添加以下内容:
[sshd] enabled = true port = 2222 filter = sshd logpath = /var/log/secure maxretry = 3 bantime = 600
启动并启用 Fail2ban 服务:
sudo systemctl start fail2ban sudo systemctl enable fail2ban
通过采取这些措施,你可以大大降低 CentOS 系统上 SSH 服务被攻击的风险。请确保定期检查和更新系统,以便保持安全性。