Fail2Ban---VPS防护工具

📘 教程 · 01-10

Fail2Ban 是一个广泛使用的工具,用于检测恶意登录尝试和其他异常活动,并自动封锁攻击者的IP地址。您可以配置它来检测过多的连接请求,然后暂时封锁来自恶意IP地址的访问。


本文以Ubuntu22.04为例

安装与启动

  1. 安装
apt update -y
apt install -y fail2ban
  1. 启动
systemctl start fail2ban
  1. 开机自启
systemctl enable fail2ban
  1. 查看状态
systemctl status fail2ban

如果启动失败,配置完后面的设置后可以启动成果。

SSH防御 防止暴力破解

  1. 主配置文件创建本地副本
cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
  1. 删除安装时自动生成的默认配置文件
rm -rf /etc/fail2ban/jail.d/*
  1. 新建/etc/fail2ban/jail.d/sshd.local,并写入以下信息:
[sshd]

enabled = true
mode   = normal
backend = systemd
  1. 重启服务
systemctl restart fail2ban
  1. 查看封锁列表
fail2ban-client status
  1. 查看SSH封锁情况
fail2ban-client status sshd

网站防御

  1. 创建网站拦截规则
vim /etc/fail2ban/jail.d/nginx.local
  1. 写入以下信息:

其中:logpath是nginx访问日志的保存路径。Ubuntu中默认为/var/log/nginx/access.log

[nginx-http-auth]

enabled = true
mode = fallback
port = http,https
logpath = /var/log/nginx/access.log


[nginx-limit-req]

enabled = true
port = http,https
logpath = /var/log/nginx/access.log


[nginx-botsearch]

enabled = true
port = http,https
logpath = /var/log/nginx/access.log


[nginx-bad-request]

enabled = true
port = http,https
logpath = /var/log/nginx/access.log


[php-url-fopen]

enabled = true
port = http,https
logpath = /var/log/nginx/access.log

  1. 重启服务
systemctl restart fail2ban
  1. 查看nginx封锁情况
fail2ban-client status nginx-http-auth

查看总日志

tail -f /var/log/fail2ban.log

卸载

systemctl disable fail2ban
systemctl stop fail2ban
apt remove -y --purge fail2ban
find / -name "fail2ban" -type d
rm -rf /etc/fail2ban

参考资料

Theme Jasmine by Kent Liao