# YARA + Sigma 规则编写方法论

## YARA 规则编写

### 基本语法

```yara
rule RuleName {
    meta:
        description = "规则描述"
        author = "作者"
        date = "2026-01"
        severity = "low/medium/high/critical"
        mitre_id = "T1234"

    strings:
        $ = "ASCII 字符串"
        $ = { 48 65 6C 6C 6F }         // 十六进制
        $ = /regex[0-9]{4}/             // 正则
        $ = "wide_string" wide          // UTF-16
        $ = "xor_encoded" xor           // XOR 编码
        $ = "case_insensitive" nocase   // 忽略大小写

    condition:
        // 逻辑组合
        uint16(0) == 0x5A4D and         // MZ header
        filesize < 500KB and
        (2 of ($s*) or $hex1) and
        not ($benign1 and $benign2)
}
```

### 性能优化

```yara
// ❌ 慢 — 全文件正则
condition: /https?:\/\/.*\.php/

// ✅ 快 — 先锚定字符串再限定位置
strings: $url = "http"
condition: $url and /https?:\/\/[a-z0-9.-]+\/[a-z]{3,8}\.php/ in (0..filesize)

// ❌ 慢 — 无锚点
condition: any of them

// ✅ 快 — 锚定在可用字符串上
condition: uint16(0) == 0x5A4D and any of them
```

### 反分析技术检测规则

```yara
// 虚拟机检测
rule AntiVM_WMI_Detection {
    meta:
        description = "检测通过 WMI 查询虚拟机信息"
        severity = "medium"
        mitre_id = "T1497"
    strings:
        $wmi1 = "SELECT * FROM Win32_BIOS" nocase
        $wmi2 = "SELECT * FROM Win32_VideoController" nocase
        $wmi3 = "SELECT * FROM Win32_NetworkAdapter" nocase
        $wmi4 = "SELECT * FROM Win32_ComputerSystem" nocase
        $bios = "VMware" nocase
        $bios2 = "VirtualBox" nocase
        $bios3 = "QEMU" nocase
    condition:
        uint16(0) == 0x5A4D and
        (2 of ($wmi*)) and
        (1 of ($bios*))
}

// 调试器检测
rule AntiDebug_PEB_Check {
    meta:
        description = "通过 PEB.BeingDebugged 检测调试器"
        severity = "medium"
        mitre_id = "T1622"
    strings:
        // x64: mov rax, gs:[0x60]; movzx eax, byte [rax+2]
        $peb_x64 = { 65 48 8B 04 25 60 00 00 00 0F B6 40 02 }
        // x86: mov eax, fs:[0x30]; movzx eax, byte [eax+2]
        $peb_x86 = { 64 A1 30 00 00 00 0F B6 40 02 }
    condition:
        uint16(0) == 0x5A4D and
        any of them
}
```

### 94 种反分析技术分类

| 类别 | 技术数量 | YARA 可检测 | 示例 |
|------|:--:|:--:|------|
| 定时检测 | 12 | 低 | Sleep → GetTickCount 对比 |
| CPU 指纹 | 8 | 中 | CPUID 指令检测 hypervisor |
| 固件/BIOS 检测 | 6 | **高** | SMBIOS 字符串匹配 |
| 硬件指纹 | 10 | 中 | MAC 地址/硬盘序列号检测 |
| API Hook 枚举 | 5 | 中 | NtQueryInformationProcess |
| 进程检测 | 15 | **高** | 进程名字符串 (frida, wireshark) |
| 文件系统检测 | 12 | **高** | 路径字符串 (C:\Program Files\VMware) |
| 注册表检测 | 8 | **高** | 注册表路径字符串 |
| 窗口检测 | 8 | **高** | 窗口类名/标题 (x64dbg, OLLYDBG) |

> 42/82 条规则 ≥75% 精度 (Anti-VM YARA Library, April 2026)

## Sigma 规则编写

### 规则模板

```yaml
title: 标题 — 描述检测行为
id: UUID-v4（生成后不变）
status: stable/experimental/test/deprecated
description: 详细描述
author: 作者
date: YYYY/MM/DD
modified: YYYY/MM/DD
references:
    - https://attack.mitre.org/techniques/TXXXX/
    - 内部引用

logsource:
    category: process_creation     # Windows 事件 ID 4688
    product: windows
    # 或: service, product: linux, category: sysmon

detection:
    # 选择条件
    selection_base:
        EventID: 4688
    selection_malicious:
        CommandLine|contains:
            - 'suspicious_command'
            - 'malware_pattern'
    # 过滤条件
    filter_legitimate:
        ParentImage|endswith: '\explorer.exe'
    
    # 最终条件
    condition: selection_base and selection_malicious and not filter_legitimate

falsepositives:
    - 合法管理工具
    - 软件开发工具
level: low/medium/high/critical
tags:
    - attack.tXXXX
    - attack.tXXXX.XXX
    - detection.malware
```

### PowerShell 恶意行为检测

```yaml
title: Suspicious PowerShell Download and Execute
id: e3b0c442-98fc-4c78-a0e5-123456789abc
status: experimental
description: |
  检测使用 PowerShell 下载并执行 Payload 的行为，
  常见于无文件恶意软件和初始访问阶段。
logsource:
    category: process_creation
    product: windows
detection:
    selection:
        Image|endswith:
            - '\powershell.exe'
            - '\pwsh.exe'
        CommandLine|contains|all:
            - 'DownloadString'
            - 'Invoke-Expression'
    condition: selection
falsepositives:
    - 系统管理员自动化脚本
    - 软件部署工具
level: high
tags:
    - attack.t1059.001  # PowerShell
    - attack.t1105      # Ingress Tool Transfer
```

### 勒索软件行为检测

```yaml
title: Potential Ransomware Activity — File Encryption + Shadow Copy Deletion
id: a1b2c3d4-5678-90ab-cdef-0123456789ab
status: stable
description: |
  检测同时出现批量文件写入和卷影副本删除的勒索软件特征行为。
logsource:
    category: process_creation
    product: windows
detection:
    sel_vss:
        CommandLine|contains:
            - 'vssadmin delete shadows'
            - 'wmic shadowcopy delete'
            - 'Get-WmiObject Win32_Shadowcopy | Remove-WmiObject'
    sel_bcdedit:
        CommandLine|contains:
            - 'bcdedit /set {default} recoveryenabled No'
    condition: sel_vss or sel_bcdedit
level: critical
tags:
    - attack.t1490  # Inhibit System Recovery
    - attack.t1486  # Data Encrypted for Impact
```

## 规则测试

```bash
# YARA 规则验证
yara -C rule.yara sample_dir/    # 编译规则并扫描
yara -s rule.yara sample.exe     # 显示匹配字符串
yara --print-meta rule.yara      # 打印元数据

# Sigma 规则转换
sigmac -t splunk rule.yml        # → Splunk SPL
sigmac -t elastalert rule.yml    # → Elastalert
sigmac -t es-qs rule.yml         # → Elasticsearch Query
sigma convert -t splunk rule.yml # sigma-cli 新版

# 规则质量检查
# 1. 不会在正常系统触发
# 2. 不会在常见软件安装/运行中触发
# 3. 在已知恶意样本上 100% 触发

# False Positive 验证
# 在 Assemblage 良性样本集（92,508 样本）上测试
```

Source: CCCS YARA Standard, SigmaHQ, Anti-VM YARA Library (2026), Joe Sandbox v44
