# fail2ban 安装与配置记录

时间：2026-07-10 09:14

服务器：Ubuntu 20.04.4 LTS (iZbp13g2dkip356tj9ns1xZ)

---

## 安装

```bash
apt-get update -qq && apt-get install -y fail2ban
```

版本：0.11.1-1

---

## 配置

### 主配置文件

路径：`/etc/fail2ban/jail.local`

```ini
[DEFAULT]
bantime = 1h
bantime.increment = true
bantime.maxtime = 168h
bantime.rndtime = 10m
bantime.factor = 2
findtime = 10m
maxretry = 5
ignoreip = 127.0.0.1/8 ::1
backend = systemd
banaction = iptables-multiport
banaction_allports = iptables-allports
```

累进封禁说明：

- 首次 1h，再次 2h，第三次 4h，以此类推（factor=2）
- 上限 168h（7天），随机抖动 10min

### SSH 防护

```ini
[sshd]
enabled  = true
mode     = aggressive
port     = ssh
logpath  = %(sshd_log)s
backend  = %(sshd_backend)s
maxretry = 3
```

10分钟内 SSH 密码失败 3 次即封禁。mode=aggressive 会额外检测端口扫描等行为。

### Nginx 404 扫描防护

```ini
[nginx-404]
enabled  = true
port     = http,https
logpath  = /var/log/nginx/access.log
maxretry = 30
findtime = 60
bantime  = 7200
```

60秒内产生 30 次以上 404 即封禁 2 小时。

过滤器：`/etc/fail2ban/filter.d/nginx-404.conf`

```ini
[Definition]
failregex = ^<HOST> - - \[.*\] "(GET|POST|HEAD) [^"]*" 404 .*$
ignoreregex =
```

### Nginx .git 扫描防护

```ini
[nginx-git-scan]
enabled  = true
port     = http,https
logpath  = /var/log/nginx/access.log
maxretry = 1
findtime = 3600
bantime  = 86400
```

1小时内出现任何 .git 路径探测即封禁 24 小时。

过滤器：`/etc/fail2ban/filter.d/nginx-git-scan.conf`

```ini
[Definition]
failregex = ^<HOST> - - \[.*\] "(GET|POST) [^"]*\.git[^"]*" .*$
ignoreregex =
```

### Nginx PHP / CMS 漏洞扫描防护

```ini
[nginx-php-scan]
enabled  = true
port     = http,https
logpath  = /var/log/nginx/access.log
maxretry = 3
findtime = 300
bantime  = 3600
```

5分钟内探测 3 次 PHP/WP/admin 漏洞路径即封禁 1 小时。

过滤器：`/etc/fail2ban/filter.d/nginx-php-scan.conf`

```ini
[Definition]
failregex = ^<HOST> - - \[.*\] "(GET|POST) [^"]*(\.php|wp-admin|wp-login|xmlrpc|eval|phpmyadmin|jmx-console|web-console)[^"]*" .*$
ignoreregex =
```

---

## 过滤器测试结果

| 过滤器 | 匹配行数 | 状态 |
|---|---|---|
| sshd | 110 | 正常 |
| nginx-404 | 1285 | 正常 |
| nginx-git-scan | 65 | 正常 |
| nginx-php-scan | 264 | 正常 |

---

## 运行状态

已启用 4 个 jail：

- sshd（journal 读取）
- nginx-404（access.log 文件读取）
- nginx-git-scan（access.log 文件读取）
- nginx-php-scan（access.log 文件读取）

---

## 常用命令

```bash
# 查看所有 jail 状态
fail2ban-client status

# 查看某个 jail 详情
fail2ban-client status sshd

# 查看封禁列表
fail2ban-client banned

# 手动解封 IP
fail2ban-client set sshd unbanip 1.2.3.4

# 重启
systemctl restart fail2ban

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

# 测试过滤器
fail2ban-regex /var/log/nginx/access.log /etc/fail2ban/filter.d/nginx-404.conf
```

---

## 当前安全建议

已完成的加固：

- fail2ban 已安装并运行，SSH 和 Nginx 扫描均受保护

未处理的风险：

- SSH 仍允许 root + 密码登录（`PermitRootLogin yes` + `PasswordAuthentication yes`）
- 建议进一步配置 SSH 密钥登录并关闭密码认证
