rahadbhuiya/cnsl
GitHub: rahadbhuiya/cnsl
一个面向 Linux 服务器的预 SIEM 意图感知安全层,通过实时分析认证日志识别攻击并自动阻断。
Stars: 0 | Forks: 0
# CNSL — 相关网络安全层
[](https://github.com/rahadbhuiya/cnsl/actions)
[](https://www.python.org)
[](LICENSE)
[]()
[]()
**CNSL** (Correlated Network Security Layer) 是一个开源、生产就绪的 **预 SIEM 意图感知安全层**,适用于 Linux 服务器。
它实时监控 `auth.log`,使用基于状态每 IP 的分析检测攻击模式,自动通过 `iptables` 或 `ipset` 屏蔽攻击者,向 Telegram/Discord/Slack 发送告警,并在实时 Web 仪表板中展示所有内容。
## 功能特性
| 功能 | 详情 |
|---|---|
| **实时检测** | 实时跟踪 `auth.log` — 毫秒级响应 |
| **3 种检测规则** | 暴力破解、凭证填充、凭证泄露 |
| **每 IP 有状态跟踪** | 滑动时间窗口,每个攻击 IP 独立状态 |
| **自动屏蔽** | `iptables` 或 `ipset`(高流量时更快) |
| **自动解封** | 临时屏蔽自动过期(默认:15 分钟) |
| **GeoIP 增强** | 国家、城市、ISP、代理/数据中心检测 — 无需 API 密钥 |
| **通知** | Telegram、Discord、Slack、自定义 Webhook |
| **实时 Web 仪表板** | 实时图表、屏蔽 IP、顶级攻击者、事件日志 |
| **SQLite 持久化** | 事件历史在重启后保留 |
| **Prometheus 指标** | `/api/metrics` 端点 — 可接入 Grafana |
| **允许列表** | 自己的 IP 永远不会被屏蔽 |
| **试运行模式** | 默认仅规划,不执行真实命令 — 安全试用 |
| **结构化 JSON 日志** | 每个事件输出到 `.jsonl` — 可接入 Loki、Elastic、Splunk |
| **tcpdump 提示** | 可选二级信号:ARP、SMB、mDNS |
| **零强制依赖** | 纯标准库核心;所有额外依赖均为可选 |
| **Docker 就绪** | 包含 Dockerfile |
## 检测规则
| 规则 | 含义 | 严重性 |
|---|---|---|
| **暴力破解** | 60 秒内来自同一 IP 的 >= 8 次失败登录 | 中等 |
| **凭证填充** | 来自同一 IP 的 >= 4 个不同用户名尝试 | 中等 |
| **凭证泄露** | SSH 成功但之前 >= 5 次失败 — 可能是被盗密码 | **高** -> 自动屏蔽 |
所有阈值均在 `config.json` 中可配置。
## 快速开始
```
# 1. 克隆
git clone https://github.com/rahadbhuiya/cnsl.git
cd cnsl
# 2. 安装
pip install -e ".[full]"
# 3. 运行(安全演练模式 — 无实际阻断)
sudo python -m cnsl
# 4. 打开 Web 仪表板
sudo python -m cnsl --dashboard
# 浏览器: http://127.0.0.1:8765
# 5. 准备好后启用实时阻断
sudo python -m cnsl --execute --dashboard
```
## 安装
```
pip install -e . # core only (stdlib, no external deps)
pip install -e ".[full]" # everything recommended
pip install -e ".[dev]" # + testing tools
```
| 额外包 | 安装内容 | 用途 |
|---|---|---|
| `full` | aiohttp, aiosqlite, pyyaml | 仪表板、数据库、YAML 配置 |
| `notify` | aiohttp | Telegram/Discord/Slack 告警 |
| `db` | aiosqlite | SQLite 持久化 |
| `yaml` | pyyaml | YAML 配置文件支持 |
| `dev` | pytest + 全部上述 | 运行测试 |
### 通过 pip(发布到 PyPI 后)
```
pip install cnsl
```
## 用法
```
sudo python -m cnsl [options]
Options:
--config FILE Config file path (.json or .yaml)
--iface IFACE Network interface for tcpdump (default: any)
--authlog PATH Auth log path (default: /var/log/auth.log)
--execute Enable real blocking (default: dry-run)
--backend BACKEND iptables or ipset (default: iptables)
--dashboard Enable web dashboard at http://127.0.0.1:8765
--no-tcpdump Disable tcpdump — auth.log only
--no-geoip Disable GeoIP lookups
--no-db Disable SQLite persistence
--version Show version
```
### 常见示例
```
# Ubuntu/Debian
sudo python -m cnsl --dashboard
# CentOS / RHEL / Fedora
sudo python -m cnsl --authlog /var/log/secure --dashboard
# ipset 后端(生产环境更快)
sudo python -m cnsl --execute --backend ipset --dashboard
# 仅 Auth.log,CPU 占用更低
sudo python -m cnsl --no-tcpdump
# 自定义配置
sudo python -m cnsl --config /etc/cnsl/config.json --execute --dashboard
```
## 配置
```
sudo mkdir -p /etc/cnsl
sudo cp config/config.example.json /etc/cnsl/config.json
sudo nano /etc/cnsl/config.json
```
**最小修改项:**
```
{
"authlog_path": "/var/log/auth.log",
"allowlist": [
"127.0.0.1",
"::1",
"YOUR_OWN_IP_HERE"
],
"actions": {
"dry_run": false,
"block_duration_sec": 900
}
}
```
完整配置参考:[`config/config.example.json`](config/config.example.json)
## 通知
```
"notifications": {
"min_severity": "MEDIUM",
"telegram": {
"enabled": true,
"bot_token": "123456:ABC...",
"chat_id": "-1001234567890"
},
"discord": {
"enabled": true,
"webhook_url": "https://discord.com/api/webhooks/..."
},
"slack": {
"enabled": true,
"webhook_url": "https://hooks.slack.com/services/..."
}
}
```
**Telegram 机器人设置:**
1. 打开 Telegram -> 搜索 `@BotFather`
2. 发送 `/newbot` -> 按步骤操作 -> 复制令牌
3. 将机器人添加到群组
4. 获取 `chat_id`:`https://api.telegram.org/bot/getUpdates`
## Web 仪表板
```
sudo python -m cnsl --dashboard
# 打开: http://127.0.0.1:8765
```
- 实时统计卡片 — 总事件数、高危告警、活跃屏蔽、唯一攻击者
- 图表 — 随时间的事件、严重性分布
- 活跃屏蔽表 — 支持一键手动解封
- 顶级攻击者 — 显示国家、城市、ISP
- 最近事件日志
- 实时事件流 — 所有 SSH 失败/成功通过 SSE 推送
## REST API
仪表板启用时可用:
```
curl http://127.0.0.1:8765/health # liveness probe
curl http://127.0.0.1:8765/api/stats # engine summary
curl http://127.0.0.1:8765/api/incidents # recent incidents
curl http://127.0.0.1:8765/api/blocks # active blocks
curl http://127.0.0.1:8765/api/top-attackers # top IPs
curl http://127.0.0.1:8765/api/metrics # Prometheus metrics
# 手动阻断
curl -X POST http://127.0.0.1:8765/api/block \
-H 'Content-Type: application/json' -d '{"ip": "1.2.3.4"}'
# 手动解封
curl -X POST http://127.0.0.1:8765/api/unblock \
-H 'Content-Type: application/json' -d '{"ip": "1.2.3.4"}'
```
## JSON 日志格式
```
{
"ts": 1713260000.0,
"time": "2024-04-16T10:00:00Z",
"type": "incident",
"payload": {
"src_ip": "1.2.3.4",
"severity": "HIGH",
"reasons": ["credential_breach: success after 6 fails (threshold=5)"],
"fail_count": 6,
"unique_users": 2,
"geo": {
"country": "China", "city": "Beijing",
"isp": "China Telecom", "flag": "CN",
"proxy": false, "hosting": true
}
}
}
```
```
# 实时视图
tail -f cnsl.jsonl | jq .
# 仅过滤 HIGH
tail -f cnsl.jsonl | jq 'select(.type=="incident" and .payload.severity=="HIGH")'
```
兼容:Grafana Loki、Elasticsearch、Splunk、Vector、Fluentd、Datadog。
## Prometheus / Grafana
添加到 `prometheus.yml`:
```
scrape_configs:
- job_name: cnsl
static_configs:
- targets: ['localhost:8765']
metrics_path: /api/metrics
```
指标:`cnsl_incidents_total{severity}`、`cnsl_blocks_active`、`cnsl_blocks_total`、
`cnsl_ssh_fails_total`、`cnsl_ip_fails_total{ip,country}`
## Docker
```
docker build -t cnsl .
docker run --rm \
--cap-add NET_ADMIN --cap-add NET_RAW \
--network host \
-v /var/log:/var/log:ro \
-v /etc/cnsl:/etc/cnsl:ro \
cnsl --config /etc/cnsl/config.json --execute --dashboard
```
## systemd 服务
```
sudo nano /etc/systemd/system/cnsl.service
```
```
[Unit]
Description=CNSL — SSH Intrusion Detection
After=network.target
[Service]
Type=simple
ExecStart=/usr/local/bin/cnsl --config /etc/cnsl/config.json --execute --dashboard
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
```
```
sudo systemctl daemon-reload
sudo systemctl enable --now cnsl
sudo journalctl -u cnsl -f
```
## 测试
```
pip install -e ".[dev]"
pytest tests/ -v
# 26 通过
```
## 项目结构
```
cnsl/
|
+-- cnsl/ <- Python package
| +-- __init__.py <- package version info
| +-- __main__.py <- enables: python -m cnsl
| +-- models.py <- Event, Detection dataclasses
| +-- config.py <- config loading + all defaults
| +-- logger.py <- async structured JSON logger
| +-- parsers.py <- auth.log + tcpdump parsers
| +-- detector.py <- stateful per-IP detection engine
| +-- blocker.py <- iptables / ipset blocking backend
| +-- sources.py <- async log tailers (auto-restart)
| +-- geoip.py <- GeoIP lookup + in-memory cache
| +-- notify.py <- Telegram, Discord, Slack, webhook
| +-- store.py <- SQLite persistent state
| +-- metrics.py <- Prometheus metrics counters
| +-- dashboard.py <- web dashboard + REST API + SSE
| +-- api.py <- standalone REST API (legacy)
| +-- engine.py <- main loop + CLI entrypoint
|
+-- tests/
| +-- test_cnsl.py <- 26 unit tests
|
+-- config/
| +-- config.example.json <- full config reference
|
+-- .github/
| +-- workflows/
| +-- ci.yml <- GitHub Actions CI (Python 3.10-3.12)
|
+-- Dockerfile
+-- setup.py
+-- requirements.txt
+-- LICENSE
+-- README.md
```
## 操作系统对应的 Auth 日志路径
| 操作系统 | 路径 | 参数 |
|---|---|---|
| Ubuntu / Debian | `/var/log/auth.log` | *(默认)* |
| CentOS / RHEL / Fedora | `/var/log/secure` | `--authlog /var/log/secure` |
| OpenSUSE | `/var/log/messages` | `--authlog /var/log/messages` |
## 路线图
- [ ] 基于国家的屏蔽 (`block_countries: ["CN", "RU"]`)
- [ ] AbuseIPDB 集成 — 社区威胁情报
- [ ] 重复违规者记忆 — 对已知不良 IP 降低阈值
- [ ] 分布式模式 — 多服务器通过 Redis 共享屏蔽列表
- [ ] 蜜罐端口检测 — 对 Telnet/RDP 探测即时屏蔽
- [ ] Grafana 仪表板 JSON 模板
- [ ] Web UI 认证 (JWT / Basic Auth)
- [ ] 邮件通知 (SMTP)
- [ ] Zeek 日志摄取
## 安全警告
`--execute` 会修改防火墙规则。启用前请确保:
- 在配置中将管理 IP 加入 **允许列表**
- 先在试运行模式测试(默认即为该模式)
- 确保拥有控制台/带外服务器访问权限
- 作者不对意外锁机负责
## 许可证
MIT — 参见 [LICENSE](LICENSE)。
标签:CNSL, Discord告警, FTP漏洞扫描, GeoIP, ipset, iptables, JSON结构化日志, Linux服务器, PoC, pre-SIEM, Prometheus指标, Slack告警, SQLite持久化, Telegram告警, Webhook通知, 主机级检测, 侦察活动, 允许列表, 凭证填充, 后渗透, 地理位置, 安全关联层, 安全编排, 实时仪表盘, 实时检测, 干运行模式, 开源安全工具, 异常检测, 意图驱动安全, 暴力破解, 滑动时间窗口, 状态跟踪, 生产级, 网络安全审计, 网络遥测, 自动阻断, 自定义请求头, 认证日志分析, 请求拦截, 逆向工具, 逆向工程平台