Linux工具(1)fail2ban

fail2ban简介

fail2ban是一个用Python编写的开源入侵防御软件框架,主要用于保护Linux服务器免受暴力破解攻击。它通过监控日志文件,检测可疑的登录尝试,并根据预定义的规则自动封禁恶意IP地址,从而提高系统的安全性。

安装(ubuntu)

1
2
sudo apt-get update
sudo apt-get install fail2ban

查看服务状态

1
2
3
4
5
6
sudo systemctl status fail2ban

○ fail2ban.service - Fail2Ban Service
Loaded: loaded (/lib/systemd/system/fail2ban.service; disabled; vendor preset: enabled)
Active: inactive (dead)
Docs: man:fail2ban(1)

但是安装之后,并没有立刻启动fail2ban服务,需要先进行配置。

配置nginx

fail2ban的配置文件位于/etc/fail2ban/jail.conf,但建议不要直接修改该文件,而是创建一个新的本地配置文件/etc/fail2ban/jail.local,以便在软件更新时保留自定义设置。

1
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

启用nginx监控,在/etc/fail2ban/jail.local文件中找到以下部分并进行修改:

1
2
[nginx-http-auth]
enabled = true # 新增此项

启用fail2ban服务

1
2
3
sudo systemctl start fail2ban
sudo systemctl enable fail2ban
sudo systemctl status fail2ban

查看封禁状态

查看启用的封禁。

1
2
3
4
5
sudo fail2ban-client status

Status
|- Number of jail: 2
`- Jail list: nginx-http-auth, sshd

查看nginx-http-auth的封禁状态。

1
2
3
4
5
6
7
8
9
10
11
sudo fail2ban-client status nginx-http-auth

Status for the jail: nginx-http-auth
|- Filter
| |- Currently failed: 0
| |- Total failed: 0
| `- File list: /var/log/nginx/error.log
`- Actions
|- Currently banned: 0
|- Total banned: 0
`- Banned IP list:

测试规则

在一个服务器上面请求不存在的页面,多次触发nginx的401或者503错误,查看封禁状态。

1
2
3
4
5
6
7
8
9
10
sudo fail2ban-client status nginx-http-auth
Status for the jail: nginx-http-auth
|- Filter
| |- Currently failed: 0
| |- Total failed: 5
| `- File list: /var/log/nginx/error.log
`- Actions
|- Currently banned: 1
|- Total banned: 1
`- Banned IP list: 108.172.85.62

如果想要取消封禁,可以使用以下命令:

1
sudo fail2ban-client set nginx-http-auth unbanip 108.172.85.62

参考

How To Protect an Nginx Server with Fail2Ban on Ubuntu 20.04