Fail2ban 入侵防御软件应用总结

虽然最近fail2ban没有太多版本更新了,但它仍然是Linux系统入侵防御、防暴力破解的好帮手。它的原理是通过读应用程序产生的日志调用iptables产生阻挡策略。作为Linux系统管理员你会碰到恶意扫描、字典攻击、寻找漏洞等非法攻击,Fail2ban能够助你消除系统风险、防范入侵的重要手段之一。
通过Fail2ban你对恶意的IP进行阻断,发送告警通知。默认安装后Fail2ban提供了多种过滤器,如ssh、nginx、apache、postfix、dovecot等,下面配置中我们以ssh、postfix作为例子

Linux中安装Fail2ban(以CentOS7为例)

1
2
3
yum install epel-release
yum -y update
yum -y install fail2ban fail2ban-firewalld fail2ban-sendmail fail2ban-mail fail2ban-systemd

配置Fail2ban

  • 安装成功后,Fail2ban的配置文件默认是在/etc/fail2ban目录中的,主配置文件为jail.conf,包含了一些默认的设置及预计规则。在以后升级过程中会被覆盖,所以不要编辑该文件。正确的作法是在当前目录 创建一个jail.local的配置文件或者在jail.d目录下创建一个新文件编辑规则

    1
    cp jail.conf jail.local
  • 默认的配置中大部分配置都是很合理的,只有个别配置需要修改

    1
    2
    3
    4
    5
    6
    7
    8
    vim /etc/fail2ban/jail.local
    [DEFAULT]
    ignoreip = 127.0.0.1/8 192.168.5.0/24
    bantime = 600
    findtime = 600
    maxretry = 3
    destemail = info@example.com
    sender = robot@example.com
  • ignoreip 例外的IP地址列表,Fail2ban会把这里列的IP排队在规则之外,多个IP可以用空隔、逼号分隔

  • bantime 主机被禁的秒数
  • findtime 如果访问主机在这个时间内达到了maxretry数会触发自动防御机制
  • maxretry 最大尝试次数
  • destemail 阻挡后发送告警邮件接收地址
  • sender 发送地址,可以通过mailx配置发送帐号和密码

配置服务(以ssh和postfix为例)

  • Fail2ban已经默认预设了很多过滤器可以 /etc/fail2ban/filter.d中看到,如果不是非常规服务,我们只需在配置文件中启用即可,enable = true 为启用 false为禁用。
  • 启用SSH防护

    1
    2
    3
    4
    enabled = true
    port = ssh
    logpath = %(sshd_log)s
    backend = %(sshd_backend)s
  • 启用postfix防护

    1
    2
    3
    4
    5
    [postfix-sasl]
    port = smtp,465,submission,imap3,imaps,pop3,pop3s
    enabled = true
    logpath = %(postfix_log)s
    backend = %(postfix_backend)s

启动Fail2ban验证规则

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
systemctl enable fail2ban && systemctl start fail2ban

iptables -L
Chain INPUT (policy ACCEPT)
target prot opt source destination
f2b-sasl tcp -- anywhere anywhere tcp dpt:smtp
f2b-SSH tcp -- anywhere anywhere tcp dpt:ssh

Chain f2b-sasl (1 references)
target prot opt source destination
REJECT all -- 46.38.144.17 anywhere reject-with icmp-port-unreachable
REJECT all -- 46.38.144.32 anywhere reject-with icmp-port-unreachable
REJECT all -- 45.142.195.151 anywhere reject-with icmp-port-unreachable
RETURN all -- anywhere anywhere

fail2ban-client status postfix
Status for the jail: postfix
|- Filter
| |- Currently failed: 5
| |- Total failed: 983
| `- File list: /var/log/maillog
`- Actions
|- Currently banned: 21
|- Total banned: 21
`- Banned IP list: 103.133.110.77 112.45.122.7 116.239.253.30 116.239.255.7 170.239.87.183 185.36.81.39 193.32.160.146 193.32.160.147 193.32.160.148 193.32.160.149 193.32.160.150 193.32.160.151 193.32.160.152 193.32.160.153 193.32.160.154 193.32.160.155 193.56.28.119 222.161.221.230 45.142.195.151 45.227.253.139 94.102.57.19

从禁止列表中删除IP

1
fail2ban-client set ssh unbanip 8.8.8.8

参考文档

最后更新: 2023年08月27日 03:06

原始链接: https://blog.icanwen.com/2021/08/19/fail2ban/