greenpdx/crmonban
GitHub: greenpdx/crmonban
基于 nftables 的入侵防御系统,实时监控服务日志并自动封禁恶意 IP,同时收集攻击者情报。
Stars: 3 | Forks: 1
# CR Monban

基于 nftables 的入侵防御系统,具备攻击者情报收集功能。
这是 fail2ban/crowdsec 的现代替代方案,直接使用 nftables 并收集有关攻击者的综合信息。
## 功能
- **nftables 集成** - 使用 nftables 集合实现 O(1) 的 IP 封禁(无需 iptables)
- **日志监控** - 实时监控 auth.log、nginx、apache、postfix、dovecot
- **攻击者情报** - 自动收集:
- GeoIP 位置(国家、城市、坐标)
- WHOIS 数据(组织、注册商、滥用联系人)
- 反向 DNS
- ASN 和 ISP 信息
- Shodan 数据(可选,需要 API key)
- AbuseIPDB 威胁评分(可选,需要 API key)
- **SQLite 数据库** - 用于封禁、事件、情报和白名单的持久化存储
- **CLI 界面** - 完整的命令行管理
- **Daemon 模式** - 具有自动封禁功能的 后台监控
- **白名单支持** - 保护受信任的 IP 免于被封禁
- **D-Bus 界面** - 提供外部控制和事件通知,便于与其他应用程序集成
- **Zone 支持** - 支持基于 Zone 的感知封禁,具备信任级别和隐式白名单
- **eBPF 快速路径** - 可选的 eBPF 集成,实现亚微秒级的 IP 封禁
- **共享白名单** - 多种白名单来源(数据库、Zone、文件、网络)
- **SIEM 导出** - 支持 CEF、LEEF、Syslog (RFC 5424) 和 JSON 格式
## 安装说明
### 从源码构建
```
# Clone the repository
git clone https://github.com/greenpdx/crmonban.git
cd crmonban
# Build
cargo build --release
# Install (optional)
sudo cp target/release/crmonban /usr/local/bin/
# Install D-Bus policy file
sudo cp dbus/org.crmonban.Daemon.conf /usr/share/dbus-1/system.d/
sudo systemctl reload dbus
```
### 依赖项
- Rust 2024 edition
- nftables(必须可用 nft 命令)
- 支持 nftables 的 Linux 内核
- D-Bus(用于支持 D-Bus 界面)
## 快速入门
```
# Generate default configuration
sudo mkdir -p /etc/crmonban
crmonban gen-config -o /etc/crmonban/config.toml
# Create database directory
sudo mkdir -p /var/lib/crmonban
# Initialize nftables table and sets
sudo crmonban init
# Start the daemon in foreground (for testing)
sudo crmonban start -f
# Or start as background daemon
sudo crmonban start
```
## CLI 命令
```
crmonban start [-f] Start monitoring daemon (-f for foreground)
crmonban stop Stop the daemon
crmonban status Show daemon status
crmonban ban [-d secs] Ban an IP address (-d duration, 0=permanent)
crmonban unban Unban an IP address
crmonban list [-f format] List active bans (table/json/simple)
crmonban intel [-r] [-j] Gather intel on IP (-r refresh, -j json)
crmonban whitelist add Add IP to whitelist
crmonban whitelist rm Remove IP from whitelist
crmonban whitelist list List whitelisted IPs
crmonban logs [-l limit] Show recent activity logs
crmonban stats Show attack statistics
crmonban init Initialize nftables configuration
crmonban flush --yes Flush all bans (dangerous!)
crmonban gen-config [-o path] Generate default configuration
```
## 配置
配置文件:`/etc/crmonban/config.toml`
### 常规设置
```
[general]
db_path = "/var/lib/crmonban/crmonban.db"
pid_file = "/var/run/crmonban.pid"
log_level = "info" # trace, debug, info, warn, error
auto_intel = true # Gather intel automatically on ban
default_ban_duration = 3600 # Default ban duration in seconds
```
### nftables 设置
```
[nftables]
table_name = "crmonban"
chain_name = "input"
set_v4 = "blocked_v4"
set_v6 = "blocked_v6"
priority = -100 # Chain priority (lower = earlier)
```
### 情报设置
```
[intel]
geoip_enabled = true
rdns_enabled = true
whois_enabled = true
timeout_secs = 10
# Optional API keys for enhanced intelligence
# shodan_api_key = "your-key"
# abuseipdb_api_key = "your-key"
```
### 服务监控
```
[services.ssh]
enabled = true
log_path = "/var/log/auth.log"
max_failures = 5 # Failures before ban
find_time = 600 # Time window (seconds)
ban_time = 3600 # Ban duration (seconds)
[[services.ssh.patterns]]
name = "failed_password"
regex = 'Failed password for .* from (?P\d+\.\d+\.\d+\.\d+)'
event_type = "failed_auth"
[[services.ssh.patterns]]
name = "invalid_user"
regex = 'Invalid user .* from (?P\d+\.\d+\.\d+\.\d+)'
event_type = "invalid_user"
```
### 可用服务
- **ssh** - SSH 身份验证失败(默认启用)
- **nginx** - 速率限制违规
- **apache** - 身份验证失败
- **postfix** - SMTP 身份验证失败
- **dovecot** - IMAP/POP3 身份验证失败
### D-Bus 设置
```
[dbus]
enabled = true # Enable D-Bus interface
system_bus = true # Use system bus (recommended for daemon)
```
## D-Bus 界面
crmonban 暴露了 D-Bus 接口,供外部应用程序控制 daemon 并接收事件。
**服务**:`org.crmonban.Daemon`
**对象路径**:`/org/crmonban/Daemon`
### 方法
| 方法 | 参数 | 返回值 | 描述 |
|--------|------------|---------|-------------|
| `Status` | - | `StatusInfo` | 获取 daemon 状态 |
| `Ban` | `ip: String, duration_secs: u32, reason: String` | `bool` | 封禁 IP 地址 |
| `Unban` | `ip: String` | `bool` | 解封 IP 地址 |
| `GetBans` | - | `Array` | 列出活跃的封禁 |
| `IsBanned` | `ip: String` | `bool` | 检查 IP 是否被封禁 |
### 属性
| 属性 | 类型 | 描述 |
|----------|------|-------------|
| `Running` | `bool` | 如果可达则始终为 true |
| `ActiveBanCount` | `u64` | 活跃封禁的数量 |
| `UptimeSeconds` | `u64` | daemon 运行时间(秒) |
| `EventsProcessed` | `u64` | 已处理的事件总数 |
### 信号
| 信号 | 参数 | 描述 |
|--------|------------|-------------|
| `BanAdded` | `ip, reason, source, duration_secs` | 当 IP 被封禁时触发 |
| `BanRemoved` | `ip, reason` | 当 IP 被解封时触发 |
| `AttackDetected` | `ip, service, event_type` | 每次检测到攻击时触发 |
| `DaemonStarted` | - | 当 daemon 启动时触发 |
| `DaemonStopping` | - | 当 daemon 停止时触发 |
### 示例:使用 dbus-monitor 监控事件
```
dbus-monitor --system "interface='org.crmonban.Daemon'"
```
### 示例:使用 busctl 查询状态
```
busctl call org.crmonban.Daemon /org/crmonban/Daemon org.crmonban.Daemon Status
```
## 高级配置
### Zone 配置
```
[zones]
enabled = true
config_file = "/etc/crmonban/zones.yaml"
whitelist_threshold = 80 # Trust level for implicit whitelist
[[zones.zones]]
name = "internal"
trust_level = 80
networks = ["10.0.0.0/8", "192.168.0.0/16"]
implicit_whitelist = true
[[zones.zones]]
name = "external"
trust_level = 0
networks = ["0.0.0.0/0"]
```
### SIEM 导出
```
[siem]
enabled = true
format = "cef" # cef, leef, syslog, json
[[siem.targets]]
type = "file"
path = "/var/log/crmonban/siem.log"
[[siem.targets]]
type = "syslog"
socket = "/dev/log"
[[siem.targets]]
type = "webhook"
url = "https://siem.example.com/api/events"
headers = [["Authorization", "Bearer token"]]
```
### eBPF 快速路径封禁
```
[ebpf]
enabled = true
method = "mapfile" # mapfile, disabled (dbus requires crrouter feature)
sync_interval_secs = 60 # Sync with nftables
max_entries = 10000
# For mapfile method:
[ebpf.method]
path = "/sys/fs/bpf/crmonban_blacklist"
```
### 共享白名单
```
[whitelist]
enabled = true
cache_ttl_secs = 300
[[whitelist.sources]]
type = "database" # Local crmonban whitelist
[[whitelist.sources]]
type = "zones" # Zone-based implicit whitelist
[[whitelist.sources]]
type = "networks"
networks = ["10.0.0.0/8", "172.16.0.0/12"]
[[whitelist.sources]]
type = "file"
path = "/etc/crmonban/whitelist.txt"
watch = true
[[whitelist.sources]]
type = "daemon" # Query external daemon via D-Bus (requires crrouter feature)
```
### 外部 Daemon 集成
在外部防火墙 daemon 中启用 crmonban 插件:
```
# Build with crmonban support
cargo build --features crmonban
# The plugin provides these JSON-RPC methods:
# crmonban.status - Get crmonban daemon status
# crmonban.bans - List active bans
# crmonban.ban - Ban an IP
# crmonban.unban - Unban an IP
# crmonban.sync - Sync bans to eBPF
```
## nftables 结构
crmonban 创建以下 nftables 结构:
```
table inet crmonban {
set blocked_v4 {
type ipv4_addr
flags timeout
}
set blocked_v6 {
type ipv6_addr
flags timeout
}
chain input {
type filter hook input priority -100; policy accept;
ip saddr @blocked_v4 drop
ip6 saddr @blocked_v6 drop
}
}
```
## Systemd 服务
创建 `/etc/systemd/system/crmonban.service`:
```
[Unit]
Description=crmonban intrusion prevention system
After=network.target
[Service]
Type=forking
PIDFile=/var/run/crmonban.pid
ExecStart=/usr/local/bin/crmonban start
ExecStop=/usr/local/bin/crmonban stop
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure
[Install]
WantedBy=multi-user.target
```
启用并启动:
```
sudo systemctl enable crmonban
sudo systemctl start crmonban
```
## 示例
### 手动封禁 24 小时
```
sudo crmonban ban 192.168.1.100 -d 86400 -r "Port scanning"
```
### 收集某个 IP 的情报
```
crmonban intel 8.8.8.8
```
输出:
```
IP: 8.8.8.8
Gathered: 2024-01-15 10:30:00 UTC
--- Location ---
Country: United States (US)
City: Mountain View, California
Coordinates: 37.4056, -122.0775
Timezone: America/Los_Angeles
--- Network ---
ASN: AS15169 (Google LLC)
ISP: Google LLC
Reverse DNS: dns.google
--- Flags ---
⚠ Hosting/Datacenter
```
### 查看攻击统计
```
crmonban stats
```
### 将受信任的服务器加入白名单
```
sudo crmonban whitelist add 10.0.0.1 -c "Internal monitoring server"
```
## 架构
```
┌─────────────────────────────────────────────────────────────┐
│ crmonban │
├─────────────────────────────────────────────────────────────┤
│ CLI Interface │
│ ├── ban/unban/list │
│ ├── whitelist management │
│ ├── intel gathering │
│ └── statistics │
├─────────────────────────────────────────────────────────────┤
│ Daemon │
│ ├── Log Monitor (watches files, matches patterns) │
│ ├── Event Processor (counts failures, triggers bans) │
│ ├── Intel Gatherer (GeoIP, WHOIS, rDNS) │
│ └── Cleanup Task (removes expired bans) │
├─────────────────────────────────────────────────────────────┤
│ Firewall (nftables) │ Database (SQLite) │
│ ├── Table: crmonban │ ├── bans │
│ ├── Sets: blocked_v4/v6 │ ├── events │
│ └── Chain: input │ ├── intel │
│ │ ├── whitelist │
│ │ └── activity_log │
└─────────────────────────────────────────────────────────────┘
```
## 许可证
LGPL 2
## 贡献
欢迎贡献!请在 GitHub 上提交 issue 或 pull request。
标签:CISA项目, Docker镜像, nftables, Rust, 入侵防御系统, 可视化界面, 威胁情报, 威胁猎捕, 开发者工具, 网络流量审计, 通知系统