给ssh服务添加fail2ban安全认证

本文最后更新于:December 22, 2020 am

本文主要讲解在centos8系统中安装fail2ban服务来提供ssh服务的安全性。

本文参考链接

fail2ban用来保护ssh的原理非常简单,主要就是通过检测ssh的日志,记录下频繁登录失败的IP,然后使用iptables来直接禁用掉这个IP对应的请求即可实现ssh的防暴力破解。

1、安装fail2ban

centos中可以直接启用epel源来直接进行安装

1
2
yum install epel-release
yum install fail2ban

2、配置fail2ban

fail2ban的主要配置目录位于/etc/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
26
$ cat jail.local
[DEFAULT]
# 以空格分隔的列表,可以是 IP 地址、CIDR 前缀或者 DNS 主机名
# 用于指定哪些地址可以忽略 fail2ban 防御
ignoreip = 192.168.0.0/24

# 客户端主机被禁止的时长(秒)
bantime = 8640000

# 客户端主机被禁止前允许失败的次数
maxretry = 3

# 查找失败次数的时长(秒)
findtime = 600

mta = sendmail

[ssh-iptables]
enabled = true
filter = sshd
action = iptables[name=SSH, port=ssh, protocol=tcp]
sendmail-whois[name=SSH-Fail2ban, dest=example@mail.com, sender=fail2ban@email.com]
# Red Hat 系的发行版
logpath = /var/log/secure
# ssh 服务的最大尝试次数
maxretry = 3

3、重启服务

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
$ sudo systemctl restart fail2ban
$ sudo systemctl status fail2ban
● fail2ban.service - Fail2Ban Service
Loaded: loaded (/usr/lib/systemd/system/fail2ban.service; disabled; vendor preset: disabled)
Active: active (running) since Tue 2020-12-22 16:01:45 +08; 5s ago
Docs: man:fail2ban(1)
Process: 46536 ExecStartPre=/bin/mkdir -p /run/fail2ban (code=exited, status=0/SUCCESS)
Main PID: 46539 (f2b/server)
Tasks: 5 (limit: 408286)
Memory: 13.4M
CGroup: /system.slice/fail2ban.service
└─46539 /usr/bin/python3.6 -s /usr/bin/fail2ban-server -xf start

Dec 22 16:01:45 tiny-server systemd[1]: Starting Fail2Ban Service...
Dec 22 16:01:45 tiny-server systemd[1]: Started Fail2Ban Service.
Dec 22 16:01:45 tiny-server fail2ban-server[46539]: Server ready

# 测试是否正常运行
$ sudo fail2ban-client ping
Server replied: pong

# 添加服务开机启动
$ sudo systemctl enable fail2ban
Created symlink /etc/systemd/system/multi-user.target.wants/fail2ban.service → /usr/lib/systemd/system/fail2ban.service.

# 查看fail2ban的日志
$ tail -f /var/log/fail2ban.log

# 查看fail2ban状态
$ fail2ban-client status
Status
|- Number of jail: 1
`- Jail list: ssh-iptables
$ fail2ban-client status ssh-iptables
Status for the jail: ssh-iptables
|- Filter
| |- Currently failed: 0
| |- Total failed: 0
| `- File list: /var/log/secure
`- Actions
|- Currently banned: 0
|- Total banned: 0
`- Banned IP list:

# 查看iptables的禁用情况
sudo iptables --list -n

# 解禁一个特定IP
fail2ban-client set ssh-iptables unbanip 192.168.1.8