performing-yara-rule-development-for-detection

通过识别可执行文件中的唯一字节模式、字符串和行为指标,开发精准的 YARA 恶意软件检测规则,同时将误报率降至最低。

9 stars

Best use case

performing-yara-rule-development-for-detection is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

通过识别可执行文件中的唯一字节模式、字符串和行为指标,开发精准的 YARA 恶意软件检测规则,同时将误报率降至最低。

Teams using performing-yara-rule-development-for-detection should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/performing-yara-rule-development-for-detection/SKILL.md --create-dirs "https://raw.githubusercontent.com/killvxk/cybersecurity-skills-zh/main/skills/performing-yara-rule-development-for-detection/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/performing-yara-rule-development-for-detection/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How performing-yara-rule-development-for-detection Compares

Feature / Agentperforming-yara-rule-development-for-detectionStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

通过识别可执行文件中的唯一字节模式、字符串和行为指标,开发精准的 YARA 恶意软件检测规则,同时将误报率降至最低。

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# 为检测开发 YARA 规则

## 概述

YARA 是恶意软件研究人员的模式匹配多用工具,能够根据文本或二进制模式识别和分类恶意软件。有效的 YARA 规则结合唯一字符串模式、字节序列、PE 头特征、导入表分析和条件逻辑,在检测恶意软件家族的同时避免误报。现代 YARA-X(用 Rust 重写,2025 年 6 月起稳定版发布)带来了性能提升和新模块。规则应针对未打包的恶意软件特征,如硬编码的栈字符串、C2 URL、互斥体名称、加密常量和唯一代码序列,而非加壳程序签名。

## 前置条件

- Python 3.9+,配合 `yara-python` 库
- YARA 4.5+ 或 YARA-X 0.10+
- PE 分析工具(`pefile`、`pestudio`)
- 十六进制编辑器,用于识别唯一字节模式
- 恶意软件样本访问权限(VirusTotal、MalwareBazaar)
- 了解 PE 文件格式、字符串和导入表

## 核心概念

### 规则结构

每条 YARA 规则由三个部分组成:`meta`(可选的描述性元数据)、`strings`(模式定义)和 `condition`(匹配逻辑)。字符串类型包括文本字符串(ASCII/wide/nocase)、带通配符和跳转的十六进制模式,以及正则表达式。条件使用布尔运算符将字符串匹配与文件属性组合。

### 字符串选择策略

有效的规则针对恶意软件家族独有的、能在重新编译后仍然存活的模式。硬编码的栈字符串是极好的选择,因为编译器会持续嵌入它们。C2 域名模式、自定义加密例程、唯一错误消息和特定 API 调用序列提供了稳定的检测锚点。避免使用编译器生成的样板代码和常见库字符串。

### 性能优化

YARA 以短路方式评估条件。将最具区分性且计算代价最低的条件放在最前面。使用 `filesize` 限制快速跳过无关文件。尽量使用十六进制模式替代正则表达式。使用 `private` 规则作为复杂检测逻辑的构建块,而不生成独立匹配。

## 操作步骤

### 步骤 1:分析样本以提取唯一模式

