ubuntu使用fail2ban防御ssh暴力破解

查看暴力破解IP

sudo grep "Failed password for root" /var/log/auth.log | awk '{print $11}' | sort | uniq -c | sort -nr | more

  不查不知道一查吓一跳,暴力破解最多的IP达到4千多次 

  


禁止root账号登录

修改/etc/ssh/sshd_config

# sudo vim /etc/ssh/sshd_config
找到并用#注释掉这行:PermitRootLogin prohibit-password
新建一行 添加:PermitRootLogin yes

重启服务
# sudo service ssh restart

解读一下这两句话

PermitRootLogin yes                             # 允许root登录,设为yes。

PermitRootLogin prohibit-password      # 允许root登录,但是禁止root用密码登录


安装fail2ban防暴力破解

安装fail2ban

更新软件仓库:   sudo apt-get update
安装fail2ban:  sudo apt-get install fail2ban

ssh服务器配置Fail2ban

新建配置文件:sudo vim /etc/fail2ban/jail.local

[DEFAULT]
# fail2ban忽略的IP
ignoreip = 192.168.145.23 113.168.58.39

# 客户端被禁止时长(秒)
bantime = 86400

# 客户端主机被禁止允许失败的次数
maxretry = 5

# 查找失败次数的时长(秒)
findtime = 600

#日志修改检测机制(gamin、polling和auto这三种)
backend = polling

[ssh-iptables]
enabled = true
filter = sshd
action = iptables[name=SSH, port=ssh, protocol=tcp]
sendmail-whois[name=SSH, [email protected], [email protected]]

重启服务:  sudo systemctl restart fail2ban

测试 fail2ban

测试fail2ban是否能正常工作,尝试通过使用错误的密码来用ssh连接到服务器模拟一个暴力破解攻击。同时监控/var/log/fail2ban.log,该文件记录在fail2ban中发生的任何敏感事件

监控:tail -f -n 10 /var/log/fail2ban.log

Fail2ban通过检测IP地址的多次失败登录尝试,禁止了一个IP地址:111.230.248.125

检查fail2ban状态

由于fail2ban的"ssh-iptables"监狱使用iptables来阻塞问题IP地址,你可以通过以下方式来检测当前iptables来验证禁止规则

sudo iptables --list -n

检验fail2ban状态(会显示出当前活动的监狱列表)

sudo fail2ban-client status

检验一个特定监狱的状态(例如ssh-iptables)

sudo fail2ban-client status ssh-iptables

上面的命令会显示出被禁止IP地址列表

解锁特定的IP地址

sudo fail2ban-client set ssh-iptables unbanip 192.168.1.8

设置 Fail2ban 开机自启

sudo systemctl enable fail2ban

注: 如果你停止了Fail2ban 服务,那么所有的IP地址都会被解锁。当你重启 Fail2ban,它会从/etc/log/secure(或 /var/log/auth.log)中找到异常的IP地址列表,如果这些异常地址的发生时间仍然在禁止时间内,那么Fail2ban会重新将这些IP地址禁止

 

个人博客

发布了59 篇原创文章 · 获赞 19 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43507959/article/details/102763985
今日推荐