2023-05-11  2024-09-18    887 字  2 分钟

安装 Fail2ban

1apt-get install fail2ban

Fail2ban 默认启用 ssh 的过滤器,可以在 /etc/fail2ban/jail.conf 查看,但是 Fail2ban 更新会覆盖此文件,建议复制一个 jail.local 进行编辑。

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

此后建议编辑 jail.local

对于 jail.local,你能找到许多 unit

例如 sshd 在文件中如此显示

1[sshd]
2#mode   = normal
3port    = ssh
4logpath = %(sshd_log)s
5backend = %(sshd_backend)s

输入

1fail2ban-client status
1Status
2|- Number of jail:      1
3`- Jail list:   sshd

可以看到,sshd的过滤器已经默认启动了。

更改默认配置

默认配置在 jail.local[DEFAULT] 下,推荐至少在 ignoreip 中加入自己常用的 ip,(如果不常用有固定公网 ip 登录的倒是无所谓)其他一些配置可以根据自己的需要酌情修改

默认日志路径配置(如mail、authpriv、user、ftp等等),依据系统而定,fail2ban在/etc/fail2ban/目录下提供了多种系统日志配置文件

 1before = paths-fedora.conf
 2# before = paths-debian.conf
 3
 4[DEFAULT]                      #全局配置
 5
 6ignoreip = 127.0.0.1           #忽略的IP列表,该Ip表将不受限制
 7
 8bantime = 600                  #被屏蔽时间, 单位:秒
 9
10findtime  = 600                #时间间隔,这个时间段内超过规定次数的主机将会被屏蔽
11
12maxretry = 5                   #最大尝试此时
13
14enabled = false                #全局禁止,在jail.local或jail.d/*.conf中开启相关联的配置
15
16
17destemail = root@localhost     #邮件接收人
18sender = root@localhost        #邮件发送人
19
20
21# action:触发后的动作
22
23#只屏蔽主机
24action_ = %(banaction)s[name=%(__name__)s, bantime="%(bantime)s", port="%(port)s", proto    col="%(protocol)s", chain="%(chain)s"]
25
26#屏蔽主机 并发送邮件
27action_mw = %(banaction)s[name=%(__name__)s, bantime="%(bantime)s", port="%(port)s", pro    tocol="%(protocol)s", chain="%(chain)s"]
28    %(mta)s-whois[name=%(__name__)s, sender="%(sender)s", dest="%(destemail)s",     protocol="%(protocol)s", chain="%(chain)s"]
29
30.......
31
32
33action = %(action_)s   #默认动作为只屏蔽主机,如需修改,只需在特定服务下配置该属性即可
34
35
36#服务配置, 以sshd 为例
37
38[sshd]
39# 开启防护
40enabled = true
41# 动作,只屏蔽(action_为默认动作,可省略)
42action = %(action_)s
43# 时间范围(s)
44findtim = 120
45# 时间范围内最大尝试次数
46maxretry = 3
47# 屏蔽时间(s)
48bantime = 180
49
50port = ssh
51logpath = %(sshd_log)s
52backend = %(sshd_backend)s

保存后启动fail2ban

1systemctl start fail2ban

添加配置:

jail.local 中本来就预设了一些配置,如需添加只需按照自己服务器的情况添加配置,同时添加 enabled = true 以启用此 jail

nginx 认证登录监控

1[nginx-http-auth]
2
3enabled  = true
4filter   = nginx-http-auth
5port     = http,https
6logpath  = /var/log/nginx/error.log

禁止一些恶意机器人

1[nginx-badbots]
2
3enabled  = true
4port     = http,https
5filter   = nginx-badbots
6logpath  = /var/log/nginx/access.log
7maxretry = 2

如果网络服务没有提供根目录的服务,可以开启以禁止访问根目录

1[nginx-nohome]
2
3enabled  = true
4port     = http,https
5filter   = nginx-nohome
6logpath  = /var/log/nginx/access.log
7maxretry = 2

防止被当作代理服务器

1[nginx-noproxy]
2
3enabled  = true
4port     = http,https
5filter   = nginx-noproxy
6logpath  = /var/log/nginx/access.log
7maxretry = 2

需要确认打开 Nginx 的 log 记录,并且正确填写目录
http 和 https 对应你在前文 NFW 中设置的 app

重启以应用更新

1systemctl restart fail2ban

以启用这些 jails

除另有声明外本博客文章均采用 知识共享 (Creative Commons) 署名 4.0 国际许可协议 进行许可转载请注明原作者与文章出处