marez8505/SigmaShield

GitHub: marez8505/SigmaShield

一个纯 Python 实现的 Sigma 检测规则引擎,能够将 YAML 格式的检测规则转换为 Splunk、Elasticsearch、Sentinel 和 grep 等多种 SIEM 查询语言,并提供规则验证、ATT&CK 覆盖率分析和日志样本测试功能。

Stars: 0 | Forks: 0

# SigmaShield **一个面向检测工程师的 Sigma 检测规则引擎和多 SIEM 查询转换器。** ``` ____ _ ____ _ _ _ _ / ___|(_) __ _ _ __ ___ __ _/ ___|| |__ (_) ___| | __| | \___ \| |/ _` | '_ ` _ \ / _` \___ \| '_ \| |/ _ \ |/ _` | ___) | | (_| | | | | | | (_| |___) | | | | | __/ | (_| | |____/|_|\__, |_| |_| |_|\__,_|____/|_| |_|_|\___|_|\__,_| |___/ Sigma Detection Rule Engine & Multi-SIEM Converter ``` [![Python](https://img.shields.io/badge/python-3.8%2B-blue.svg)](https://python.org) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE) [![Tests](https://img.shields.io/badge/tests-116%20passing-green.svg)](#testing) **作者:** Edward Marez **许可证:** MIT **版本:** 1.0.0 ## 什么是 Sigma? **Sigma 对于日志检测的意义,就如同 Snort/Suricata 规则对于网络流量,以及 YARA 对于恶意软件文件的意义。** 它是一种用于 SIEM 系统的通用开放签名格式,允许您编写一次检测规则即可随处部署。 如果没有 Sigma,检测工程师需要编写: - 针对 Splunk SPL 的一条规则 - 针对 Elasticsearch Lucene 的一条规则 - 针对 Microsoft Sentinel KQL 的一条规则 - 用于事件响应日志搜索的 Shell 命令 这些全都是为了应对同一种威胁。借助 Sigma,您只需用 YAML 编写一次检测逻辑,即可自动将其转换为适用于任何 SIEM 的查询。 **SigmaShield** 使用纯 Python 实现了一个完整的 Sigma 规则处理引擎——包括解析器、转换器、验证器和覆盖率报告器——以及涵盖最常见攻击技术的 40 个内置检测规则。 ## 为什么检测工程如此重要 检测工程是安全运营中心 (SOC) 招聘中排名第一的技能缺口。根据行业调查显示: - **75%** 的 SOC 团队难以编写出有效的检测规则 - 平均而言,SOC 对 MITRE ATT&CK 技术的覆盖率不足 **30%** - 在检测覆盖率较差的环境中,攻击者平均潜伏 **200 多天** 而不被发现 - 检测工程师的收入可达 **12 万至 18 万美元**——这是目前最紧缺的安全职位之一 掌握 Sigma、MITRE ATT&CK 和 SIEM 查询语言,将使您成为任何安全团队的力量倍增器。 ## 功能特性 - **完整的 Sigma 解析器** — 处理所有检测语法,包括修饰符(`|contains`、`|startswith`、`|endswith`、`|re`、`|all`、`|base64`)、条件表达式(`1 of selection*`、`all of them`)和聚合管道 - **4 种 SIEM 后端** — Splunk SPL、Elasticsearch Lucene、Microsoft Sentinel KQL 以及 grep/regex - **40 多个内置检测规则** — 包含 Windows (15)、Linux (10)、Network (8)、Web (7) 以及 MITRE ATT&CK 映射 - **字段映射管道** — Windows Event Log、Sysmon 和 Linux 字段名称转换 - **规则验证器** — 检查必填字段、UUID 格式、ATT&CK 标签语法和最佳实践 - **覆盖率报告器** — 生成 MITRE ATT&CK 矩阵覆盖率分析 - **规则测试器** — 针对 JSON 日志样本应用规则,以验证检测是否有效 - **完整的 CLI** — 包含转换、验证、覆盖率、测试、列表、演示等命令 - **116 个单元测试** — 涵盖所有模块的全面测试 ## 安装 ``` git clone https://github.com/edwardmarez/sigmashield cd sigmashield pip install -r requirements.txt pip install -e . ``` **需求:** Python 3.8+, PyYAML, Jinja2, colorama, tabulate ## 快速开始 ``` # 查看所有功能的完整演示 python -m sigmashield demo # 列出所有 40 条内置规则 python -m sigmashield list --rules-dir sigmashield/rules/ # 将规则转换为全部 4 个 backends python -m sigmashield convert --rule sigmashield/rules/windows/brute_force_login.yml --backend splunk python -m sigmashield convert --rule sigmashield/rules/windows/brute_force_login.yml --backend elastic python -m sigmashield convert --rule sigmashield/rules/windows/brute_force_login.yml --backend sentinel python -m sigmashield convert --rule sigmashield/rules/windows/brute_force_login.yml --backend grep # 转换整个规则库并保存到文件 python -m sigmashield convert --rules-dir sigmashield/rules/ --backend splunk --output ./converted/ # 验证所有规则 python -m sigmashield validate --rules-dir sigmashield/rules/ --verbose # 生成 ATT&CK 覆盖率报告 python -m sigmashield coverage --rules-dir sigmashield/rules/ --output coverage.txt # 使用示例日志测试规则 python -m sigmashield test \ --rule sigmashield/rules/windows/powershell_encoded.yml \ --logs sample_logs/windows_events.json ``` ## 多 SIEM 转换示例 同一条 Sigma 规则可以生成针对每个平台优化的查询。以下是转换为全部 4 种后端的 **Windows 暴力破解登录** 规则示例: **Sigma 规则 (`brute_force_login.yml`):** ``` title: Windows Brute Force Login Attempts detection: selection: EventID: 4625 LogonType: - 3 - 10 condition: selection | count() by IpAddress > 10 ``` ### Splunk SPL ``` index=windows sourcetype="WinEventLog:Security" EventCode=4625 (LogonType=3 OR LogonType=10) | stats count by IpAddress | where count > 10 ``` ### Elasticsearch Lucene ``` // Index: winlogbeat-* winlog.channel:"Security" AND event.code:4625 AND (winlog.event_data.LogonType:3 OR winlog.event_data.LogonType:10) // Aggregation: count() by IpAddress > 10 ``` ### Microsoft Sentinel KQL ``` SecurityEvent | where EventID == 4625 and LogonType in~ ("3", "10") | summarize count() by IpAddress | where count_ > 10 ``` ### Grep(事件响应) ``` grep -i -P '(?=.*EventID.*4625)(?=.*LogonType.*(3|10))' /var/log/windows/Security.evtx.log ``` ## 架构 ``` SigmaShield/ ├── sigmashield/ │ ├── parser.py # Sigma YAML → SigmaRule objects │ │ # Handles all modifiers and condition expressions │ ├── backends/ │ │ ├── base.py # Abstract BaseBackend with condition tree resolver │ │ ├── splunk.py # SPL with index/sourcetype context + stats │ │ ├── elastic.py # Lucene with ECS field mapping + index comments │ │ ├── sentinel.py # KQL with table routing + summarize │ │ └── grep.py # grep -E / grep -P with lookaheads for AND logic │ ├── pipelines/ │ │ ├── pipeline.py # FieldMappingPipeline base class (chainable) │ │ ├── windows.py # Windows Event Log field name mappings │ │ ├── sysmon.py # Sysmon event field mappings │ │ └── linux.py # Linux syslog/auditd field mappings │ ├── validator.py # Rule correctness + best practice checks │ ├── coverage.py # MITRE ATT&CK matrix coverage analysis │ ├── testing.py # Rule → JSON event matching engine │ └── main.py # CLI (argparse) ├── sigmashield/rules/ # 40 production-quality detection rules │ ├── windows/ # 15 rules │ ├── linux/ # 10 rules │ ├── network/ # 8 rules │ └── web/ # 7 rules ├── sample_logs/ # JSON event samples for rule testing └── tests/ # 116 unit tests ``` ## 检测规则 ### Windows(15 条规则) | 规则 | 级别 | ATT&CK | |------|-------|--------| | 暴力破解登录尝试 | HIGH | T1110, T1110.001 | | PowerShell 编码命令执行 | HIGH | T1059, T1059.001 | | 可疑服务安装 | HIGH | T1543.003 | | LSASS 内存转储 | CRITICAL | T1003, T1003.001 | | Mimikatz sekurlsa 命令 | CRITICAL | T1003, T1003.001 | | 注册表 Run 键修改 | MEDIUM | T1547, T1547.001 | | 计划任务创建 | MEDIUM | T1053, T1053.005 | | PsExec 横向移动 | HIGH | T1021, T1021.002 | | 哈希传递攻击 | HIGH | T1550 | | WMI 命令执行 | MEDIUM | T1047 | | DLL 侧加载 | MEDIUM | T1574 | | 利用 eventvwr 绕过 UAC | HIGH | T1548, T1548.002 | | 卷影副本删除 | CRITICAL | T1490 | | RDP 横向移动 | LOW | T1021, T1021.001 | | PowerShell 下载诱饵 | HIGH | T1059.001, T1105 | ### Linux(10 条规则) | 规则 | 级别 | ATT&CK | |------|-------|--------| | Cron 任务持久化 | MEDIUM | T1053 | | Sudo 提权 | MEDIUM | T1548 | | SSH 暴力破解 | MEDIUM | T1110, T1110.001 | | 反弹 Shell | CRITICAL | T1059, T1059.004 | | /etc/passwd 或 /etc/shadow 访问 | HIGH | T1003 | | 内核模块加载 (Rootkit) | HIGH | T1547 | | 使用 curl 进行数据窃取 | MEDIUM | T1048 | | SUID 二进制文件滥用 | MEDIUM | T1548.001 | | Docker 容器逃逸 | HIGH | T1611 | | 日志文件清除 | HIGH | T1070, T1070.002 | ### Network(8 条规则) | 规则 | 级别 | ATT&CK | |------|-------|--------| | 端口扫描检测 | MEDIUM | T1046 | | DNS 隧道 | MEDIUM | T1071, T1071.004 | | C2 信标模式 | MEDIUM | T1071, T1071.001 | | Tor 出口节点连接 | MEDIUM | T1090 | | SMB 横向移动 | MEDIUM | T1021, T1021.002 | | Nmap 扫描检测 | MEDIUM | T1046 | | ICMP 数据窃取 | MEDIUM | T1048 | | 密码喷洒攻击 | HIGH | T1110, T1110.003 | ### Web(7 条规则) | 规则 | 级别 | ATT&CK | |------|-------|--------| | SQL 注入 | HIGH | T1190 | | 反射型 XSS | MEDIUM | T1189 | | 路径遍历 | HIGH | T1083 | | Web Shell 访问 | CRITICAL | T1505, T1505.003 | | Log4Shell (CVE-2021-44228) | CRITICAL | T1190 | | 命令注入 | HIGH | T1190 | | Spring4Shell (CVE-2022-22965) | CRITICAL | T1190 | ## Sigma 检测语法参考 SigmaShield 实现了完整的 Sigma 规范。以下是关键模式: ### 基本字段匹配 ``` detection: selection: EventID: 4625 # Exact match LogonType: - 3 # OR logic for lists - 10 condition: selection ``` ### 修饰符 ``` detection: selection: CommandLine|contains: '-enc' # *-enc* CommandLine|startswith: 'powershell' # powershell* CommandLine|endswith: '.ps1' # *.ps1 CommandLine|re: '(?i)invoke-.*' # Regex CommandLine|contains|all: # AND logic (all must match) - 'powershell' - '-bypass' - '-enc' Hash|base64: 'MaliciousString' # Base64 encoded ``` ### 条件表达式 ``` # 单选 condition: selection # 排除误报 condition: selection and not filter # Pattern matching (wildcard) condition: 1 of selection* condition: all of filter* # 所有选择必须匹配 condition: all of them # 布尔表达式 condition: (selection_a or selection_b) and not filter ``` ### 聚合 ``` # 按字段的 Count threshold condition: selection | count() by src_ip > 10 # Min/max/avg/sum condition: selection | min(duration) by src_ip < 1000 ``` ## 字段映射管道 不同 SIEM 平台之间的字段名称各不相同。管道负责将 Sigma 的通用名称进行转换: ``` from sigmashield.backends import get_backend from sigmashield.pipelines import get_pipeline from sigmashield.parser import SigmaParser # Parse rule parser = SigmaParser() rule = parser.parse_file("rule.yml") # 应用 Windows pipeline + 转换为 Splunk pipeline = get_pipeline("windows") backend = get_backend("splunk", pipeline=pipeline) query = backend.convert_rule(rule) ``` **可用的管道:** `windows`, `sysmon`, `linux` **Windows 管道示例映射:** | Sigma 字段 | Windows Event Log | |-------------|-------------------| | `EventID` | `EventCode` | | `Image` | `NewProcessName` | | `ParentImage` | `ParentProcessName` | | `TargetUsername` | `TargetUserName` | | `SubjectUsername` | `SubjectUserName` | ## Python API ``` from sigmashield import SigmaParser, SigmaValidator, CoverageReporter from sigmashield.backends import get_backend from sigmashield.testing import RuleTester # Parse a rule parser = SigmaParser() rule = parser.parse_file("sigmashield/rules/windows/brute_force_login.yml") print(f"Title: {rule.title}") print(f"ATT&CK: {', '.join(rule.mitre_attack_techniques)}") # 转换为 Splunk backend = get_backend("splunk") query = backend.convert_rule(rule) print(query) # Validate rules validator = SigmaValidator() result = validator.validate_rule(rule) if not result.is_valid: for finding in result.errors: print(f"ERROR: {finding.message}") # 生成 ATT&CK 覆盖率报告 reporter = CoverageReporter() report = reporter.analyze_directory("sigmashield/rules/") print(f"Coverage: {report.coverage_percentage:.1f}%") print(report.format_text()) # 使用日志事件测试规则 tester = RuleTester() result = tester.test_rule_against_file(rule, "sample_logs/windows_events.json") print(f"Matches: {result.match_count} of {result.total_events} events") for match in result.matches: if match.matched: print(f" Matched event: {match.event.get('description', '')}") ``` ## CLI 参考 ``` python -m sigmashield [options] ``` ### `convert` — 将规则转换为 SIEM 查询 ``` # 单条规则 python -m sigmashield convert \ --rule sigmashield/rules/windows/brute_force_login.yml \ --backend splunk # 所有规则,保存到文件 python -m sigmashield convert \ --rules-dir sigmashield/rules/ \ --backend sentinel \ --output ./converted/ # 使用 field mapping pipeline python -m sigmashield convert \ --rules-dir sigmashield/rules/windows/ \ --backend splunk \ --pipeline windows # 可用 backends: splunk, elastic, sentinel, grep ``` ### `validate` — 验证规则质量 ``` # Validate single rule python -m sigmashield validate --rule rule.yml # Validate 整个库 python -m sigmashield validate --rules-dir sigmashield/rules/ --verbose ``` ### `coverage` — ATT&CK 覆盖率报告 ``` # 打印报告 python -m sigmashield coverage --rules-dir sigmashield/rules/ # 保存到文件 python -m sigmashield coverage --rules-dir sigmashield/rules/ --output coverage.txt # 用于 dashboards 的 JSON 导出 python -m sigmashield coverage --rules-dir sigmashield/rules/ --json coverage.json ``` ### `test` — 针对日志样本测试规则 ``` # Test single rule python -m sigmashield test \ --rule sigmashield/rules/windows/brute_force_login.yml \ --logs sample_logs/windows_events.json # 测试所有规则 python -m sigmashield test \ --rules-dir sigmashield/rules/ \ --logs sample_logs/windows_events.json \ --show-all ``` ### `list` — 列出可用规则 ``` # 简单列表 python -m sigmashield list --rules-dir sigmashield/rules/ # 表格格式(需要 tabulate) python -m sigmashield list --rules-dir sigmashield/rules/ --format table # JSON 导出 python -m sigmashield list --rules-dir sigmashield/rules/ --format json # 按 level 过滤 python -m sigmashield list --rules-dir sigmashield/rules/ --level critical # 按 product 过滤 python -m sigmashield list --rules-dir sigmashield/rules/ --product windows # 按 ATT&CK technique 过滤 python -m sigmashield list --rules-dir sigmashield/rules/ --technique T1059 ``` ### `demo` — 完整功能演示 ``` python -m sigmashield demo ``` ## 与真实 SIEM 集成 ### Splunk 1. 将转换后的查询保存到 `.spl` 文件中 2. 在 Splunk 中:**Search & Reporting → Alerts → Create Alert** 3. 粘贴 SPL 查询,设置触发条件,配置通知 4. 用于持续检测:使用 **Splunk Enterprise Security Correlation Searches** ### Elasticsearch / Kibana 1. 使用 `--backend elastic` 转换规则 2. 在 Kibana 中:**Security → Rules → Create Detection Rule → Custom Query** 3. 粘贴 Lucene 查询 4. 启用 ECS (Elastic Common Schema) 以确保字段映射正常工作 ### Microsoft Sentinel 1. 使用 `--backend sentinel` 转换规则 2. 在 Sentinel 中:**Analytics → Create → Scheduled query rule** 3. 粘贴 KQL 查询并设置计划 4. 如果需要,将字段映射到您的数据连接器 ### 事件响应 (grep) 适用于在拥有直接服务器访问权限的事件发生期间进行快速日志搜索: ``` # 转换并立即运行 python -m sigmashield convert \ --rule sigmashield/rules/linux/reverse_shell.yml \ --backend grep # 输出: grep -i -P '(bash.*>.*\/dev\/tcp|0>&1)' /var/log/syslog ``` ## 编写自定义 Sigma 规则 ``` title: My Custom Detection Rule id: status: experimental description: | Describe what this rule detects, why it matters, and what attacker technique it covers. author: Your Name date: 2024-01-15 references: - https://attack.mitre.org/techniques/T1234/ tags: - attack.persistence - attack.t1234 logsource: category: process_creation # OR product/service product: windows detection: selection: Image|endswith: '\malicious.exe' CommandLine|contains: - '-evil' - '--bad' filter_legit: CommandLine|contains: 'legitimate_vendor' condition: selection and not filter_legit fields: - CommandLine - Image - ParentImage falsepositives: - List known false positive scenarios here level: high # informational, low, medium, high, critical ``` 在部署前验证您的规则: ``` python -m sigmashield validate --rule my_rule.yml --verbose ``` ## MITRE ATT&CK 覆盖范围 SigmaShield 的 40 个内置规则涵盖了跨 10 个战术的 **39 种 ATT&CK 技术**: | 战术 | 覆盖范围 | |--------|----------| | Credential Access | T1003, T1110, T1550 | | Persistence | T1053, T1543, T1547, T1505 | | Execution | T1059, T1047, T1059.004 | | Lateral Movement | T1021, T1021.001, T1021.002 | | Privilege Escalation | T1548, T1548.002, T1611 | | Defense Evasion | T1070, T1574, T1090 | | Initial Access | T1190, T1189 | | Discovery | T1046, T1083 | | Command and Control | T1071, T1071.004 | | Exfiltration | T1048 | 生成您当前的覆盖率: ``` python -m sigmashield coverage --rules-dir sigmashield/rules/ ``` ## 测试 ``` # 运行所有测试 python -m pytest tests/ -v # 运行特定测试模块 python -m pytest tests/test_parser.py -v python -m pytest tests/test_backends.py -v python -m pytest tests/test_validator.py -v python -m pytest tests/test_pipelines.py -v # 附带覆盖率 pip install pytest-cov python -m pytest tests/ --cov=sigmashield --cov-report=term-missing ``` **测试覆盖率:** 4 个模块共 116 个测试: - `test_parser.py` — 35 个测试:YAML 解析、修饰符、聚合、条件解析 - `test_backends.py` — 34 个测试:所有 4 种后端,包括完整规则库转换 - `test_validator.py` — 25 个测试:有效规则、警告、错误、内置规则集 - `test_pipelines.py` — 22 个测试:所有 3 种管道、工厂模式、后端集成 ## 项目结构 ``` SigmaShield/ ├── sigmashield/ │ ├── __init__.py │ ├── __main__.py # python -m sigmashield entry point │ ├── main.py # CLI with argparse │ ├── parser.py # SigmaRule, SigmaParser, FieldCondition, etc. │ ├── validator.py # SigmaValidator, ValidationResult, ValidationFinding │ ├── coverage.py # CoverageReporter, CoverageReport │ ├── testing.py # RuleTester, RuleTestResult │ ├── utils.py # Escape helpers, wildcard conversions, utilities │ ├── backends/ │ │ ├── __init__.py # get_backend() factory │ │ ├── base.py # Abstract BaseBackend │ │ ├── splunk.py # Splunk SPL backend │ │ ├── elastic.py # Elasticsearch Lucene backend │ │ ├── sentinel.py # Microsoft Sentinel KQL backend │ │ └── grep.py # grep/egrep CLI backend │ ├── pipelines/ │ │ ├── __init__.py # get_pipeline() factory │ │ ├── pipeline.py # FieldMappingPipeline, PipelineRule │ │ ├── windows.py # Windows Event Log field mappings │ │ ├── sysmon.py # Sysmon field mappings │ │ └── linux.py # Linux syslog/auditd field mappings │ └── rules/ │ ├── windows/ # 15 Windows detection rules │ ├── linux/ # 10 Linux detection rules │ ├── network/ # 8 network detection rules │ └── web/ # 7 web application detection rules ├── sample_logs/ │ ├── windows_events.json # Windows event samples │ ├── linux_events.json # Linux syslog/auth samples │ └── README.md ├── tests/ │ ├── test_parser.py │ ├── test_backends.py │ ├── test_validator.py │ └── test_pipelines.py ├── requirements.txt ├── setup.py ├── LICENSE └── README.md ``` ## 资源 - [Sigma 项目](https://github.com/SigmaHQ/sigma) — 官方 Sigma 规范和社区规则 - [Sigma 规范](https://github.com/SigmaHQ/sigma-specification) — 完整语法参考 - [MITRE ATT&CK 框架](https://attack.mitre.org/) — 对手战术和技术 - [MITRE ATT&CK Navigator](https://mitre-attack.github.io/attack-navigator/) — 覆盖范围可视化 - [Detection Engineering 周刊](https://www.detectionengineering.net/) — 行业新闻通讯 - [Sigma HQ 规则](https://github.com/SigmaHQ/sigma/tree/master/rules) — 3000 多条社区规则 - [Elastic 安全规则](https://github.com/elastic/detection-rules) — Elastic 的检测库 - [Splunk 安全基础](https://splunkbase.splunk.com/app/3435) — Splunk 的检测内容 ## 许可证 MIT License — 版权所有 (c) 2024 Edward Marez。详情请参见 [LICENSE](LICENSE)。 ## 贡献 1. Fork 本代码仓库 2. 创建一个功能分支:`git checkout -b feature/new-detection-rule` 3. 将您的 Sigma 规则添加到相应的 `rules/` 子目录中 4. 验证:`python -m sigmashield validate --rule rules/your_rule.yml` 5. 运行测试:`python -m pytest tests/` 6. 提交 Pull Request *由 Edward Marez 构建 — 检测*
标签:AMSI绕过, Beacon Object File, CISA项目, Cloudflare, DNS 反向解析, EDR, Elasticsearch, Grep, IP 地址批量处理, KQL, Microsoft Sentinel, MITRE ATT&CK, Modbus, Mr. Robot, Python, Sigma规则, Splunk SPL, YAML, 云计算, 后渗透, 多平台转换, 威胁检测, 子域名变形, 安全信息和事件管理系统, 安全库, 安全运营中心, 恶意代码分类, 插件系统, 搜索语句(dork), 攻击模拟, 无后门, 无线安全, 日志检测, 模拟器, 目标导入, 端点检测与响应, 网络安全, 网络映射, 脆弱性评估, 脱壳工具, 规则引擎, 逆向工具, 隐私保护, 驱动签名利用