# fail2ban 安装与配置记录

**日期**: 2026-07-10
**服务器**: 124.220.53.46 (腾讯云 Ubuntu 24.04)

---

## 1. 背景

服务器持续遭受 SSH 暴力破解和 Web 漏洞扫描：

### SSH 攻击概况
- 最近 3 天失败登录记录 **755 条**
- 单 IP `35.200.201.144` 在 7月5日集中暴破 **364 次**，枚举了 oracle/es/nvidia/nexus/wang/guest/sugi 等数十个用户名
- `47.253.221.248` 进行字典攻击：admin2→adminuser→amir→azureuser→backup→data→root→elasticsearch→esroot
- 被尝试最多的用户名：root(98次) > admin(20) > oracle(18) > ftpuser/deploy/user(各12)
- 所有攻击均未成功

### Web 扫描概况
- `.git` 源码泄露探测（路径遍历 + URL 编码绕过）
- CGI 路径穿越攻击 `/cgi-bin/..%2e/bin/sh`
- PHP pearcmd RCE 尝试
- `wp-admin/install.php` 探测
- ASP 登录页扫描

### 原有防护
- iptables 有基础规则（腾讯云镜 YJ-FIREWALL 链）
- 无自动封禁机制，攻击者可无限重试

---

## 2. 安装

```bash
sudo apt update
sudo apt install -y fail2ban
```

安装版本：`fail2ban 1.0.2-3ubuntu0.1`

---

## 3. 配置

配置文件路径：`/etc/fail2ban/jail.local`

```ini
[DEFAULT]
bantime = 3600          # 封禁 1 小时
findtime = 600          # 10 分钟内
maxretry = 3            # 3 次失败即封
banaction = iptables-multiport    # 兼容腾讯云 iptables
banaction_allports = iptables-allports
backend = systemd       # 使用 journald
ignoreip = 127.0.0.1/8 ::1 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16

[sshd]
enabled = true
port = ssh
logpath = %(sshd_log)s
maxretry = 3
bantime = 3600          # SSH 单独 1 小时

[recidive]
enabled = true
logpath = /var/log/fail2ban.log
banaction = iptables-allports
bantime = 604800        # 屡犯者：封 7 天
findtime = 86400        # 24 小时内再次被封
maxretry = 3
```

### 配置要点
- 使用 `iptables-multiport` 而非 `nftables`（系统使用 iptables + 腾讯云镜 YJ-FIREWALL 链）
- 启用 `recidive` jail：被封过又回来的 IP 升级为全端口封禁 7 天
- 白名单排除本机和内网，避免误封

---

## 4. 启动与验证

```bash
sudo systemctl restart fail2ban
sudo systemctl enable fail2ban
sudo fail2ban-client status
```

输出：
```
Status
|- Number of jail:  2
`- Jail list:   recidive, sshd
```

### Filter 匹配测试
```bash
sudo fail2ban-regex /var/log/auth.log "sshd"
```
结果：23114 行日志中匹配到 **755 条**攻击记录，确认 filter 正常工作。

---

## 5. 常用运维命令

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

# 查看 sshd jail 详情（含封禁列表）
sudo fail2ban-client status sshd

# 手动封禁 IP
sudo fail2ban-client set sshd banip <IP>

# 手动解封 IP
sudo fail2ban-client set sshd unbanip <IP>

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

# 查看 iptables 中 fail2ban 的规则
sudo iptables -L -n | grep f2b
```

---

## 6. 预期效果

配置后，暴力破解行为将受到自动封禁：

1. **首次违规**：10 分钟内 SSH 失败 3 次 → 封禁 1 小时
2. **屡犯升级**：24 小时内被封 3 次 → 全端口封禁 7 天
3. 封禁动作在 iptables INPUT 链顶部插入，优先于所有放行规则

之前像 `35.200.201.144`（364 次暴破）这样的攻击，在启用 fail2ban 后会在第 3 次失败即被封禁，无法继续。
