Communitygithub.com

使用 Sigma 建立偵測規則

使用 Sigma 規則格式建立供應商無關的偵測規則,可跨多種 SIEM 平台移植。

使用 Sigma 建立偵測規則 是什麼?

此技能引導安全工程師運用 Sigma 格式建立、驗證、轉換和部署供應商無關的偵測規則。使用者可將威脅情資或 MITRE ATT&CK 技術對應至 YAML 規則,再透過 pySigma 驗證語法並轉換為 Splunk SPL、Elasticsearch Lucene 或 Microsoft Sentinel KQL 等目標 SIEM 查詢語言。技能涵蓋完整工作流程:定義偵測邏輯、使用 sigma check 驗證規則、轉換多平台查詢、對應 ATT&CK 標籤以計算覆蓋率、測試樣本資料以減少誤報,最後將規則作為排程搜尋或關聯規則部署至正式環境。也涵蓋 Git 版本控制和 GitHub Actions CI/CD 整合,以自動化驗證與轉換。支援的平台包括 Splunk、Elastic Security、Microsoft Sentinel 和 30 多個其他 SIEM;使用 Python 3.8+、pySigma 和專用後端套件。關鍵概念包括 Sigma 作為供應商中立格式、pySigma 用於處理規則、後端負責轉譯查詢語言、管道定義欄位對應,以及將偵測規則納入版本控制的偵測即程式碼實務。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/mukul975/Anthropic-Cybersecurity-Skills/tree/main/skills/building-detection-rules-with-sigma

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

使用 Sigma 建立偵測規則 是做什麼的?

使用時機

使用此技能的時機:

  • SOC 工程師需要建立可跨多個 SIEM 平台移植的偵測規則
  • 威脅情資報告描述需要新增偵測覆蓋範圍的 TTP
  • 現有廠商特定規則需要標準化為可分享格式
  • 團隊在 CI/CD 管線中採用 Sigma 作為偵測即程式碼標準

