随机
Enter 搜索 ↑↓ 切换 Esc 清空

fail2ban

命令

日志审计封禁恶意IP安全防护程序

fail2ban

日志审计封禁恶意IP安全防护程序

补充说明

fail2ban 是一款入侵防御软件,通过扫描日志文件(如 /var/log/auth.log),识别多次认证失败的 IP 地址,并临时更新防火墙规则予以封禁,降低暴力破解攻击的风险。

安装

# Debian / Ubuntu
apt update && apt install fail2ban -y

# CentOS / RHEL / Fedora
yum install epel-release -y && yum install fail2ban -y

# Alpine
apk add fail2ban

# Arch Linux
pacman -S fail2ban --noconfirm

语法

fail2ban-client <子命令> [选项]
fail2ban-server [选项]

子命令

start              启动 fail2ban 服务
stop               停止 fail2ban 服务
reload             重新加载所有配置
restart            重启 fail2ban 服务
status             查看全局状态和所有监狱列表
status <监狱名>    查看指定监狱的状态(封禁 IP 列表)
set <监狱名> banip  <IP>    手动封禁 IP
set <监狱名> unbanip <IP>   手动解封 IP
ping               测试服务是否正常响应

常用配置

主配置文件:/etc/fail2ban/jail.conf 本地覆盖配置:/etc/fail2ban/jail.local

推荐创建 jail.local 写入自定义配置,避免升级时被覆盖:

[DEFAULT]
ignoreip = 127.0.0.1/8          # 白名单 IP(永远不被封禁)
bantime  = 1h                    # 封禁时长(默认 1 小时)
findtime = 10m                   # 统计时间窗口(10 分钟内)
maxretry = 5                     # 最大失败次数(超过则封禁)

[sshd]
enabled = true
port    = ssh
logpath = %(sshd_log)s

用法示例

查看服务状态

fail2ban-client status

输出示例:

Status
|- Number of jail:  1
`- Jail list:   sshd

查看指定监狱的封禁列表

fail2ban-client status sshd

输出示例:

Status for the jail: sshd
|- Filter
|  |- Currently failed: 3
|  |- Total failed:     27
|  `- File list:        /var/log/auth.log
`- Actions
   |- Currently banned: 2
   |- Total banned:     5
   `- Banned IP list:   192.168.1.100 10.0.0.55

手动封禁 IP

fail2ban-client set sshd banip 192.168.1.100

手动解封 IP

fail2ban-client set sshd unbanip 192.168.1.100

重新加载配置

fail2ban-client reload

修改 jail.local 后执行,使配置生效。

查看 fail2ban 日志

tail -f /var/log/fail2ban.log

测试配置是否正确

fail2ban-client -t

配置无错误时无输出,有错误会显示具体行号。

启动并设置开机自启

systemctl start fail2ban
systemctl enable fail2ban

自定义监狱示例

# /etc/fail2ban/jail.local

[DEFAULT]
ignoreip = 127.0.0.1/8
bantime  = 24h
findtime = 30m
maxretry = 3

[sshd]
enabled  = true
port     = ssh
logpath  = %(sshd_log)s
maxretry = 3
bantime  = 7d

[nginx-http-auth]
enabled  = true
port     = http,https
logpath  = /var/log/nginx/error.log
maxretry = 5
bantime  = 1h

[postfix]
enabled  = true
logpath  = /var/log/mail.log
maxretry = 3

[dovecot]
enabled  = true
logpath  = /var/log/dovecot/auth.log
maxretry = 3

安全提示

  1. 配置 ignoreip 将本地和信任 IP 加入白名单,避免误封;
  2. 开始使用前执行 fail2ban-client -t 检查配置语法;
  3. 修改配置后执行 fail2ban-client reload 重新加载,无需重启服务;
  4. 合理设置 maxretrybantime,避免正常用户被误封或封禁时间过短失效;
  5. fail2ban 依赖 iptables nf_tables 后端,确保防火墙服务正常运行。