使用 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

参考

分析攻击情况:https://blog.csdn.net/qq_23936389/article/details/82230191?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-8.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-8.nonecase

posted @ 2020-07-05 03:25  水郁  阅读(556)  评论(0编辑  收藏  举报
……