請勿使用於即時串流偵測(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 憑證竊取 (T1003.001 — LSASS 記憶體):

title: Mimikatz 透過 LSASS 存取進行憑證傾印
id: 0d894093-71bc-43c3-8d63-bf520e73a7c5
status: stable
level: high
description: 偵測存取 lsass.exe 記憶體的處理程序,表示有類似 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:
    - 合法的安全工具存取 LSASS
    - Windows Defender 掃描
    - CrowdStrike Falcon 感應器

步驟 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")

轉換為 Elasticsearch 查詢 (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        # 戰術
    - attack.t1003.001                # 子技術
    - attack.t1003                    # 父技術

使用 ATT&CK Navigator 追蹤偵測覆蓋率:

import json

# 從 Sigma 規則產生 ATT&CK Navigator 圖層
layer = {
    "name": "SOC 偵測覆蓋率",
    "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 記憶體存取 - 憑證傾印"
description = "偵測對 LSASS 處理程序記憶體的可疑存取"
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 = "作業系統憑證傾印"

步驟 7:版本控制與 CI/CD 整合

將規則儲存在 Git 中並搭配自動化測試:

# .github/workflows/sigma-ci.yml
name: Sigma 規則 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)pySigma 插件,將 Sigma 偵測邏輯轉譯為目標平台查詢語言(SPL、KQL、Lucene)
管線 (Pipeline)欄位對應設定,將通用 Sigma 欄位名稱轉譯為 SIEM 特定欄位名稱
日誌來源 (Logsource)Sigma 規則區段,定義目標資料的類別 (process_creation、network_connection) 和產品 (windows、linux)
偵測即程式碼 (Detection-as-Code)在版本控制中管理偵測規則的實務,搭配 CI/CD 測試和自動化部署

工具與系統

  • SigmaHQ:官方 Sigma 規則儲存庫,GitHub 上有 3,000 多條社群維護的偵測規則
  • pySigma:基於 Python 的 Sigma 規則處理框架,支援模組化後端和管線
  • ATT&CK Navigator:MITRE 工具,用於視覺化對應至 ATT&CK 技術的偵測覆蓋率
  • Uncoder.IO:基於網頁的 Sigma 規則轉換器,支援 30 多個 SIEM 平台以進行快速轉譯

常見情境

  • 新 CVE 偵測:為漏洞利用指標撰寫 Sigma 規則(例如 Web 日誌中的 Log4Shell JNDI 查詢模式)
  • 狩獵規則升級:將 ad-hoc Splunk 狩獵查詢轉換為 Sigma 規則,以進行持續自動化偵測
  • 多 SIEM 遷移:將 500 多個 Splunk 關聯搜尋轉換為 Sigma,以遷移至 Elastic Security
  • 紫隊產出:將紅隊發現結果轉換為 Sigma 規則,立即提供防禦覆蓋
  • 威脅情資實戰化:將基於 IOC 的威脅報告轉換為行為 Sigma 規則

輸出格式

SIGMA 規則部署報告
━━━━━━━━━━━━━━━━━━━━━━━━━━━
規則 ID:      0d894093-71bc-43c3-8d63-bf520e73a7c5
標題:        Mimikatz 透過 LSASS 存取進行憑證傾印
ATT&CK:       T1003.001 - LSASS 記憶體
嚴重性:     高
狀態:       已部署至正式環境

轉換結果:
  Splunk SPL:    通過 — 已建立排程搜尋 "sigma_lsass_access"
  Elastic EQL:   通過 — 已啟用偵測規則 ID elastic-0d894093
  Sentinel KQL:  通過 — 已透過 ARM 範本部署分析規則

測試結果:
  真陽性:    4/4 個測試案例相符
  誤報:      7 天回溯測試中出現 2 次 (svchost 邊緣案例 — 已新增篩選器)
  效能:      在每天 5000 萬事件規模下平均執行 3.2 秒

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

abusing-dpapi-for-credential-access

Extract and decrypt Windows DPAPI-protected secrets (Credential Manager, browser logins/cookies, Wi-Fi credentials, KeePass keys) online or offline using SharpDPAPI, SharpChrome, Mimikatz, or Impacket

abusing-shadow-credentials-for-privesc

Take over Active Directory accounts by writing attacker-controlled public keys to msDS-KeyCredentialLink (Shadow Credentials) with pyWhisker, Whisker, or Certipy, then authenticate via PKINIT to recover the target

achieving-cmmc-level-2-compliance

>-

acquiring-disk-image-with-dd-and-dcfldd

Create forensically sound bit-for-bit disk images with dd or dcfldd on a Linux forensic workstation, preserving evidence integrity through hash verification (MD5/SHA) during acquisition. Use when imaging a suspect drive, USB device, or memory card for investigation, preserving volatile disk evidence during incident response, or producing a verified copy for legal or law-enforcement proceedings before any destructive analysis.

analyzing-active-directory-acl-abuse

Detect dangerous ACL misconfigurations in Active Directory using ldap3

analyzing-android-malware-with-apktool

Perform static analysis of Android APK malware using apktool for resource decompilation, jadx for Java source recovery, and androguard for manifest inspection, dangerous permission-combination detection, and identification of obfuscated code, dynamic code loading, and reflection-based API calls. Use to statically triage a suspicious APK without executing it or to build mobile malware detection rules.

analyzing-api-gateway-access-logs

Parses API Gateway access logs (AWS API Gateway, Kong, Nginx) to detect

analyzing-apt-group-with-mitre-navigator

Query ATT&CK data with attackcti, mitreattack-python, and stix2, then build MITRE ATT&CK Navigator layers and multi-layer heatmap overlays mapping one or more APT groups

analyzing-azure-activity-logs-for-threats

Queries Azure Monitor activity logs and sign-in logs via azure-monitor-query

analyzing-bootkit-and-rootkit-samples

Analyzes bootkit and advanced rootkit malware infecting the Master

analyzing-browser-forensics-with-hindsight

Parse Chromium-based browser databases with Hindsight to extract and correlate browsing history, downloads, cookies, cached content, autofill data, saved passwords, and extensions from Chrome, Edge, Brave, Opera, and Vivaldi into a unified timeline (XLSX, JSON, or SQLite output). Use during incident response, insider-threat investigations, or criminal cases when you need to reconstruct a user

analyzing-campaign-attribution-evidence

Systematically evaluate cyber-campaign evidence to attribute an operation to a threat actor, using the Diamond Model and Analysis of Competing Hypotheses (ACH) to weigh infrastructure overlaps, TTP consistency, malware code similarity, and timing/language artifacts into confidence-weighted attribution assessments. Use when an incident investigation needs a defensible attribution confidence level.

analyzing-certificate-transparency-for-phishing

Monitor Certificate Transparency logs using crt.sh and Certstream to

analyzing-cloud-storage-access-patterns

Detect abnormal access in AWS S3, GCS, and Azure Blob Storage by analyzing CloudTrail Data Events, GCS audit logs, and Azure Storage Analytics for after-hours bulk downloads, new-IP access, and API-call spikes (e.g. GetObject) via statistical baselines and time-series anomaly detection. Use when investigating suspected cloud data exfiltration or building related detection rules.

analyzing-cobalt-strike-beacon-configuration

Extract and analyze Cobalt Strike beacon configuration from PE files

analyzing-cobaltstrike-malleable-c2-profiles

Parse and analyze Cobalt Strike Malleable C2 profiles with dissect.cobaltstrike (profiles and beacon-payload configs) and pyMalleableC2 (AST parsing) to extract HTTP/DNS transforms, URIs, headers, sleep/jitter, and injection behavior, then generate network detection signatures. Use when reverse-engineering a captured malleable profile or building detections against Cobalt Strike Beacon traffic.

analyzing-command-and-control-communication

Analyzes malware C2 communication over HTTP, HTTPS, DNS, and custom

analyzing-cyber-kill-chain

Analyzes intrusion activity against the Lockheed Martin Cyber Kill Chain

analyzing-disk-image-with-autopsy

Perform comprehensive forensic analysis of raw (dd), E01, or AFF disk images with Autopsy and The Sleuth Kit, recovering deleted files, examining metadata and embedded artifacts, keyword searching, and building investigation timelines with visual reports. Use for structured analysis of a forensic disk image or when stakeholders need visual reports from evidence.

analyzing-dns-logs-for-exfiltration

Analyzes DNS query logs to detect data exfiltration via DNS tunneling,

相關技能