```python
#!/usr/bin/env python3
"""提取用于 YARA 规则创建的候选字符串和字节模式。"""
import pefile
import re
import sys
from collections import Counter


def extract_strings(filepath, min_length=6):
    """从二进制文件中提取 ASCII 和宽字符字符串。"""
    with open(filepath, 'rb') as f:
        data = f.read()

    # ASCII 字符串
    ascii_strings = re.findall(
        rb'[\x20-\x7e]{' + str(min_length).encode() + rb',}', data
    )

    # 宽字符(UTF-16LE)字符串
    wide_strings = re.findall(
        rb'(?:[\x20-\x7e]\x00){' + str(min_length).encode() + rb',}', data
    )

    return {
        'ascii': [s.decode('ascii') for s in ascii_strings],
        'wide': [s.decode('utf-16-le') for s in wide_strings],
    }


def analyze_pe_imports(filepath):
    """提取导入表用于基于 API 的检测。"""
    try:
        pe = pefile.PE(filepath)
    except pefile.PEFormatError:
        return []

    imports = []
    if hasattr(pe, 'DIRECTORY_ENTRY_IMPORT'):
        for entry in pe.DIRECTORY_ENTRY_IMPORT:
            dll_name = entry.dll.decode('utf-8', errors='replace')
            for imp in entry.imports:
                if imp.name:
                    func_name = imp.name.decode('utf-8', errors='replace')
                    imports.append(f"{dll_name}!{func_name}")
    return imports


def find_unique_byte_patterns(filepath, pattern_length=16):
    """查找适用于 YARA 十六进制模式的唯一字节序列。"""
    with open(filepath, 'rb') as f:
        data = f.read()

    try:
        pe = pefile.PE(filepath)
        # 聚焦于代码节
        for section in pe.sections:
            if section.Characteristics & 0x20000000:  # IMAGE_SCN_MEM_EXECUTE
                code_start = section.PointerToRawData
                code_end = code_start + section.SizeOfRawData
                code_data = data[code_start:code_end]
                break
        else:
            code_data = data
    except Exception:
        code_data = data

    # 查找只出现一次的字节模式
    patterns = []
    for i in range(0, len(code_data) - pattern_length, 4):
        pattern = code_data[i:i+pattern_length]
        if pattern.count(b'\x00') < pattern_length // 3:  # 跳过空字节密集的模式
            hex_pattern = ' '.join(f'{b:02X}' for b in pattern)
            patterns.append(hex_pattern)

    # 统计频率并返回唯一出现的模式
    freq = Counter(patterns)
    unique = [p for p, count in freq.items() if count == 1]

    return unique[:20]  # 返回前 20 个候选


def suggest_rule_strings(filepath):
    """为 YARA 规则推荐字符串和模式。"""
    print(f"[+] 正在分析:{filepath}")

    # 提取字符串
    strings = extract_strings(filepath)

    # 过滤可疑/唯一字符串
    suspicious_keywords = [
        'http', 'https', 'cmd', 'powershell', 'mutex', 'pipe',
        'password', 'credential', 'inject', 'hook', 'debug',
        'sandbox', 'virtual', 'vmware', 'vbox',
    ]

    print("\n[+] 可疑 ASCII 字符串:")
    for s in strings['ascii']:
        if any(kw in s.lower() for kw in suspicious_keywords):
            print(f"  $ = \"{s}\" ascii")

    print("\n[+] 可疑宽字符字符串:")
    for s in strings['wide']:
        if any(kw in s.lower() for kw in suspicious_keywords):
            print(f"  $ = \"{s}\" wide")

    # 导入分析
    imports = analyze_pe_imports(filepath)
    suspicious_apis = [
        'VirtualAlloc', 'VirtualProtect', 'WriteProcessMemory',
        'CreateRemoteThread', 'NtUnmapViewOfSection', 'RtlMoveMemory',
        'OpenProcess', 'CreateToolhelp32Snapshot',
        'InternetOpenA', 'HttpSendRequestA',
        'CryptEncrypt', 'CryptDecrypt',
    ]

    print("\n[+] 可疑导入:")
    for imp in imports:
        func = imp.split('!')[-1]
        if func in suspicious_apis:
            print(f"  {imp}")

    # 字节模式
    print("\n[+] 候选十六进制模式:")
    patterns = find_unique_byte_patterns(filepath)
    for p in patterns[:5]:
        print(f"  $hex = {{ {p} }}")


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print(f"用法:{sys.argv[0]} <sample_path>")
        sys.exit(1)
    suggest_rule_strings(sys.argv[1])
```

### 步骤 2:编写并测试 YARA 规则

