ParshwaBhavsar/authdetect
GitHub: ParshwaBhavsar/authdetect
一款纯 Python 实现的兼容 Sigma 规则的身份验证日志流式检测引擎,能够自动解析多种日志格式并生成带有 MITRE ATT&CK 映射的结构化安全告警。
Stars: 0 | Forks: 0
# authdetect





**通过兼容 Sigma 的检测规则流式处理身份验证日志,并获取带有 MITRE ATT&CK 映射的结构化告警。**
将 `authdetect` 指向任何身份验证日志 —— JSON、nginx Combined Log Format 或 Linux `auth.log` —— 它会根据检测规则库评估每一个事件,在出现攻击模式时触发按严重程度分级的告警。输出内容可以是供人类阅读的 `rich` 终端表格,也可以是 NDJSON 格式,以便通过管道传输至 SIEM、Slack webhook 或 `jq`。
## 目录
- [为什么开发此工具](#why-this-exists)
- [功能](#features)
- [安装说明](#install)
- [快速开始](#quick-start)
- [用法](#usage)
- [输出示例](#example-output)
- [工作原理](#how-it-works)
- [检测规则格式](#detection-rule-format)
- [内置规则库](#bundled-rule-library)
- [支持的日志格式](#supported-log-formats)
- [测试](#testing)
- [项目结构](#project-structure)
- [展示的概念](#concepts-demonstrated)
- [扩展 authdetect](#extending-authdetect)
- [客观存在的局限性](#honest-limitations)
- [路线图](#roadmap)
- [道德与范围](#ethics--scope)
- [许可协议](#license)
## 为什么开发此工具
检测工程是将攻击者的行为转化为规则,以便监控系统能够实时进行评估的实践。表达这些规则的最常见标准是 [Sigma](https://github.com/SigmaHQ/sigma) —— 一种供应商中立的 YAML 格式,只需编写一次检测逻辑,即可将其编译为 Splunk、Elastic、Sentinel 或任何其他后端使用的规则。
`authdetect` 使用纯 Python 实现了一个兼容 Sigma 的检测引擎,专注于身份验证和会话管理攻击模式:这类威胁出现在每一份 OWASP Top 10 列表中,并构成了大部分账户接管事件。
通过从零开始实现该引擎(而不是封装现有的 SIEM),该项目展示了对检测规则实际运作方式的全面理解 —— 从条件解析到滑动窗口聚合,再到告警富化 —— 而不仅仅是知道如何配置托管服务。
## 功能
- **兼容 Sigma 的规则格式** — 包含字段匹配、布尔逻辑(`and` / `or` / `not`)和聚合条件的 YAML 规则
- **滑动窗口聚合** — 具有时间限制的基于计数的规则(例如“60秒内来自同一 IP 的 5 次以上失败登录”),并带有按组划分的状态
- **字段修饰符** — `contains`、`startswith`、`endswith`、`re` (regex) 以及普通相等判断 / 列表成员匹配
- **三种日志格式解析器** — 自动检测:JSON/NDJSON、Combined Log Format (nginx/Apache)、Linux `auth.log`
- **JWT 字段提取** — 自动从 `Authorization` 标头的 Bearer token 中解码算法和 JTI
- **MITRE ATT&CK 富化** — 每条告警都包含战术和技巧 ID
- 每条规则都包含 **CWE / OWASP 参考**
- **两种输出模式** — `rich` 终端表格(人类可读)和 NDJSON 流(用于机器读取 / SIEM 摄取)
- **`watch` 模式** — 持续追踪不断增长的日志文件,并实时输出告警流
- **`validate` 命令** — 在部署前对所有规则进行语法检查
- **`generate-logs` 命令** — 生成能够触发所有内置规则的合成测试日志
## 安装说明
```
git clone https://github.com/ParshwaBhavsar/authdetect.git
cd authdetect
pip install -r requirements.txt
pip install -e . # optional: installs the `authdetect` command
```
需要 Python 3.10+。运行时依赖:`pyyaml`、`rich`。
## 快速开始
```
# 1. 生成 synthetic logs(无真实 credentials — 完全虚构的数据)
python -m authdetect generate-logs --output sample.ndjson
# 2. 使用所有 bundled rules 对 logs 运行检测
python -m authdetect analyze --logfile sample.ndjson --rules rules/
# 3. 验证所有 rules 均能顺利解析
python -m authdetect validate rules/
```
## 用法
```
# 分析 log file — 丰富的 terminal 输出
python -m authdetect analyze --logfile /var/log/nginx/access.log --rules rules/
# JSON 输出,用于通过管道传递给 jq 或 SIEM
python -m authdetect analyze --logfile auth.ndjson --rules rules/ --format json
# 仅筛选 HIGH 及以上级别
python -m authdetect analyze --logfile auth.ndjson --rules rules/ --min-severity high
# 显式指定 log format(默认:auto-detect)
python -m authdetect analyze --logfile auth.log --rules rules/ --input-format auth
# tail 实时 log file 并在警报触发时 stream 警报
python -m authdetect watch --logfile /var/log/app/auth.ndjson --rules rules/
# 验证 rule 语法
python -m authdetect validate rules/
# 编写 31 个 synthetic events,涵盖所有 bundled detection 场景
python -m authdetect generate-logs --output test.ndjson
```
## 输出示例
针对合成日志(31 个事件,12 条规则,15 条告警)运行的结果:
```
Loaded 12 rule(s) from rules/
authdetect — 15 alert(s)
┏━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┓
┃ Sev ┃ Rule ID ┃ Timestamp ┃ Src IP ┃ User ┃
┡━━━━━━━━━━╇━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━┩
│ 🔴 │ AUTHDET-007 │ 2025-06-01 12:00:00 │ 9.8.7.6 │ attacker │
│ CRITICAL │ │ │ │ │
│ │ │ JWT Algorithm None — Signature Bypass Attempt │
│ │ │ [MITRE] T1550.001 │
│ 🟠 HIGH │ AUTHDET-001 │ 2025-06-01 11:59:57 │ 1.2.3.4 │ admin │
│ │ │ Brute Force Authentication Attempt │
│ │ │ 8 events in 60s · src_ip=1.2.3.4 │
│ 🟠 HIGH │ AUTHDET-005 │ 2025-06-01 11:59:00 │ 22.33.44.55 │ — │
│ │ │ Session Fixation Attempt │
│ 🟡 MED │ AUTHDET-009 │ 2025-06-01 11:59:45 │ 11.22.33.44 │ bob │
│ │ │ Authentication Token Transmitted in URL │
└──────────┴────────────────┴─────────────────────┴────────────────┴─────────────┘
╭─────────────── Summary ────────────────╮
│ Events processed: 31 │
│ Total alerts: 15 │
│ 🔴 CRITICAL: 1 │
│ 🟠 HIGH: 6 │
│ 🟡 MEDIUM: 8 │
│ Top rules: │
│ Known Attack Tool User Agent 7 │
│ Brute Force Authentication 3 │
│ JWT Algorithm None — Bypass 1 │
╰────────────────────────────────────────╯
```
## 工作原理
```
log file
│
▼
parsers.py auto-detect format → normalise to LogEvent
│ (JSON / Combined Log Format / auth.log)
▼
engine.py for each event, evaluate all loaded rules
│
├── SIMPLE rule match field values with modifiers
│ (single event) resolve boolean condition string
│
└── AGGREGATION rule maintain per-rule sliding time window
(time-bounded) count events grouped by a field
fire when threshold is crossed
│
▼
model.py build Alert with context, severity, MITRE
│
▼
report.py render rich terminal table / NDJSON stream
```
**滑动窗口状态**使用内存中的 `deque` 按 `(rule_id, group_value)` 对进行保存。当超过聚合阈值时,窗口会被清除,因此引擎不会在随后的每一个事件上重复触发。
**条件解析器**是一个递归下降的微型语言,支持 `and`、`or`、`not` 以及裸露的选择器名称。它可以处理像 `selection and not filter` 或 `sel1 or sel2` 这样的复合条件。
## 检测规则格式
规则是受 Sigma 启发的 YAML。一个最简的规则如下:
```
title: Failed Login
id: EXAMPLE-001
detection:
selection:
status_code: 401
condition: selection
level: low
```
### 字段修饰符
```
detection:
selection:
path|contains: /admin # substring
path|startswith: /api/ # prefix
path|endswith: .php # suffix
path|re: ".*token=[A-Za-z0-9]{8,}.*" # regex
status_code: [401, 403] # list → OR
user_agent: sqlmap # exact match
```
### 聚合(时间窗口阈值)
```
detection:
selection:
status_code: 401
path|contains: login
condition: selection | count(src_ip) > 5
timeframe: 60s # also: 5m, 1h, 1d
level: high
```
### 布尔逻辑
```
detection:
selection:
status_code: 401
filter:
src_ip: 10.0.0.1 # known-good internal scanner
condition: selection and not filter
```
### 完整规则 schema
```
title: Human-readable name # required
id: AUTHDET-NNN # required
status: stable | experimental | deprecated
description: |
Multi-line explanation of what this detects and why.
author: your-name
date: YYYY-MM-DD
logsource:
category: authentication | web | syslog
detection:
: # any name; 'filter*' names are for exclusions
: # or list of values (OR)
|:
condition: [| count() > ]
timeframe: # required for aggregation rules
level: info | low | medium | high | critical
mitre_attack:
tactics: [credential-access, defense-evasion]
techniques: [T1110.001, T1110.003]
references:
- cwe: CWE-307
- owasp: "A07:2021 – Identification and Authentication Failures"
- url: https://attack.mitre.org/techniques/T1110/
false_positives:
- Automated load-testing suites
- Legitimate shared NAT addresses
tags: [attack.credential_access, attack.t1110.001]
```
## 内置规则库
| ID | 标题 | 级别 | MITRE 技巧 |
|---------------|--------------------------------------------|----------|-----------------|
| AUTHDET-001 | 暴力破解身份验证尝试 | HIGH | T1110.001 |
| AUTHDET-002 | 密码喷洒攻击 | HIGH | T1110.003 |
| AUTHDET-003 | 撞库攻击 — 高并发量 | CRITICAL | T1110.004 |
| AUTHDET-004 | 通过登录接口进行账户枚举 | MEDIUM | T1589.001 |
| AUTHDET-005 | 会话固定攻击 | HIGH | T1563 |
| AUTHDET-006 | 已知攻击工具的 User Agent | MEDIUM | T1595.002 |
| AUTHDET-007 | JWT 算法为 None — 签名绕过 | CRITICAL | T1550.001 |
| AUTHDET-008 | JWT 出现意外或弱的签名算法 | HIGH | T1550.001 |
| AUTHDET-009 | 身份验证 token 在 URL 中传输 | MEDIUM | T1552.001 |
| AUTHDET-010 | API 密钥暴力破解 — 频繁出现 403 | HIGH | T1110.001 |
| AUTHDET-011 | 不带 State 参数的 OAuth 流程 | MEDIUM | T1550 |
| AUTHDET-012 | 分布式身份验证失败突发 | CRITICAL | T1110 |
所有规则均包含 CWE 编号、OWASP 分类参考、误报指导以及 MITRE ATT&CK 战术/技巧标签。
## 支持的日志格式
| 格式 | 解析器类 | 自动检测依据 |
|----------------------|---------------------|-----------------------------|
| JSON / NDJSON | `JSONParser` | 以 `{` 开头的行 |
| Combined Log Format | `CombinedLogParser` | 匹配 CLF regex |
| Linux auth.log | `AuthLogParser` | 匹配 syslog 时间戳 |
**JSON 字段别名** — JSON 解析器会自动解析常见的字段名变体:
| 规范字段 | 也可识别为 |
|----------------|--------------------|
| `src_ip` | `remote_addr`, `client_ip`, `ip`, `source_ip` |
| `user` | `username`, `user_id`, `account` |
| `status_code` | `status`, `response_code`, `http_status` |
| `user_agent` | `ua`, `http_user_agent` |
**JWT 提取** — 如果 JSON 日志行包含 `Authorization: Bearer ` 标头,解析器会尝试对 JWT 标头和 payload 进行 base64 解码,并自动填充 `token_alg` 和 `token_jti` 字段。
## 测试
```
pip install pytest
pytest -q
```
```
30 passed in 0.17s
```
测试覆盖率包括:
- JSON、CLF 和 `auth.log` 解析器(字段映射、别名、JWT 提取、格式错误的输入)
- 规则加载器:有效规则、缺失必填字段、错误的 level 值、聚合条件解析
- 引擎:简单匹配 / 不匹配、聚合阈值、按字段分组、所有字段修饰符(`contains`、`startswith`、`endswith`、`re`、列表 OR)、`and not` 布尔逻辑
- 内置规则:AUTHDET-007 (JWT alg:none) 在 `token_alg=none` 时触发,在 `HS256` 时不触发
- 告警富化:MITRE 字段正确传播
## 项目结构
```
authdetect/
├── authdetect/
│ ├── model.py # LogEvent, RuleSpec, Alert dataclasses
│ ├── rule_loader.py # YAML → RuleSpec with full validation
│ ├── parsers.py # JSON / CLF / auth.log parsers
│ ├── engine.py # simple + aggregation detection engine
│ ├── report.py # rich terminal table + NDJSON renderer
│ └── cli.py # analyze / watch / validate / generate-logs
├── rules/
│ ├── auth/ # brute force, spray, enumeration, session, UA
│ ├── jwt/ # alg:none, unexpected algorithm
│ ├── token/ # token-in-URL, API key brute force
│ └── oauth/ # missing state parameter
├── tests/
│ └── test_authdetect.py
├── requirements.txt
├── pyproject.toml
└── README.md
```
## 展示的概念
对于将其作为作品集进行审查的人而言:
- **Sigma 规则格式** — 供应商中立检测逻辑的社区标准,被各大主要安全厂商的 SOC 团队所使用
- **MITRE ATT&CK 框架** — 为每个告警映射战术/技巧;防御者如何将攻击者行为转化为可观察的模式
- **滑动窗口聚合** — 大多数基于速率的检测(暴力破解、撞库)的统计主干;使用按组划分的 deque 状态从零开始实现
- **布尔条件解析** — 用于对命名选择器进行 `and / or / not` 逻辑运算的递归下降解析器;与 Sigma 的条件编译器概念相同
- **日志规范化** — 将异构日志格式映射到统一的事件模型,从而使检测逻辑与格式无关
- **JWT 内部机制** — base64url 解码、标头/payload 结构、`alg` 声明以及为什么 `none` 是一项严重的安全配置错误
- **检测工程工作流** — 编写规则、针对已标记样本进行测试、衡量误报风险、编写修复文档
- 简洁的 Python 架构:dataclasses、抽象基类、`pathlib`、完整的类型注解
## 扩展 authdetect
**添加新规则** — 在 `rules/` 下的任意位置创建一个 `.yml` 文件,并运行 `authdetect validate rules/` 进行检查。引擎在下一次运行时会自动加载它。
**添加新的日志格式** — 继承 `parsers.py` 中的 `BaseParser`,实现 `parse_line(line: str) -> LogEvent | None`,并在 `auto_detect()` 中添加一个检测分支。
**将告警发送至 SIEM** — 通过管道传输 JSON 输出:
```
python -m authdetect analyze --logfile auth.ndjson --format json \
| curl -X POST https://your-siem/ingest -d @-
```
**在 cron / CI pipeline 中运行** — 当有告警触发时退出代码为 `1`,无异常时为 `0`;可结合 `--min-severity high` 根据严重程度进行卡点拦截。
## 客观存在的局限性
- **运行间无状态持久化** — 聚合状态仅存在于内存中。重启进程会重置所有滑动窗口。若在生产环境中使用,请使用 Redis 或时间序列数据库作为状态支撑。
- **单线程、基于文件** — `watch` 模式只能追踪单个文件。生产环境中的等价方案通常会从 Kafka、Kinesis 或日志转发器中消费数据。
- **无机器学习** — 所有规则均为确定性规则。异常检测(基线偏差、用户行为分析)需要单独的模型层。
- **规则调整需手动进行** — 误报率取决于具体环境。每条规则都附带了 `false_positives` 指导,但需要根据您自身的流量对阈值进行调整。
## 路线图
- [ ] 基于 Redis 的窗口状态,实现跨重启的持久化
- [ ] 将编译后的 Sigma 导出为 Elastic / Splunk / Chronicle 查询语句
- [ ] Webhook / Slack 告警投递适配器
- [ ] `sigma import` 命令,用于从 SigmaHQ 社区规则库拉取规则
- [ ] 用于 Grafana 面板的 Prometheus metrics endpoint (`/metrics`)
- [ ] 更多规则类别:数据 exfiltration、权限提升、横向移动
## 道德与范围
专为防御用途构建:安全运营、检测工程、事件响应和安全教育。`authdetect` 仅负责读取日志文件并报告发现结果。它不会生成流量、探测 endpoint,也不会协助任何攻击性行动。
仅分析您已被授权处理的日志数据。
## 许可协议
[MIT](LICENSE)
标签:Cloudflare, MITRE ATT&CK, Modbus, Python, URL发现, 云计算, 安全检测, 恶意代码分类, 无后门, 规则引擎, 逆向工具