参考文献

环境说明

  • nginx version: nginx/1.18.0
  • CentOS Linux release 8.3.2011
  • fail2ban 0.11.2
  • 防火墙:firewalld

问题说明

nginx access.log 有许多恶意访问路径记录,导致日志文件过大,占用服务器资源
例:

47.117.84.86 - - [18/Jun/2021:17:06:15 +0800] "GET /phpMyAdmin/ HTTP/1.1" 404 548 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safar
i/537.36"
47.117.84.86 - - [18/Jun/2021:17:06:15 +0800] "GET /phpmyadmin/ HTTP/1.1" 404 548 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safar
i/537.36"

步骤说明

安装 fail2ban

sudo dnf install fail2ban

启动&设置开机启动 fail2ban

sudo systemctl enable --now fail2ban
注:--now参数

  • 设置为开机自动:systemctl enable
  • 设置为开机自动并现在立刻启动:systemctl enable --now

配置 fail2ban

Fail2ban会按照以下顺序读取配置文件:

/etc/fail2ban/jail.conf
/etc/fail2ban/jail.d/*.conf
/etc/fail2ban/jail.local
/etc/fail2ban/jail.d/*.local

每个.local文件都会覆盖文件中的设置.conf。
示例配置

[nginx-cc]
enabled = true
port = http,https
filter = nginx-cc
action = %(action_mwl)s
maxretry = 3
findtime = 60
bantime = -1
logpath = /home/wwwlogs/access.log
[root@iZbp14vt99zpj8dde2fdlmZ wwwroot]# fail2ban-client status nginx-cc
Status for the jail: nginx-cc
|- Filter
|  |- Currently failed: 12
|  |- Total failed:     338
|  `- File list:        /home/wwwlogs/access.log
`- Actions
   |- Currently banned: 19
   |- Total banned:     21
   `- Banned IP list:   47.117.94.207 47.117.33.84 47.117.79.197 47.117.84.41 47.117.67.205 47.117.73.237 47.117.37.92 47.117.75.161 47.117.39.76 47.117.65.124 47.117.39.232 47.117.35.77 47.117.34.254 113.57.182.197 185.142.236.43 169.255.6.18 47.90.209.11 120.36.229.157 61.151.178.176