使用 Fail2ban 防止 ssh 暴力破解攻击
介绍
Fail2ban 通过扫描错误日志来禁止某些 IP 访问服务,它会直接修改防火墙规则来阻止来自这些 IP的请求。
起因
我在使用 journalctl -xe --full
查日志时,发现大量的类似下面的日志:
sshd[13352]: pam_unix(sshd:auth): check pass; user unknown
sshd[13352]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=182.61.161.121
sshd[13352]: Failed password for invalid user chase from 182.61.161.121 port 58172 ssh2
sshd[13352]: Received disconnect from 182.61.161.121 port 58172:11: Bye Bye [preauth]
sshd[13352]: Disconnected from 182.61.161.121 port 58172 [preauth]
sshd[13354]: reverse mapping checking getaddrinfo for dynamic-ip-1868417225.cable.net.co [186.84.172.25] failed - POSSIBLE BREAK-IN ATTEM
sshd[13354]: Invalid user survey from 186.84.172.25 port 38058
sshd[13354]: input_userauth_request: invalid user survey [preauth]
可以发现是有陌生 IP 的用户在尝试破解 SSH 登录。
通过这条命令可以看到的确有大量失败登录的记录:
grep -o "Failed password" /var/log/secure|uniq -c
73426 Failed password
。
因此我采取了一些措施,首先修改了 ssh 的默认端口:
vim /etc/ssh/sshd_config
改完后需要重启 sshd:
systemctl restart sshd
然后就是安装了 Fail2ban。
安装与配置
在我的 CentOS 服务器上用 yum 安装:
yum -y install fail2ban
然后进行配置:
vim /etc/fail2ban/jail.d/jail.local
其中 22 要改为实际的 ssh 端口:
[sshd]
enabled = true
filter = sshd
action = iptables[name=ssh,port=22,protocol=tcp]
logpath = /var/log/secure
bantime = 600
maxretry = 3
保存后重启服务
systemctl restart fail2ban
查看状态
fail2ban-client status sshd
参考
┆凉┆暖┆降┆等┆幸┆我┆我┆里┆将┆ ┆可┆有┆谦┆戮┆那┆ ┆大┆始┆ ┆然┆
┆薄┆一┆临┆你┆的┆还┆没┆ ┆来┆ ┆是┆来┆逊┆没┆些┆ ┆雁┆终┆ ┆而┆
┆ ┆暖┆ ┆如┆地┆站┆有┆ ┆也┆ ┆我┆ ┆的┆有┆精┆ ┆也┆没┆ ┆你┆
┆ ┆这┆ ┆试┆方┆在┆逃┆ ┆会┆ ┆在┆ ┆清┆来┆准┆ ┆没┆有┆ ┆没┆
┆ ┆生┆ ┆探┆ ┆最┆避┆ ┆在┆ ┆这┆ ┆晨┆ ┆的┆ ┆有┆来┆ ┆有┆
┆ ┆之┆ ┆般┆ ┆不┆ ┆ ┆这┆ ┆里┆ ┆没┆ ┆杀┆ ┆来┆ ┆ ┆来┆