```python
import yara
import os

def create_yara_rule(rule_name, meta, strings, condition):
    """从各组件生成 YARA 规则。"""
    meta_str = "\n".join(f'        {k} = "{v}"' for k, v in meta.items())
    strings_str = "\n".join(f"        {s}" for s in strings)

    rule = f"""rule {rule_name} {{
    meta:
{meta_str}

    strings:
{strings_str}

    condition:
        {condition}
}}"""
    return rule


def test_yara_rule(rule_text, test_dir):
    """编译并对样本目录测试 YARA 规则。"""
    try:
        rules = yara.compile(source=rule_text)
    except yara.SyntaxError as e:
        print(f"[-] YARA 语法错误:{e}")
        return None

    results = {"matches": [], "no_match": []}

    for filename in os.listdir(test_dir):
        filepath = os.path.join(test_dir, filename)
        if not os.path.isfile(filepath):
            continue

        matches = rules.match(filepath)
        if matches:
            results["matches"].append({
                "file": filename,
                "rules": [m.rule for m in matches],
            })
        else:
            results["no_match"].append(filename)

    print(f"[+] 匹配:{len(results['matches'])} 个")
    print(f"[-] 未匹配:{len(results['no_match'])} 个")
    return results


# 示例:为假设的恶意软件家族创建规则
example_rule = create_yara_rule(
    rule_name="MalwareFamily_Variant_A",
    meta={
        "description": "Detects MalwareFamily Variant A",
        "author": "Malware Analysis Team",
        "date": "2025-01-01",
        "hash": "abc123...",
        "tlp": "WHITE",
    },
    strings=[
        '$mutex = "Global\\\\UniqueM4lwareMutex" ascii wide',
        '$c2_pattern = /https?:\\/\\/[a-z]{5,10}\\.(xyz|top|buzz)\\/gate\\.php/',
        '$api1 = "VirtualAllocEx" ascii',
        '$api2 = "WriteProcessMemory" ascii',
        '$api3 = "CreateRemoteThread" ascii',
        '$hex_decrypt = { 8B 45 ?? 33 C1 89 45 ?? 83 C1 04 }',
        '$pdb = "C:\\\\Users\\\\" ascii',
    ],
    condition=(
        'uint16(0) == 0x5A4D and filesize < 2MB and '
        '($mutex or $c2_pattern) and '
        '2 of ($api*) and '
        '$hex_decrypt'
    ),
)

print(example_rule)
```

### 步骤 3:性能测试与优化

```python
import time

def benchmark_rule(rule_text, scan_directory, iterations=3):
    """对 YARA 规则扫描性能进行基准测试。"""
    rules = yara.compile(source=rule_text)

    files = []
    for root, _, filenames in os.walk(scan_directory):
        for f in filenames:
            files.append(os.path.join(root, f))

    print(f"[+] 对 {len(files)} 个文件进行基准测试"
          f"({iterations} 次迭代)")

    times = []
    for i in range(iterations):
        start = time.perf_counter()
        matches = 0
        for filepath in files:
            try:
                result = rules.match(filepath)
                if result:
                    matches += 1
            except Exception:
                pass
        elapsed = time.perf_counter() - start
        times.append(elapsed)
        print(f"  第 {i+1} 次迭代:{elapsed:.3f} 秒({matches} 次匹配)")

    avg_time = sum(times) / len(times)
    files_per_sec = len(files) / avg_time
    print(f"\n[+] 平均:{avg_time:.3f} 秒({files_per_sec:.0f} 文件/秒)")
    return avg_time
```

## 验证标准

- YARA 规则编译无语法错误
- 规则以零漏报率检测目标恶意软件家族样本
- 对干净文件语料库扫描时,误报率低于 0.1%
- 规则性能允许每秒扫描 1000 个以上的文件
- 规则能够承受轻微的恶意软件修改(重新编译、字符串变化)
- 元数据包含哈希、作者、日期、描述和 TLP 标记

## 参考资料

