Debian 12 安装配置 fail2ban 限制SSH访问

tanqi
18
2025-04-18

背景介绍

系统里面就收集到了很多的 SSH 恶意登录

1.配置fail2ban

# 安装 ufw 和 fail2ban sudo apt install -y ufw fail2ban # 配置 ufw 防火墙放行 SSH 端口 sudo ufw allow SSH # 开启 ufw sudo ufw enable sudo systemctl enable ufw --now

2.编辑文件

sudo vim /etc/fail2ban/jail.d/defaults-debian.conf
[DEFAULT]
# 忽略的 IP 地址, 相当于白名单
ignoreip = 1.1.1.1
# [重点] 指定使用 ufw 作为防护的操作
banaction = ufw
# 设置永久 Ban 时长
bantime = -1

[sshd]
enabled = true
# [重点] Debian 12 中的 SSH 审计日志都在 systemd 里面, 所以一定要指定
backend = systemd
filter = sshd

3.测试

sudo fail2ban-client status sshd

Status for the jail: sshd
|- Filter
|  |- Currently failed:	0
|  |- Total failed:	0
|  `- Journal matches:	_SYSTEMD_UNIT=sshd.service + _COMM=sshd
`- Actions
   |- Currently banned:	0
   |- Total banned:	0
   `- Banned IP list:	

直接用另一台电脑测试了一下:密码输错五次直接报错

查看一下日志

/var/log# cat fail2ban.log

2025-04-18 10:49:10,787 fail2ban.filter         [528336]: INFO    [sshd] Found 58.16.204.56 - 2025-04-18 10:49:10
2025-04-18 10:49:16,817 fail2ban.filter         [528336]: INFO    [sshd] Found 58.16.204.56 - 2025-04-18 10:49:16
2025-04-18 10:49:22,817 fail2ban.filter         [528336]: INFO    [sshd] Found 58.16.204.56 - 2025-04-18 10:49:22
2025-04-18 10:49:27,067 fail2ban.filter         [528336]: INFO    [sshd] Found 58.16.204.56 - 2025-04-18 10:49:26
2025-04-18 10:49:31,477 fail2ban.filter         [528336]: INFO    [sshd] Found 58.16.204.56 - 2025-04-18 10:49:31
2025-04-18 10:49:31,575 fail2ban.actions        [528336]: NOTICE  [sshd] Ban 58.16.204.56
2025-04-18 10:49:35,817 fail2ban.filter         [528336]: INFO    [sshd] Found 58.16.204.56 - 2025-04-18 10:49:35
2025-04-18 10:49:37,317 fail2ban.filter         [528336]: INFO    [sshd] Found 58.16.204.56 - 2025-04-18 10:49:36
sudo fail2ban-client status sshd

Status for the jail: sshd
|- Filter
|  |- Currently failed:	1
|  |- Total failed:	7
|  `- Journal matches:	_SYSTEMD_UNIT=sshd.service + _COMM=sshd
`- Actions
   |- Currently banned:	1
   |- Total banned:	1
   `- Banned IP list:	58.16.204.56

查看 ufw

sudo ufw status


Status: active
To                         Action      From
--                         ------      ----
Anywhere                   REJECT      58.16.204.56               # by Fail2Ban after 5 attempts against sshd

动物装饰