Building detection rules with sigma

From killvxk/cybersecurity-skills-zh · View interactive version

Building detection rules with sigma is an AI agent skill from the GitHub repository killvxk/cybersecurity-skills-zh. 使用 Sigma 规则格式构建与供应商无关的检测规则,用于跨 SIEM 平台(包括 Splunk、Elastic 和 Microsoft Sentinel)的威胁检测。适用于从威胁情报创建可移植检测逻辑、将规则映射到 MITRE ATT&CK 技术,或使用 sigmac 或 pySigma 后端将社区 Sigma 规则转换为平台特定查询。

How to use this skill

Skill file

使用 Sigma 构建检测规则(Building Detection Rules with Sigma)

适用场景

在以下情况使用本技能:

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

前置条件

工作流程

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

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

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 验证规则:

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

# 验证规则
sigma check rule.yml

或使用 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:

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])

输出:

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):

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:

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 标签:

tags:
    - attack.credential_access        # 战术(Tactic)
    - attack.t1003.001                # 子技术
    - attack.t1003                    # 父技术

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

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:针对样本数据测试规则

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

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

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

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

步骤 6:部署到生产 SIEM

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

Splunk ES 关联搜索:

| 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 格式):

[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 中,并配置自动化测试:

# .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 测试和自动化部署的实践 |

工具与系统

常见场景

输出格式

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 秒
Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.