- [YARA 官方文档](https://virustotal.github.io/yara/)
- [YARA-X(Rust 重写版)](https://github.com/VirusTotal/yara-x)
- [Yara-Rules 社区仓库](https://github.com/Yara-Rules/rules)
- [ReversingLabs - 编写详细的 YARA 规则](https://www.reversinglabs.com/blog/writing-detailed-yara-rules-for-malware-detection)
- [YARA 规则制作深度解析](https://cyberthreatintelligencenetwork.com/index.php/2024/09/11/yara-rule-crafting-a-deep-dive-into-signature-based-threat-hunting-strategies/)

Related Skills

performing-wireless-security-assessment-with-kismet

9
from killvxk/cybersecurity-skills-zh

使用 Kismet 通过被动射频监控进行无线网络安全评估,检测流氓接入点(Rogue AP)、隐藏 SSID、弱加密和未授权客户端。

performing-wireless-network-penetration-test

9
from killvxk/cybersecurity-skills-zh

执行无线网络渗透测试,通过捕获握手包、破解 WPA2/WPA3 密钥、检测流氓接入点以及使用 Aircrack-ng 和相关工具测试无线网络分段,评估 WiFi 安全性。

performing-windows-artifact-analysis-with-eric-zimmerman-tools

9
from killvxk/cybersecurity-skills-zh

使用 Eric Zimmerman 的开源 EZ Tools 套件(包括 KAPE、MFTECmd、PECmd、LECmd、JLECmd 和 Timeline Explorer)执行全面的 Windows 取证制品分析,解析注册表 hive、预取文件、事件日志和文件系统元数据。

performing-wifi-password-cracking-with-aircrack

9
from killvxk/cybersecurity-skills-zh

在授权无线安全评估中捕获 WPA/WPA2 握手包,并使用 aircrack-ng、hashcat 和字典攻击进行离线密码破解, 以评估密码短语强度和无线网络安全状况。

performing-web-cache-poisoning-attack

9
from killvxk/cybersecurity-skills-zh

在授权安全测试期间,通过未纳入缓存键的头部和参数毒化缓存响应,利用 Web 缓存机制向其他用户投递恶意内容。

performing-web-cache-deception-attack

9
from killvxk/cybersecurity-skills-zh

通过利用 CDN 缓存层与源服务器之间的路径规范化差异,执行 Web 缓存欺骗攻击,从而缓存并获取敏感的已认证内容。

performing-web-application-vulnerability-triage

9
from killvxk/cybersecurity-skills-zh

使用 OWASP 风险评级方法论对 DAST/SAST 扫描器的 Web 应用程序漏洞发现进行分类,区分真阳性和假阳性,并确定修复优先级。

performing-web-application-scanning-with-nikto

9
from killvxk/cybersecurity-skills-zh

Nikto 是一款开源 Web 服务器和 Web 应用程序扫描器,可针对超过 7,000 个潜在危险文件/程序进行测试,检查超过 1,250 个服务器的过期版本,并识别超过 270 个服务器的版本特定问题。

performing-web-application-penetration-test

9
from killvxk/cybersecurity-skills-zh

遵循 OWASP Web 安全测试指南(WSTG)方法论,对 Web 应用程序执行系统化安全测试,识别认证、授权、 输入验证、会话管理和业务逻辑中的漏洞。测试人员以 Burp Suite 作为主要拦截代理,结合手动测试技术 发现自动化扫描器遗漏的缺陷。适用于 Web 应用渗透测试、OWASP 测试、应用安全评估或 Web 漏洞测试等请求场景。

performing-web-application-firewall-bypass

9
from killvxk/cybersecurity-skills-zh

使用编码技术、HTTP 方法操控、参数污染和载荷混淆绕过 Web 应用防火墙保护,将 SQL 注入、XSS 及其他攻击载荷穿透 WAF 检测规则。

performing-vulnerability-scanning-with-nessus

9
from killvxk/cybersecurity-skills-zh

使用 Tenable Nessus 执行认证和未认证漏洞扫描,识别网络基础设施、服务器和应用程序中的已知漏洞、 错误配置、默认凭据和缺失补丁。扫描器将发现与 CVE 数据库和 CVSS 评分关联,生成优先级修复指导。 适用于漏洞扫描、Nessus 评估、补丁合规检查或自动化漏洞检测等请求场景。

performing-vlan-hopping-attack

9
from killvxk/cybersecurity-skills-zh

在授权环境中使用交换机欺骗(Switch Spoofing)和双标签(Double Tagging)技术模拟 VLAN 跳转攻击, 测试 VLAN 分段有效性,并验证交换机端口安全配置对二层旁路攻击的抵御能力。