# Building Detection Rules With Sigma

> 使用 Sigma 规则格式构建与供应商无关的检测规则，用于跨 SIEM 平台（包括 Splunk、Elastic 和 Microsoft Sentinel）的威胁检测。适用于从威胁情报创建可移植检测逻辑、将规则映射到 MITRE ATT&CK 技术，或使用 sigmac 或 pySigma 后端将社区 Sigma 规则转换为平台特定查询。

- Skill: `killvxk/building-detection-rules-with-sigma` (Agent Skill, multi-file: 4 files)
- Install (CLI): `npx skillmds@latest add killvxk/building-detection-rules-with-sigma`
- Raw SKILL.md: https://api.skillmd.com/api/skills/killvxk/building-detection-rules-with-sigma/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Coding & Dev Tools
- License: Apache-2.0
- Author: killvxk (https://skillmd.com/u/killvxk)
- Updated: 2026-09-17
- Page: https://skillmd.com/skills/killvxk/building-detection-rules-with-sigma

---

# 使用 Sigma 构建检测规则（Building Detection Rules with Sigma）

## 适用场景

在以下情况使用本技能：
- 安全运营中心（SOC）工程师需要创建可跨多个 SIEM 平台移植的检测规则
- 威胁情报（Threat Intelligence）报告描述了需要新增检测覆盖的 TTP
- 现有供应商特定规则需要标准化为可共享格式
- 团队在 CI/CD 流水线中采用 Sigma 作为检测即代码（Detection-as-Code）标准

**不适用于**实时流式检测（Sigma 适用于批量/计划搜索），或目标 SIEM 具有 Sigma 无法表达的原生检测功能（例如 Splunk RBA 风险评分）。

## 前置条件

- Python 3.8+ 及 `pySigma` 和相应后端（`pySigma-backend-splunk`、`pySigma-backend-elasticsearch`、`pySigma-backend-microsoft365defender`）
- 已克隆 Sigma 规则仓库：`git clone https://github.com/SigmaHQ/sigma.git`
- MITRE ATT&CK 框架知识（用于技术映射）
- 对目标 SIEM 日志源字段映射的理解

## 工作流程

### 步骤 1：从威胁情报定义检测逻辑

从威胁报告或 ATT&CK 技术入手。示例：检测 Mimikatz 凭据转储（Credential Dumping）（T1003.001 — LSASS 内存）：

```yaml
title: Mimikatz Credential Dumping via LSASS Access
id: 0d894093-71bc-43c3-8d63-bf520e73a7c5
status: stable
level: high
description: Detects process accessing lsass.exe memory, indicative of credential dumping tools like Mimikatz
references:
    - https://attack.mitre.org/techniques/T1003/001/
    - https://github.com/gentilkiwi/mimikatz
author: mahipal
date: 2024/03/15
modified: 2024/03/15
tags:
    - attack.credential_access
    - attack.t1003.001
logsource:
    category: process_access
    product: windows
detection:
    selection:
        TargetImage|endswith: '\lsass.exe'
        GrantedAccess|contains:
            - '0x1010'
            - '0x1038'
            - '0x1fffff'
            - '0x40'
    filter_main_svchost:
        SourceImage|endswith: '\svchost.exe'
    filter_main_csrss:
        SourceImage|endswith: '\csrss.exe'
    filter_main_wininit:
        SourceImage|endswith: '\wininit.exe'
    condition: selection and not 1 of filter_main_*
falsepositives:
    - Legitimate security tools accessing LSASS
    - Windows Defender scanning
    - CrowdStrike Falcon sensor
```

### 步骤 2：验证 Sigma 规则语法

使用 `sigma check` 验证规则：

```bash
# 安装 pySigma 和验证器
pip install pySigma pySigma-validators-sigmaHQ

# 验证规则
sigma check rule.yml
```

或使用 Python 验证：

```python
from sigma.rule import SigmaRule
from sigma.validators.core import SigmaValidator

rule = SigmaRule.from_yaml(open("rule.yml").read())
validator = SigmaValidator()
issues = validator.validate_rule(rule)
for issue in issues:
    print(f"{issue.severity}: {issue.message}")
```

### 步骤 3：转换为目标 SIEM 查询

**转换为 Splunk SPL：**

```python
from sigma.rule import SigmaRule
from sigma.backends.splunk import SplunkBackend
from sigma.pipelines.splunk import splunk_windows_pipeline

pipeline = splunk_windows_pipeline()
backend = SplunkBackend(pipeline)

rule = SigmaRule.from_yaml(open("rule.yml").read())
splunk_query = backend.convert_rule(rule)
print(splunk_query[0])
```

输出：
```spl
TargetImage="*\\lsass.exe" (GrantedAccess="*0x1010*" OR GrantedAccess="*0x1038*"
OR GrantedAccess="*0x1fffff*" OR GrantedAccess="*0x40*")
NOT (SourceImage="*\\svchost.exe") NOT (SourceImage="*\\csrss.exe")
NOT (SourceImage="*\\wininit.exe")
```

**转换为 Elastic 查询（Lucene）：**

```python
from sigma.backends.elasticsearch import LuceneBackend
from sigma.pipelines.elasticsearch import ecs_windows_pipeline

pipeline = ecs_windows_pipeline()
backend = LuceneBackend(pipeline)
elastic_query = backend.convert_rule(rule)
print(elastic_query[0])
```

**转换为 Microsoft Sentinel KQL：**

```python
from sigma.backends.microsoft365defender import Microsoft365DefenderBackend

backend = Microsoft365DefenderBackend()
kql_query = backend.convert_rule(rule)
print(kql_query[0])
```

### 步骤 4：映射到 MITRE ATT&CK 并添加覆盖元数据

在 `tags` 字段中为每条规则打上 ATT&CK 技术 ID 标签：

```yaml
tags:
    - attack.credential_access        # 战术（Tactic）
    - attack.t1003.001                # 子技术
    - attack.t1003                    # 父技术
```

使用 ATT&CK Navigator 跟踪检测覆盖率：

```python
import json

# 从 Sigma 规则生成 ATT&CK Navigator 层
layer = {
    "name": "SOC Detection Coverage",
    "versions": {"attack": "14", "navigator": "4.9", "layer": "4.5"},
    "domain": "enterprise-attack",
    "techniques": []
}

# 解析 Sigma 规则目录中的技术标签
import os
from sigma.rule import SigmaRule

for root, dirs, files in os.walk("sigma/rules/windows/"):
    for f in files:
        if f.endswith(".yml"):
            rule = SigmaRule.from_yaml(open(os.path.join(root, f)).read())
            for tag in rule.tags:
                if str(tag).startswith("attack.t"):
                    technique_id = str(tag).replace("attack.", "").upper()
                    layer["techniques"].append({
                        "techniqueID": technique_id,
                        "color": "#31a354",
                        "score": 1
                    })

with open("coverage_layer.json", "w") as f:
    json.dump(layer, f, indent=2)
```

### 步骤 5：针对样本数据测试规则

创建测试数据，验证规则能捕获预期事件：

```bash
# 使用 sigma 测试框架
sigma test rule.yml --target splunk --pipeline splunk_windows

# 或在 Splunk 中使用样本数据手动测试
# 上传含已知 Mimikatz 特征的 Sysmon process_access 日志
```

通过在非告警保存搜索中对 7 天生产数据运行来验证误报率。

### 步骤 6：部署到生产 SIEM

将转换后的查询部署为计划搜索或关联规则：

**Splunk ES 关联搜索：**
```spl
| tstats summariesonly=true count from datamodel=Endpoint.Processes
  where Processes.process_name="*\\lsass.exe"
  by Processes.src, Processes.user, Processes.process_name, Processes.parent_process_name
| `drop_dm_object_name(Processes)`
| where count > 0
```

**Elastic Security 规则（TOML 格式）：**
```toml
[rule]
name = "LSASS Memory Access - Credential Dumping"
description = "Detects suspicious access to LSASS process memory"
risk_score = 73
severity = "high"
type = "eql"
query = '''
process where event.action == "access" and
  process.name == "lsass.exe" and
  not process.executable : ("*\\svchost.exe", "*\\csrss.exe")
'''

[rule.threat]
framework = "MITRE ATT&CK"
[[rule.threat.technique]]
id = "T1003"
name = "OS Credential Dumping"
```

### 步骤 7：版本控制与 CI/CD 集成

将规则存储在 Git 中，并配置自动化测试：

```yaml
# .github/workflows/sigma-ci.yml
name: Sigma Rule CI
on: [push, pull_request]
jobs:
  validate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: '3.11'
      - run: pip install pySigma pySigma-validators-sigmaHQ
      - run: sigma check rules/
      - run: sigma convert -t splunk -p splunk_windows rules/ > /dev/null
```

## 核心概念

| 术语 | 定义 |
|------|-----------|
| **Sigma** | 与供应商无关的检测规则格式（基于 YAML），通过后端编译为 SIEM 特定查询 |
| **pySigma** | 替代旧版 sigmac 的 Python 库，用于规则转换、验证和管道处理 |
| **后端（Backend）** | 将 Sigma 检测逻辑转换为目标平台查询语言（SPL、KQL、Lucene）的 pySigma 插件 |
| **管道（Pipeline）** | 将通用 Sigma 字段名转换为 SIEM 特定字段名的字段映射配置 |
| **日志源（Logsource）** | Sigma 规则中定义目标数据类别（process_creation、network_connection）和产品（windows、linux）的部分 |
| **检测即代码（Detection-as-Code）** | 在版本控制系统中管理检测规则，配合 CI/CD 测试和自动化部署的实践 |

## 工具与系统

- **SigmaHQ**：GitHub 上官方 Sigma 规则仓库，包含 3000+ 条社区维护的检测规则
- **pySigma**：基于 Python 的 Sigma 规则处理框架，具有模块化后端和管道
- **ATT&CK Navigator**：MITRE 工具，用于可视化映射到 ATT&CK 技术的检测覆盖率
- **Uncoder.IO**：基于 Web 的 Sigma 规则转换器，支持 30+ 个 SIEM 平台的快速翻译

## 常见场景

- **新 CVE 检测**：为利用指标编写 Sigma 规则（例如 Web 日志中的 Log4Shell JNDI 查找模式）
- **狩猎规则晋级**：将临时 Splunk 狩猎查询转换为 Sigma 规则，用于持续自动检测
- **多 SIEM 迁移**：将 500+ 条 Splunk 关联搜索转换为 Sigma，用于迁移到 Elastic Security
- **紫队输出（Purple Team Output）**：将红队（Red Team）发现转换为 Sigma 规则，立即提供防御覆盖
- **威胁情报落地**：将基于失陷指标（IOC）的威胁报告转换为行为型 Sigma 规则

## 输出格式

```
SIGMA 规则部署报告（SIGMA RULE DEPLOYMENT REPORT）
━━━━━━━━━━━━━━━━━━━━━━━━━━━
规则 ID:      0d894093-71bc-43c3-8d63-bf520e73a7c5
标题:         Mimikatz Credential Dumping via LSASS Access
ATT&CK:       T1003.001 - LSASS Memory
严重性:       高
状态:         已部署到生产

转换结果:
  Splunk SPL:    通过 — 已创建保存的搜索 "sigma_lsass_access"
  Elastic EQL:   通过 — 已启用检测规则 ID elastic-0d894093
  Sentinel KQL:  通过 — 已通过 ARM 模板部署分析规则

测试结果:
  真阳性:    4/4 测试用例匹配
  误报:      7 天回测中发现 2 个（svchost 边缘情况 — 已添加过滤）
  性能:      每天 5000 万事件平均执行时间 3.2 秒
```

