Communitygithub.com

Sigma를 사용한 탐지 규칙 구축

Sigma 규칙 형식을 사용하여 공급업체에 종속되지 않는 탐지 규칙을 구축합니다.

Sigma를 사용한 탐지 규칙 구축란 무엇인가요?

이 스킬은 SOC 엔지니어, 위협 인텔리전스 분석가, 보안 팀이 Sigma 규칙 형식을 사용하여 공급업체에 독립적인 탐지 규칙을 생성, 검증, 변환 및 배포하는 방법을 안내합니다. Sigma는 YAML 기반의 공개 규칙 형식으로, pySigma 라이브러리를 통해 Splunk SPL, Elasticsearch Lucene/KQL, Microsoft Sentinel KQL 등 다양한 SIEM 플랫폼의 쿼리 언어로 자동 변환됩니다. 이 스킬은 MITRE ATT&CK 매핑, 가양성 필터링, CI/CD 파이프라인 통합, 탐지 커버리지 시각화(ATT&CK Navigator) 등 전체 워크플로우를 다룹니다. Windows, Linux, 네트워크 로그 등 다양한 로그 소스를 지원하며, python 기반 도구인 pySigma와 SigmaHQ 커뮤니티 저장소를 활용하여 3,000개 이상의 기존 규칙을 기반으로 작업할 수 있습니다. 또한, 다중 SIEM 환경으로의 마이그레이션, 새로운 CVE 탐지, 사냥 규칙의 자동화 등 실무 시나리오에서 즉시 적용 가능한 방법을 제공합니다.

지원 대상~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/mukul975/Anthropic-Cybersecurity-Skills/tree/main/skills/building-detection-rules-with-sigma

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

Sigma를 사용한 탐지 규칙 구축은(는) 무엇을 하나요?

사용 시기

이 스킬은 다음과 같은 경우에 사용합니다:

  • SOC 엔지니어가 여러 SIEM 플랫폼에서 이식 가능한 탐지 규칙을 만들어야 할 때
  • 위협 인텔리전스 보고서가 새로운 탐지 적용 범위가 필요한 TTP를 설명할 때
  • 기존 공급업체별 규칙을 공유 가능한 형식으로 표준화해야 할 때
  • 팀이 CI/CD 파이프라인에서 Detection-as-Code 표준으로 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 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        # 전술
    - 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)대상 데이터의 범주(process_creation, network_connection)와 제품(windows, linux)을 정의하는 Sigma 규칙 섹션입니다.
Detection-as-CodeCI/CD 테스트 및 자동 배포를 통해 탐지 규칙을 버전 관리 시스템에서 관리하는 방식입니다.

도구 및 시스템

  • SigmaHQ: GitHub의 공식 Sigma 규칙 저장소로, 커뮤니티에서 유지 관리하는 3,000개 이상의 탐지 규칙 보유
  • pySigma: 모듈식 백엔드와 파이프라인을 갖춘 Python 기반 Sigma 규칙 처리 프레임워크
  • ATT&CK Navigator: ATT&CK 기술에 매핑된 탐지 적용 범위를 시각화하는 MITRE 도구
  • Uncoder.IO: 30개 이상의 SIEM 플랫폼을 지원하는 웹 기반 Sigma 규칙 변환기

일반적인 시나리오

  • 새 CVE 탐지: 취약점 악용 지표에 대한 Sigma 규칙 작성(예: 웹 로그의 Log4Shell JNDI 조회 패턴)
  • 헌팅 규칙 승격: 임시 Splunk 헌팅 쿼리를 지속적인 자동 탐지를 위한 Sigma 규칙으로 변환
  • 다중 SIEM 마이그레이션: 500개 이상의 Splunk 상관 관계 검색을 Sigma로 변환하여 Elastic Security로 마이그레이션
  • 퍼플 팀 결과물: 레드 팀 발견 사항을 즉각적인 방어 적용을 위한 Sigma 규칙으로 변환
  • 위협 인텔리전스 운영화: IOC 기반 위협 보고서를 행동 기반 Sigma 규칙으로 변환

출력 형식

SIGMA RULE DEPLOYMENT REPORT
━━━━━━━━━━━━━━━━━━━━━━━━━━━
Rule ID:      0d894093-71bc-43c3-8d63-bf520e73a7c5
Title:        Mimikatz Credential Dumping via LSASS Access
ATT&CK:       T1003.001 - LSASS Memory
Severity:     High
Status:       Deployed to Production

Conversions:
  Splunk SPL:    PASS — Saved search "sigma_lsass_access" created
  Elastic EQL:   PASS — Detection rule ID elastic-0d894093 enabled
  Sentinel KQL:  PASS — Analytics rule deployed via ARM template

Testing:
  True Positives:    4/4 test cases matched
  False Positives:   2 in 7-day backtest (svchost edge case — filter added)
  Performance:       Avg execution 3.2s on 50M events/day

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,

관련 스킬