Fail2ban简单配置

运行环境
  • 系统: Debian 11。
  • 用户: root用户。

安装fail2bannftables:

1
apt install fail2ban nftables

设置为开机自启:

1
2
systemctl enable fail2ban
systemctl enable nftables

启动:

1
2
systemctl start fail2ban
systemctl start nftables

检查运行状态:

1
2
systemctl status fail2ban
systemctl status nftables

编辑fail2banjail配置:

1
2
cp /etc/fail2ban/jail.{conf,local}
vim /etc/fail2ban/jail.local
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
[INCLUDES]
before = paths-debian.conf

[DEFAULT]
bantime.rndtime = 30m
ignoreself = true
ignoreip = 127.0.0.1/8 ::1
ignorecommand =
bantime  = 10m
findtime  = 10m
maxretry = 5
maxmatches = %(maxretry)s
backend = auto
usedns = warn
logencoding = auto
enabled = false
mode = normal
filter = %(__name__)s[mode=%(mode)s]

# ACTIONS
destemail = root@localhost
sender = root@<fq-hostname>
mta = sendmail
protocol = tcp
chain = <known/chain>
port = 0:65535
fail2ban_agent = Fail2Ban/%(fail2ban_version)s

banaction = nftables-multiport
banaction_allports = nftables-allports
action_ = %(banaction)s[port="%(port)s", protocol="%(protocol)s", chain="%(chain)s"]
action_mw = %(action_)s
            %(mta)s-whois[sender="%(sender)s", dest="%(destemail)s", protocol="%(protocol)s", chain="%(chain)s"]
action_mwl = %(action_)s
             %(mta)s-whois-lines[sender="%(sender)s", dest="%(destemail)s", logpath="%(logpath)s", chain="%(chain)s"]
action_xarf = %(action_)s
             xarf-login-attack[service=%(__name__)s, sender="%(sender)s", logpath="%(logpath)s", port="%(port)s"]
action_cf_mwl = cloudflare[cfuser="%(cfemail)s", cftoken="%(cfapikey)s"]
                %(mta)s-whois-lines[sender="%(sender)s", dest="%(destemail)s", logpath="%(logpath)s", chain="%(chain)s"]
action_blocklist_de  = blocklist_de[email="%(sender)s", service="%(__name__)s", apikey="%(blocklist_de_apikey)s", agent="%(fail2ban_agent)s"]
action_badips = badips.py[category="%(__name__)s", banaction="%(banaction)s", agent="%(fail2ban_agent)s"]
action_badips_report = badips[category="%(__name__)s", agent="%(fail2ban_agent)s"]
action_abuseipdb = abuseipdb
action = %(action_)s

# JAILS

[sshd]
enabled  = true
port     = 10022
filter   = sshd
mode     = aggressive
logpath  = %(sshd_log)s
backend  = %(sshd_backend)s
bantime  = 7d
findtime = 10m
maxretry = 2

重新启动fail2ban , 并检查其状态:

1
2
systemctl restart fail2ban
systemctl status fail2ban

使用fail2ban-client查看fail2ban的状态:

1
fail2ban-client status sshd

封禁某一IP:

1
fail2ban-client set sshd banip xx.xx.xx.xx

解封某一IP:

1
fail2ban-client set sshd unbanip xx.xx.xx.xx

重新启动nftables时, 确保也重新启动fail2ban服务, 以便其添加防火墙规则, 为此需要在两者之间添加服务依赖关系, 创建一个新文件/etc/systemd/system/fail2ban.service.d/override.conf并填入以下内容:

1
2
3
4
5
6
[Unit]
Requires=nftables.service
PartOf=nftables.service

[Install]
WantedBy=multi-user.target nftables.service

重新加载系统守护程序服务以包含此依赖项:

1
systemctl daemon-reload