[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7EVK5J6FYR5ZEDYQKG2FT61":3,"skill-same:01M7EVK5J6FYR5ZEDYQKG2FT61":86},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":6,"ownerHtmlUrl":29,"ownerBlogUrl":6,"ownerDescription":30,"updatedAt":31,"install":32,"resources":45},"01M7EVK5J6FYR5ZEDYQKG2FT61","yara-rule-authoring",null,"Guides authoring of high-quality YARA-X detection rules for malware identification. Use when writing, reviewing, or optimizing YARA rules. Covers naming conventions, string selection, performance optimization, migration from legacy YARA, and false positive reduction. Triggers on: YARA, YARA-X, malware detection, threat hunting, IOC, signature, crx module, dex module.","lza6\u002FArmor-piercing-system-prompts","lza6","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F128880206?v=4","01M7EB3K7WPX5T28EJ2NVHE6EG","Chinese-tingfeng","01M7EB3K97E1KQ16QWKJMFNGX8",11,"MIT","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F04-安全渗透\u002Fyara-rule-authoring\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: yara-rule-authoring\ndescription: >\n  Guides authoring of high-quality YARA-X detection rules for malware identification.\n  Use when writing, reviewing, or optimizing YARA rules. Covers naming conventions,\n  string selection, performance optimization, migration from legacy YARA, and false\n  positive reduction. Triggers on: YARA, YARA-X, malware detection, threat hunting,\n  IOC, signature, crx module, dex module.\n---\n\n# YARA-X Rule Authoring\n\nWrite detection rules that catch malware without drowning in false positives.\n\n**This skill targets YARA-X**, the Rust-based successor to legacy YARA — 5-10x faster regex, better errors, built-in formatter, stricter validation, new modules (crx, dex), 99% rule compatibility. It powers VirusTotal's production systems. Install with `brew install yara-x` or `cargo install yara-x`; the CLI is `yr`. See [Migrating from Legacy YARA](#migrating-from-legacy-yara) for existing rules.\n\n## Core Principles\n\n1. **Strings must generate good atoms** — YARA extracts 4-byte subsequences for fast matching. Strings with repeated bytes, common sequences, or under 4 bytes force slow bytecode verification on too many files.\n\n2. **Target specific families, not categories** — \"Detects ransomware\" catches everything and nothing. \"Detects LockBit 3.0 configuration extraction routine\" catches what you want.\n\n3. **Test against goodware before deployment** — A rule that fires on Windows system files is useless. Validate against VirusTotal's goodware corpus or your own clean file set.\n\n4. **Short-circuit with cheap checks first** — `filesize` (instant), then magic bytes (nearly instant), then strings (cheap), then modules (expensive).\n\n5. **Metadata is documentation** — Future you (and your team) need to know what this catches, why, and where the sample came from.\n\n## When to Use\n\n- Writing new YARA-X rules for malware detection\n- Reviewing existing rules for quality or performance issues\n- Optimizing slow-running rulesets\n- Converting IOCs or threat intel into detection signatures\n- Debugging false positive issues\n- Preparing rules for production deployment\n- Migrating legacy YARA rules to YARA-X\n- Analyzing Chrome extensions (crx module) or Android apps (dex module)\n\n## When NOT to Use\n\n- Static analysis requiring disassembly → use Ghidra\u002FIDA skills\n- Dynamic malware analysis → use sandbox analysis skills\n- Network-based detection → use Suricata\u002FSnort skills\n- Memory forensics with Volatility → use memory forensics skills\n- Simple hash-based detection → just use hash lists\n\n## Platform Considerations\n\nYARA works on any file type. Adapt patterns to your target:\n\n| Platform | Magic Bytes | Bad Strings | Good Strings |\n|----------|-------------|-------------|--------------|\n| **Windows PE** | `uint16(0) == 0x5A4D` | API names, Windows paths | Mutex names, PDB paths |\n| **macOS Mach-O** | `uint32(0) == 0xFEEDFACE` (32-bit), `0xFEEDFACF` (64-bit), `uint32be(0) == 0xCAFEBABE` (universal) | Common Obj-C methods | Keylogger strings, persistence paths |\n| **JavaScript\u002FNode** | (none needed) | `require`, `fetch`, `axios` | Obfuscator signatures, eval+decode chains |\n| **npm\u002Fpip packages** | (none needed) | `postinstall`, `dependencies` | Suspicious package names, exfil URLs |\n| **Office docs** | `uint32(0) == 0x04034B50` | VBA keywords | Macro auto-exec, encoded payloads |\n| **VS Code extensions** | (none needed) | `vscode.workspace` | Uncommon activationEvents, hidden file access |\n| **Chrome extensions** | Use `crx` module | Common Chrome APIs | Permission abuse, manifest anomalies |\n| **Android apps** | Use `dex` module | Standard DEX structure | Obfuscated classes, suspicious permissions |\n\n> **`uintNN()` reads little-endian.** Write the constant as the bytes *reversed*, or use `uintNNbe()` and write them in file order. A ZIP\u002FOOXML file starts with bytes `50 4B 03 04`, so it is `uint32(0) == 0x04034B50` — `uint32(0) == 0x504B0304` compiles cleanly and never matches anything. The same trap catches Mach-O universal binaries: on disk they are `CA FE BA BE`, so `uint32(0) == 0xCAFEBABE` is a dead branch; write `uint32be(0) == 0xCAFEBABE` or `uint32(0) == 0xBEBAFECA`. Verify with `yr scan` against one known-good sample before trusting any magic-byte check.\n\n### macOS Malware Detection\n\nNo dedicated Mach-O module exists yet — use magic bytes plus string patterns. Good indicators:\n\n- Keylogger artifacts: `CGEventTapCreate`, `kCGEventKeyDown`\n- SSH tunnel strings: `ssh -D`, `tunnel`, `socks`\n- Persistence paths: `~\u002FLibrary\u002FLaunchAgents`, `\u002FLibrary\u002FLaunchDaemons`\n- Credential theft: `security find-generic-password`, `keychain`\n\n```yara\n\u002F\u002F Pattern from Airbnb BinaryAlert\nrule SUSP_Mac_ProtonRAT\n{\n    strings:\n        $lib1 = \"SRWebSocket\" ascii          \u002F\u002F Library indicators\n        $lib2 = \"SocketRocket\" ascii\n        $behav1 = \"SSH tunnel not launched\" ascii   \u002F\u002F Behavioral indicators\n        $behav2 = \"Keylogger\" ascii\n    condition:\n        (uint32(0) == 0xFEEDFACF or uint32be(0) == 0xCAFEBABE) and\n        any of ($lib*) and any of ($behav*)\n}\n```\n\n### JavaScript Detection\n\n| Target | Approach |\n|---|---|\n| npm package | `package.json` patterns, postinstall\u002Fpreinstall hooks, exfil combination: fetch + env access + credential paths |\n| Chrome extension | `crx` module |\n| Other extension | Manifest patterns, background script behaviors |\n| Standalone JS | Obfuscation markers (eval+atob, fromCharCode chains), unique function\u002Fvariable names, packed payloads |\n| Minified\u002Fwebpack bundle | Unique strings that survive bundling (URLs, magic values); **avoid function names** — they get mangled |\n\n**Good JS strings:** Ethereum function selectors — `{ a9 05 9c bb }` (`transfer(address,uint256)`), `{ 70 a0 82 31 }` (`balanceOf(address)`); zero-width characters for steganography — `{ E2 80 8B E2 80 8C }`; obfuscator signatures — `_0x`, `var _0x`; specific C2 domains and webhook URLs.\n\n**Bad JS strings:** `require`, `fetch`, `axios` (too common); `Buffer`, `crypto` (legitimate uses everywhere); `process.env` alone (need specific env var names).\n\n## String Selection\n\n**Value ranking:** mutex names are gold, C2 paths silver, error messages bronze. Stack strings are almost always unique. If you need more than 6 strings, you're over-fitting.\n\nReject a candidate string when any of these holds:\n\n| Test | Why it fails | Do instead |\n|---|---|---|\n| Under 4 bytes | No atom | Find a longer string |\n| Repeated bytes (`0000`, `9090`) | Weak atom | Add surrounding context |\n| API name (`VirtualAlloc`, `CreateRemoteThread`) | Every packer and installer calls it | Hex pattern of the call site plus a unique marker |\n| Appears in Windows system files | Guaranteed FPs | Find something family-specific |\n| Common path (`C:\\Windows\\`, `cmd.exe`) | Ubiquitous | Find malware-specific paths |\n| Appears in other malware families | Not identifying *this* family | Combine with a family-specific marker |\n\nEverything left — unique to this family — is what the rule should rest on.\n\n### Choosing a String Type\n\n| Need | Use |\n|---|---|\n| Exact ASCII\u002FUnicode text | `$s = \"MutexName\" ascii wide` |\n| Specific byte sequence | `$h = { 4D 5A 90 00 }` |\n| Byte sequence with variation | Hex wildcards: `{ 4D 5A ?? ?? 50 45 }` |\n| Pattern with structure (URLs, paths) | Bounded regex: `\u002Fhttps:\\\u002F\\\u002F[a-z]{5,20}\\.onion\u002F` |\n| Unknown encoding (XOR, base64) | Modifier: `$s = \"config\" xor(0x00-0xFF)` |\n\n**Modifier discipline:** never use `nocase` or `wide` speculatively — only with confirmed evidence that case or encoding varies across samples. `nocase` doubles atom generation; `wide` doubles string matching. \"If you don't have a clear reason for using those modifiers, don't do it\" — Kaspersky Applied YARA.\n\n## Condition Design\n\nOrder for short-circuit: `filesize \u003C`, magic bytes, strings, modules. If the condition runs past 5 lines, split into multiple rules.\n\n### all of vs any of\n\n| Situation | Use |\n|---|---|\n| Strings are individually unique to the malware | `any of them` — each alone is suspicious |\n| Strings are common but the combination is suspicious | `all of them` — require the full pattern |\n| Strings have different confidence levels | Group: `all of ($core_*) and any of ($variant_*)` |\n| Seeing false positives | Tighten: `any` → `all`, add more required strings |\n\n**Lesson from production:** rules using `any of ($network_*)` where the strings included `fetch`, `axios`, and `http` matched virtually all web applications. Switching to require a credential path AND a network call AND an exfil destination eliminated the FPs.\n\n### Grouping by Confidence\n\nDifferent indicator types carry different weight — a C2 domain might be definitive while library imports need corroboration. Grouping by prefix lets you express graduated requirements:\n\n```yara\nstrings:\n    $a1 = \"SRWebSocket\" ascii            \u002F\u002F Category A: library indicators\n    $a2 = \"SocketRocket\" ascii\n    $b1 = \"SSH tunnel\" ascii             \u002F\u002F Category B: behavioral\n    $b2 = \"keylogger\" ascii nocase\n    $c1 = \u002Fhttps:\\\u002F\\\u002F[a-z0-9]{8,16}\\.onion\u002F   \u002F\u002F Category C: C2\n\ncondition:\n    filesize \u003C 10MB and\n    any of ($a*) and any of ($b*)        \u002F\u002F Evidence from BOTH categories\n```\n\n### Modules vs Byte Checks\n\n| Need | Use |\n|---|---|\n| imphash, rich header, authenticode | PE module — too complex to replicate |\n| Magic bytes or simple offsets | `uint16`\u002F`uint32` — faster, no module overhead |\n| Section names\u002Fsizes | PE module, but put the magic-byte filter FIRST |\n| Chrome extension permissions | `crx` module — string parsing is fragile |\n| LNK target paths | `lnk` module — the format is complex |\n\n\"Avoid the magic module — use explicit hex checks instead\" — Neo23x0. Generalize it: if `uint32()` can do the job, don't load a module.\n\n### Performance\n\n- **Regex must be anchored to a 4+ byte literal.** Without one it evaluates at *every* file offset — catastrophic. Write `\u002Fmshta\\.exe http:\\\u002F\\\u002F...\u002F`, not `\u002Fhttp:\\\u002F\\\u002F...\u002F`. If you can't anchor, use a hex pattern with wildcards.\n- **Bound every regex quantifier** — `.{0,30}`, never `.*`. Unbounded regex is both a performance disaster and a memory explosion.\n- **Bound loops with filesize** — `filesize \u003C 100KB and for all i in (1..#a) : ...`. Unbounded `#a` can reach thousands in large files.\n- **Prefer hex over regex** where the bytes are fixed.\n\n## Before Writing: Is the Sample Packed?\n\n| Signal | What to do |\n|---|---|\n| Entropy > 7.0 | Likely packed — find the unpacked layer first |\n| Few or no readable strings | Likely packed — use entropy, PE structure, or packer signatures |\n| UPX\u002FMPRESS\u002Fcustom packer detected | Target the unpacked payload OR detect the packer itself |\n| Readable strings available | Proceed with string-based detection |\n\n**Don't write rules against packed layers.** The packing changes; the payload doesn't.\n\n### When Strings Fail, Pivot to Structure\n\nIf extraction returns only API names and generic paths:\n\n| Available signal | Use |\n|---|---|\n| High entropy sections | `math.entropy()` on specific sections |\n| Unusual import pattern | `pe.imphash()` for import-hash clustering |\n| PE structure anomalies | Section names, sizes, characteristics |\n| Metadata present | Version info, timestamps, resources |\n| Nothing unique | This sample may not be detectable with YARA alone |\n\n\"One can try to use other file properties, such as metadata, entropy, import hashes or other data which stays constant.\" — Kaspersky Applied YARA Training\n\n## Debugging False Positives\n\n1. **Which string matched?** — `yr scan -s rule.yar false_positive.exe`\n2. **In a legitimate library?** — add a `not $fp_vendor_string` exclusion\n3. **A common development pattern?** — replace the string with something more specific\n4. **Multiple generic strings matching together?** — tighten to require all, plus a unique marker\n5. **Malware using a common technique?** — target its specific implementation details, not the technique\n\n### When to Abandon the Approach\n\n- **Extraction returns only API names and paths** → [pivot to structure](#when-strings-fail-pivot-to-structure)\n- **Can't find 3 unique strings** → probably packed; target the unpacked version or detect the packer\n- **Rule matches goodware** → 1-2 matches: investigate and tighten; 3-5: find different indicators; 6+: start over\n- **Performance is terrible after optimization** → architecture problem; split into focused rules or add strict pre-filters\n- **The description is hard to write** → the rule is too vague. If you can't explain what it catches, it catches too much\n\n## Rationalizations to Reject\n\nWhen you catch yourself thinking these, stop and reconsider.\n\n| Rationalization | Expert Response |\n|-----------------|-----------------|\n| \"This generic string is unique enough\" \u002F \"This hex pattern is unique\" | Unique in one sample ≠ unique across the ecosystem. Test against goodware; your intuition is wrong. |\n| \"yarGen gave me these strings\" | yarGen suggests, you validate. Check each one manually — expect to discard 80%. |\n| \"It works on my 10 samples\" | 10 samples ≠ production. Use a goodware corpus. |\n| \"One rule to catch all variants\" | Causes FP floods. Target specific families. |\n| \"I'll make it more specific if we get FPs\" \u002F \"I'll add more conditions later\" | Write tight rules upfront. A weak rule deployed is damage done, and FPs burn trust. |\n| \"This is just for hunting\" | Hunting rules become detection rules. Same quality bar. |\n| \"The API name makes it malicious\" | Legitimate software uses the same APIs. Need behavioral context. |\n| \"`any of them` is fine for these common strings\" | Common strings + `any` = FP flood. Use `any of` only for individually unique strings. |\n| \"This regex is specific enough\" | `\u002Ffetch.*token\u002F` matches all auth code. Add an exfil destination requirement. |\n| \"I'll use `.*` for flexibility\" | Unbounded regex = performance disaster plus memory explosion. Use `.{0,30}`. |\n| \"The JavaScript looks clean\" | Attackers poison legitimate code with injects. Check for eval+decode chains. |\n| \"Performance doesn't matter\" | One slow rule slows the entire ruleset. Optimize atoms. |\n| \"I'll use `--relaxed-re-syntax` everywhere\" | Masks real bugs. Fix the regex instead of hiding the problem. |\n| \"PEiD rules still work\" | Obsolete. 32-bit packers aren't relevant. |\n\n## Toolkit\n\n| Tool | Purpose |\n|------|---------|\n| **yr CLI** | `yr check` (validate), `yr fmt` (format), `yr scan -s` (scan, show strings), `yr dump -m pe` (inspect structure) |\n| **yarGen** | Extract candidate strings: `yarGen.py -m samples\u002F --excludegood` |\n| **FLOSS** | Extract obfuscated\u002Fstack strings: `floss sample.exe` — when yarGen comes up empty |\n| **signature-base** | Study quality examples |\n| **YARA-CI** | Goodware corpus testing before deployment |\n\nMaster these five. Don't get distracted by tool catalogs.\n\n**Development cycle:**\n\n```bash\nyr check rule.yar                                   # syntax, with precise line numbers\nyr fmt -w rule.yar                                  # standardize formatting\nyr dump -m pe sample.exe --output-format yaml       # inspect structure, no dummy rule needed\ntime yr scan -s rule.yar corpus\u002F                    # scan with timing\n```\n\nReach for `yr dump` when investigating which module fields are available, debugging why a module condition isn't matching, or exploring a new module (crx, lnk, dotnet) before writing against it. YARA-X error messages carry precise source locations — if `yr check` says line 15, the problem is on line 15.\n\n**Version-gated features:** `private $helper = \"pattern\"` matches but stays out of output (v1.3.0+); `\u002F\u002F suppress: slow_pattern` silences a specific warning inline (v1.4.0+); `filesize \u003C 10_000_000` numeric underscores (v1.5.0+). `$_unused` also suppresses unused-string warnings.\n\n## Chrome Extension Analysis (crx module)\n\nRequires YARA-X v1.5.0+, or v1.11.0+ for `permhash()`.\n\n**Key APIs:** `crx.is_crx`, `crx.permissions`, `crx.permhash()`\n**Red flags:** `nativeMessaging` + `downloads`, `debugger` permission, content scripts on `\u003Call_urls>`\n\n```yara\nimport \"crx\"\n\nrule SUSP_CRX_HighRiskPerms {\n    condition:\n        crx.is_crx and\n        for any perm in crx.permissions : (perm == \"debugger\")\n}\n```\n\nSee [crx-module.md](references\u002Fcrx-module.md) for the full API, permission risk assessment, and example rules.\n\n## Android DEX Analysis (dex module)\n\nRequires YARA-X v1.11.0+. **Not compatible with legacy YARA's dex module** — the API is completely different.\n\n**Key APIs:** `dex.is_dex`, `dex.contains_class()`, `dex.contains_method()`, `dex.contains_string()`\n**Red flags:** single-letter class names (obfuscation), `DexClassLoader` reflection, encrypted assets\n\n```yara\nimport \"dex\"\n\nrule SUSP_DEX_DynamicLoading {\n    condition:\n        dex.is_dex and\n        dex.contains_class(\"Ldalvik\u002Fsystem\u002FDexClassLoader;\")\n}\n```\n\nSee [dex-module.md](references\u002Fdex-module.md) for the full API, obfuscation detection, and example rules.\n\n## Migrating from Legacy YARA\n\n99% rule compatibility, but stricter validation:\n\n```bash\nyr check --relaxed-re-syntax rules\u002F   # identify issues\n# fix each one, then verify without relaxed mode:\nyr check rules\u002F\n```\n\n| Issue | Legacy | YARA-X Fix |\n|-------|--------|------------|\n| Literal `{` in regex | `\u002F{\u002F` | `\u002F\\{\u002F` |\n| Invalid escapes | `\\R` silently literal | `\\\\R` or `R` |\n| Base64 strings | Any length | 3+ chars required |\n| Negative indexing | `@a[-1]` | `@a[#a - 1]` |\n| Duplicate modifiers | Allowed | Remove duplicates |\n\n`--relaxed-re-syntax` is a diagnostic, not a destination. Fix the regex.\n\n## Naming and Metadata\n\n```\n{CATEGORY}_{PLATFORM}_{FAMILY}_{VARIANT}_{DATE}      e.g. MAL_Win_Emotet_Loader_Jan25\n```\n\n**Categories:** `MAL_` (malware), `HKTL_` (hacking tool), `WEBSHELL_`, `EXPL_`, `SUSP_` (suspicious), `GEN_` (generic). **Platforms:** `Win_`, `Lnx_`, `Mac_`, `Android_`, `CRX_`.\n\nEvery rule needs `description` (starting with \"Detects\"), `author`, `reference`, and `date`:\n\n```yara\nmeta:\n    description = \"Detects Example malware via unique mutex and C2 path\"\n    author = \"Your Name \u003Cemail@example.com>\"\n    reference = \"https:\u002F\u002Fexample.com\u002Fanalysis\"\n    date = \"2025-01-29\"\n```\n\nSee [style-guide.md](references\u002Fstyle-guide.md) for full conventions.\n\n## Workflow\n\n1. **Gather samples** — multiple; single-sample rules are brittle\n2. **Extract candidates** — `yarGen -m samples\u002F --excludegood`\n3. **Validate quality** — apply the [string selection](#string-selection) tests; expect to discard 80% of yarGen output\n4. **Write the rule** — proper metadata, cheap checks first\n5. **Lint and test** — `yr check`, `yr fmt`, the linter script\n6. **Goodware validation** — VirusTotal corpus or local clean files\n7. **Deploy** — full metadata, then monitor for FPs\n\nQuality signals along the way: a rule matching under 50% of known variants is too narrow; one matching goodware is too broad.\n\n**Reviewing a rule someone else wrote** — run both scripts before reading the rule by eye, and quote the codes they emit:\n\n```bash\nuv run {baseDir}\u002Fscripts\u002Fyara_lint.py suspect.yar      # style, metadata, YARA-X compatibility\nuv run {baseDir}\u002Fscripts\u002Fatom_analyzer.py suspect.yar  # atom quality per string\n```\n\nThey catch the mechanical faults — short strings, FP-prone substrings, unbounded quantifiers, expensive terms ahead of cheap ones — so your attention goes to the judgement calls they cannot make: whether the strings identify *this* family, and whether the condition can fire on generic strings alone. Report findings by code (`E002`, `W009`) so the author can look each one up in [style-guide.md](references\u002Fstyle-guide.md).\n\nSee [testing.md](references\u002Ftesting.md) for the validation workflow and [rule-development.md](workflows\u002Frule-development.md) for the full step-by-step guide.\n\n## Common Mistakes\n\n| Mistake | Bad | Good |\n|---------|-----|------|\n| API names as indicators | `\"VirtualAlloc\"` | Hex pattern of call site + unique mutex |\n| Unbounded regex | `\u002Fhttps?:\\\u002F\\\u002F.*\u002F` | `\u002Fhttps?:\\\u002F\\\u002F[a-z0-9]{8,12}\\.onion\u002F` |\n| Missing file type filter | `pe.imports(...)` first | `uint16(0) == 0x5A4D and filesize \u003C 10MB` first |\n| Short strings | `\"abc\"` (3 bytes) | `\"abcdef\"` (4+ bytes) |\n| Unescaped braces (YARA-X) | `\u002Fconfig{key}\u002F` | `\u002Fconfig\\{key\\}\u002F` |\n| Wrong-endian magic bytes | `uint32(0) == 0xCAFEBABE` | `uint32be(0) == 0xCAFEBABE` |\n\n## Quality Checklist\n\nBefore deploying any rule:\n\n- [ ] Name follows `{CATEGORY}_{PLATFORM}_{FAMILY}_{VARIANT}_{DATE}`\n- [ ] Description starts with \"Detects\" and explains what\u002Fhow\n- [ ] All required metadata present (author, reference, date)\n- [ ] Strings are unique — not API names, common paths, or format strings\n- [ ] All strings 4+ bytes with good atom potential\n- [ ] Base64 modifier only on strings with 3+ characters\n- [ ] Regex bounded, anchored to a literal, with `{` escaped\n- [ ] Condition starts with cheap checks (filesize, magic bytes)\n- [ ] Magic-byte constants verified against a known-good sample\n- [ ] Rule matches all target samples\n- [ ] Rule produces zero matches on the goodware corpus\n- [ ] `yr check` and `yr fmt --check` pass\n- [ ] Linter passes with no errors\n- [ ] Peer review completed\n\n## Scripts\n\n```bash\nuv run {baseDir}\u002Fscripts\u002Fyara_lint.py rule.yar      # validate style\u002Fmetadata\nuv run {baseDir}\u002Fscripts\u002Fatom_analyzer.py rule.yar  # check string quality\n```\n\nSee [README.md](..\u002F..\u002FREADME.md#scripts) for detailed script documentation.\n\n## Further Reading\n\n| Topic | Document |\n|-------|----------|\n| Naming and metadata conventions | [style-guide.md](references\u002Fstyle-guide.md) |\n| Performance and atom optimization | [performance.md](references\u002Fperformance.md) |\n| String types and judgment | [strings.md](references\u002Fstrings.md) |\n| Testing and validation | [testing.md](references\u002Ftesting.md) |\n| Chrome extension module (crx) | [crx-module.md](references\u002Fcrx-module.md) |\n| Android DEX module (dex) | [dex-module.md](references\u002Fdex-module.md) |\n| Complete rule development process | [rule-development.md](workflows\u002Frule-development.md) |\n\nThe `examples\u002F` directory holds real, attributed rules worth reading before writing your own:\n\n| Example | Demonstrates | Source |\n|---------|--------------|--------|\n| [MAL_Win_Remcos_Jan25.yar](examples\u002FMAL_Win_Remcos_Jan25.yar) | PE malware: graduated string counts, multiple rules per family | Elastic Security |\n| [MAL_Mac_ProtonRAT_Jan25.yar](examples\u002FMAL_Mac_ProtonRAT_Jan25.yar) | macOS: Mach-O magic bytes, multi-category grouping | Airbnb BinaryAlert |\n| [MAL_NPM_SupplyChain_Jan25.yar](examples\u002FMAL_NPM_SupplyChain_Jan25.yar) | npm supply chain: real attack patterns, ERC-20 selectors | Stairwell Research |\n| [SUSP_JS_Obfuscation_Jan25.yar](examples\u002FSUSP_JS_Obfuscation_Jan25.yar) | JavaScript: obfuscator detection, density-based matching | imp0rtp3, Nils Kuhnert |\n| [SUSP_CRX_SuspiciousPermissions.yar](examples\u002FSUSP_CRX_SuspiciousPermissions.yar) | Chrome extensions: crx module, permissions | Educational |\n\n**Rule repositories to learn from:** [Neo23x0\u002Fsignature-base](https:\u002F\u002Fgithub.com\u002FNeo23x0\u002Fsignature-base) (17,000+ production rules), [elastic\u002Fprotections-artifacts](https:\u002F\u002Fgithub.com\u002Felastic\u002Fprotections-artifacts) (endpoint-tested), [imp0rtp3\u002Fjs-yara-rules](https:\u002F\u002Fgithub.com\u002Fimp0rtp3\u002Fjs-yara-rules) (JavaScript), [InQuest\u002Fawesome-yara](https:\u002F\u002Fgithub.com\u002FInQuest\u002Fawesome-yara) (curated index).\n\n**Guides:** [YARA Style Guide](https:\u002F\u002Fgithub.com\u002FNeo23x0\u002FYARA-Style-Guide) and [YARA Performance Guidelines](https:\u002F\u002Fgithub.com\u002FNeo23x0\u002FYARA-Performance-Guidelines) (Neo23x0), [YARA-X documentation](https:\u002F\u002Fvirustotal.github.io\u002Fyara-x\u002F).\n\n**macOS specifics:** Apple's own production rules ship at `\u002FSystem\u002FLibrary\u002FCoreServices\u002FXProtect.bundle\u002F`; [objective-see](https:\u002F\u002Fobjective-see.org\u002F) publishes macOS malware research and samples.\n","# YARA-X Rule Authoring\n\nWrite detection rules that catch malware without drowning in false positives.\n\n**This skill targets YARA-X**, the Rust-based successor to legacy YARA — 5-10x faster regex, better errors, built-in formatter, stricter validation, new modules (crx, dex), 99% rule compatibility. It powers VirusTotal's production systems. Install with `brew install yara-x` or `cargo install yara-x`; the CLI is `yr`. See [Migrating from Legacy YARA](#migrating-from-legacy-yara) for existing rules.\n\n## Core Principles\n\n1. **Strings must generate good atoms** — YARA extracts 4-byte subsequences for fast matching. Strings with repeated bytes, common sequences, or under 4 bytes force slow bytecode verification on too many files.\n\n2. **Target specific families, not categories** — \"Detects ransomware\" catches everything and nothing. \"Detects LockBit 3.0 configuration extraction routine\" catches what you want.\n\n3. **Test against goodware before deployment** — A rule that fires on Windows system files is useless. Validate against VirusTotal's goodware corpus or your own clean file set.\n\n4. **Short-circuit with cheap checks first** — `filesize` (instant), then magic bytes (nearly instant), then strings (cheap), then modules (expensive).\n\n5. **Metadata is documentation** — Future you (and your team) need to know what this catches, why, and where the sample came from.\n\n## When to Use\n\n- Writing new YARA-X rules for malware detection\n- Reviewing existing rules for quality or performance issues\n- Optimizing slow-running rulesets\n- Converting IOCs or threat intel into detection signatures\n- Debugging false positive issues\n- Preparing rules for production deployment\n- Migrating legacy YARA rules to YARA-X\n- Analyzing Chrome extensions (crx module) or Android apps (dex module)\n\n## When NOT to Use\n\n- Static analysis requiring disassembly → use Ghidra\u002FIDA skills\n- Dynamic malware analysis → use sandbox analysis skills\n- Network-based detection → use Suricata\u002FSnort skills\n- Memory forensics with Volatility → use memory forensics skills\n- Simple hash-based detection → just use hash lists\n\n## Platform Considerations\n\nYARA works on any file type. Adapt patterns to your target:\n\n| Platform | Magic Bytes | Bad Strings | Good Strings |\n|----------|-------------|-------------|--------------|\n| **Windows PE** | `uint16(0) == 0x5A4D` | API names, Windows paths | Mutex names, PDB paths |\n| **macOS Mach-O** | `uint32(0) == 0xFEEDFACE` (32-bit), `0xFEEDFACF` (64-bit), `uint32be(0) == 0xCAFEBABE` (universal) | Common Obj-C methods | Keylogger strings, persistence paths |\n| **JavaScript\u002FNode** | (none needed) | `require`, `fetch`, `axios` | Obfuscator signatures, eval+decode chains |\n| **npm\u002Fpip packages** | (none needed) | `postinstall`, `dependencies` | Suspicious package names, exfil URLs |\n| **Office docs** | `uint32(0) == 0x04034B50` | VBA keywords | Macro auto-exec, encoded payloads |\n| **VS Code extensions** | (none needed) | `vscode.workspace` | Uncommon activationEvents, hidden file access |\n| **Chrome extensions** | Use `crx` module | Common Chrome APIs | Permission abuse, manifest anomalies |\n| **Android apps** | Use `dex` module | Standard DEX structure | Obfuscated classes, suspicious permissions |\n\n> **`uintNN()` reads little-endian.** Write the constant as the bytes *reversed*, or use `uintNNbe()` and write them in file order. A ZIP\u002FOOXML file starts with bytes `50 4B 03 04`, so it is `uint32(0) == 0x04034B50` — `uint32(0) == 0x504B0304` compiles cleanly and never matches anything. The same trap catches Mach-O universal binaries: on disk they are `CA FE BA BE`, so `uint32(0) == 0xCAFEBABE` is a dead branch; write `uint32be(0) == 0xCAFEBABE` or `uint32(0) == 0xBEBAFECA`. Verify with `yr scan` against one known-good sample before trusting any magic-byte check.\n\n### macOS Malware Detection\n\nNo dedicated Mach-O module exists yet — use magic bytes plus string patterns. Good indicators:\n\n- Keylogger artifacts: `CGEventTapCreate`, `kCGEventKeyDown`\n- SSH tunnel strings: `ssh -D`, `tunnel`, `socks`\n- Persistence paths: `~\u002FLibrary\u002FLaunchAgents`, `\u002FLibrary\u002FLaunchDaemons`\n- Credential theft: `security find-generic-password`, `keychain`\n\n```yara\n\u002F\u002F Pattern from Airbnb BinaryAlert\nrule SUSP_Mac_ProtonRAT\n{\n    strings:\n        $lib1 = \"SRWebSocket\" ascii          \u002F\u002F Library indicators\n        $lib2 = \"SocketRocket\" ascii\n        $behav1 = \"SSH tunnel not launched\" ascii   \u002F\u002F Behavioral indicators\n        $behav2 = \"Keylogger\" ascii\n    condition:\n        (uint32(0) == 0xFEEDFACF or uint32be(0) == 0xCAFEBABE) and\n        any of ($lib*) and any of ($behav*)\n}\n```\n\n### JavaScript Detection\n\n| Target | Approach |\n|---|---|\n| npm package | `package.json` patterns, postinstall\u002Fpreinstall hooks, exfil combination: fetch + env access + credential paths |\n| Chrome extension | `crx` module |\n| Other extension | Manifest patterns, background script behaviors |\n| Standalone JS | Obfuscation markers (eval+atob, fromCharCode chains), unique function\u002Fvariable names, packed payloads |\n| Minified\u002Fwebpack bundle | Unique strings that survive bundling (URLs, magic values); **avoid function names** — they get mangled |\n\n**Good JS strings:** Ethereum function selectors — `{ a9 05 9c bb }` (`transfer(address,uint256)`), `{ 70 a0 82 31 }` (`balanceOf(address)`); zero-width characters for steganography — `{ E2 80 8B E2 80 8C }`; obfuscator signatures — `_0x`, `var _0x`; specific C2 domains and webhook URLs.\n\n**Bad JS strings:** `require`, `fetch`, `axios` (too common); `Buffer`, `crypto` (legitimate uses everywhere); `process.env` alone (need specific env var names).\n\n## String Selection\n\n**Value ranking:** mutex names are gold, C2 paths silver, error messages bronze. Stack strings are almost always unique. If you need more than 6 strings, you're over-fitting.\n\nReject a candidate string when any of these holds:\n\n| Test | Why it fails | Do instead |\n|---|---|---|\n| Under 4 bytes | No atom | Find a longer string |\n| Repeated bytes (`0000`, `9090`) | Weak atom | Add surrounding context |\n| API name (`VirtualAlloc`, `CreateRemoteThread`) | Every packer and installer calls it | Hex pattern of the call site plus a unique marker |\n| Appears in Windows system files | Guaranteed FPs | Find something family-specific |\n| Common path (`C:\\Windows\\`, `cmd.exe`) | Ubiquitous | Find malware-specific paths |\n| Appears in other malware families | Not identifying *this* family | Combine with a family-specific marker |\n\nEverything left — unique to this family — is what the rule should rest on.\n\n### Choosing a String Type\n\n| Need | Use |\n|---|---|\n| Exact ASCII\u002FUnicode text | `$s = \"MutexName\" ascii wide` |\n| Specific byte sequence | `$h = { 4D 5A 90 00 }` |\n| Byte sequence with variation | Hex wildcards: `{ 4D 5A ?? ?? 50 45 }` |\n| Pattern with structure (URLs, paths) | Bounded regex: `\u002Fhttps:\\\u002F\\\u002F[a-z]{5,20}\\.onion\u002F` |\n| Unknown encoding (XOR, base64) | Modifier: `$s = \"config\" xor(0x00-0xFF)` |\n\n**Modifier discipline:** never use `nocase` or `wide` speculatively — only with confirmed evidence that case or encoding varies across samples. `nocase` doubles atom generation; `wide` doubles string matching. \"If you don't have a clear reason for using those modifiers, don't do it\" — Kaspersky Applied YARA.\n\n## Condition Design\n\nOrder for short-circuit: `filesize \u003C`, magic bytes, strings, modules. If the condition runs past 5 lines, split into multiple rules.\n\n### all of vs any of\n\n| Situation | Use |\n|---|---|\n| Strings are individually unique to the malware | `any of them` — each alone is suspicious |\n| Strings are common but the combination is suspicious | `all of them` — require the full pattern |\n| Strings have different confidence levels | Group: `all of ($core_*) and any of ($variant_*)` |\n| Seeing false positives | Tighten: `any` → `all`, add more required strings |\n\n**Lesson from production:** rules using `any of ($network_*)` where the strings included `fetch`, `axios`, and `http` matched virtually all web applications. Switching to require a credential path AND a network call AND an exfil destination eliminated the FPs.\n\n### Grouping by Confidence\n\nDifferent indicator types carry different weight — a C2 domain might be definitive while library imports need corroboration. Grouping by prefix lets you express graduated requirements:\n\n```yara\nstrings:\n    $a1 = \"SRWebSocket\" ascii            \u002F\u002F Category A: library indicators\n    $a2 = \"SocketRocket\" ascii\n    $b1 = \"SSH tunnel\" ascii             \u002F\u002F Category B: behavioral\n    $b2 = \"keylogger\" ascii nocase\n    $c1 = \u002Fhttps:\\\u002F\\\u002F[a-z0-9]{8,16}\\.onion\u002F   \u002F\u002F Category C: C2\n\ncondition:\n    filesize \u003C 10MB and\n    any of ($a*) and any of ($b*)        \u002F\u002F Evidence from BOTH categories\n```\n\n### Modules vs Byte Checks\n\n| Need | Use |\n|---|---|\n| imphash, rich header, authenticode | PE module — too complex to replicate |\n| Magic bytes or simple offsets | `uint16`\u002F`uint32` — faster, no module overhead |\n| Section names\u002Fsizes | PE module, but put the magic-byte filter FIRST |\n| Chrome extension permissions | `crx` module — string parsing is fragile |\n| LNK target paths | `lnk` module — the format is complex |\n\n\"Avoid the magic module — use explicit hex checks instead\" — Neo23x0. Generalize it: if `uint32()` can do the job, don't load a module.\n\n### Performance\n\n- **Regex must be anchored to a 4+ byte literal.** Without one it evaluates at *every* file offset — catastrophic. Write `\u002Fmshta\\.exe http:\\\u002F\\\u002F...\u002F`, not `\u002Fhttp:\\\u002F\\\u002F...\u002F`. If you can't anchor, use a hex pattern with wildcards.\n- **Bound every regex quantifier** — `.{0,30}`, never `.*`. Unbounded regex is both a performance disaster and a memory explosion.\n- **Bound loops with filesize** — `filesize \u003C 100KB and for all i in (1..#a) : ...`. Unbounded `#a` can reach thousands in large files.\n- **Prefer hex over regex** where the bytes are fixed.\n\n## Before Writing: Is the Sample Packed?\n\n| Signal | What to do |\n|---|---|\n| Entropy > 7.0 | Likely packed — find the unpacked layer first |\n| Few or no readable strings | Likely packed — use entropy, PE structure, or packer signatures |\n| UPX\u002FMPRESS\u002Fcustom packer detected | Target the unpacked payload OR detect the packer itself |\n| Readable strings available | Proceed with string-based detection |\n\n**Don't write rules against packed layers.** The packing changes; the payload doesn't.\n\n### When Strings Fail, Pivot to Structure\n\nIf extraction returns only API names and generic paths:\n\n| Available signal | Use |\n|---|---|\n| High entropy sections | `math.entropy()` on specific sections |\n| Unusual import pattern | `pe.imphash()` for import-hash clustering |\n| PE structure anomalies | Section names, sizes, characteristics |\n| Metadata present | Version info, timestamps, resources |\n| Nothing unique | This sample may not be detectable with YARA alone |\n\n\"One can try to use other file properties, such as metadata, entropy, import hashes or other data which stays constant.\" — Kaspersky Applied YARA Training\n\n## Debugging False Positives\n\n1. **Which string matched?** — `yr scan -s rule.yar false_positive.exe`\n2. **In a legitimate library?** — add a `not $fp_vendor_string` exclusion\n3. **A common development pattern?** — replace the string with something more specific\n4. **Multiple generic strings matching together?** — tighten to require all, plus a unique marker\n5. **Malware using a common technique?** — target its specific implementation details, not the technique\n\n### When to Abandon the Approach\n\n- **Extraction returns only API names and paths** → [pivot to structure](#when-strings-fail-pivot-to-structure)\n- **Can't find 3 unique strings** → probably packed; target the unpacked version or detect the packer\n- **Rule matches goodware** → 1-2 matches: investigate and tighten; 3-5: find different indicators; 6+: start over\n- **Performance is terrible after optimization** → architecture problem; split into focused rules or add strict pre-filters\n- **The description is hard to write** → the rule is too vague. If you can't explain what it catches, it catches too much\n\n## Rationalizations to Reject\n\nWhen you catch yourself thinking these, stop and reconsider.\n\n| Rationalization | Expert Response |\n|-----------------|-----------------|\n| \"This generic string is unique enough\" \u002F \"This hex pattern is unique\" | Unique in one sample ≠ unique across the ecosystem. Test against goodware; your intuition is wrong. |\n| \"yarGen gave me these strings\" | yarGen suggests, you validate. Check each one manually — expect to discard 80%. |\n| \"It works on my 10 samples\" | 10 samples ≠ production. Use a goodware corpus. |\n| \"One rule to catch all variants\" | Causes FP floods. Target specific families. |\n| \"I'll make it more specific if we get FPs\" \u002F \"I'll add more conditions later\" | Write tight rules upfront. A weak rule deployed is damage done, and FPs burn trust. |\n| \"This is just for hunting\" | Hunting rules become detection rules. Same quality bar. |\n| \"The API name makes it malicious\" | Legitimate software uses the same APIs. Need behavioral context. |\n| \"`any of them` is fine for these common strings\" | Common strings + `any` = FP flood. Use `any of` only for individually unique strings. |\n| \"This regex is specific enough\" | `\u002Ffetch.*token\u002F` matches all auth code. Add an exfil destination requirement. |\n| \"I'll use `.*` for flexibility\" | Unbounded regex = performance disaster plus memory explosion. Use `.{0,30}`. |\n| \"The JavaScript looks clean\" | Attackers poison legitimate code with injects. Check for eval+decode chains. |\n| \"Performance doesn't matter\" | One slow rule slows the entire ruleset. Optimize atoms. |\n| \"I'll use `--relaxed-re-syntax` everywhere\" | Masks real bugs. Fix the regex instead of hiding the problem. |\n| \"PEiD rules still work\" | Obsolete. 32-bit packers aren't relevant. |\n\n## Toolkit\n\n| Tool | Purpose |\n|------|---------|\n| **yr CLI** | `yr check` (validate), `yr fmt` (format), `yr scan -s` (scan, show strings), `yr dump -m pe` (inspect structure) |\n| **yarGen** | Extract candidate strings: `yarGen.py -m samples\u002F --excludegood` |\n| **FLOSS** | Extract obfuscated\u002Fstack strings: `floss sample.exe` — when yarGen comes up empty |\n| **signature-base** | Study quality examples |\n| **YARA-CI** | Goodware corpus testing before deployment |\n\nMaster these five. Don't get distracted by tool catalogs.\n\n**Development cycle:**\n\n```bash\nyr check rule.yar                                   # syntax, with precise line numbers\nyr fmt -w rule.yar                                  # standardize formatting\nyr dump -m pe sample.exe --output-format yaml       # inspect structure, no dummy rule needed\ntime yr scan -s rule.yar corpus\u002F                    # scan with timing\n```\n\nReach for `yr dump` when investigating which module fields are available, debugging why a module condition isn't matching, or exploring a new module (crx, lnk, dotnet) before writing against it. YARA-X error messages carry precise source locations — if `yr check` says line 15, the problem is on line 15.\n\n**Version-gated features:** `private $helper = \"pattern\"` matches but stays out of output (v1.3.0+); `\u002F\u002F suppress: slow_pattern` silences a specific warning inline (v1.4.0+); `filesize \u003C 10_000_000` numeric underscores (v1.5.0+). `$_unused` also suppresses unused-string warnings.\n\n## Chrome Extension Analysis (crx module)\n\nRequires YARA-X v1.5.0+, or v1.11.0+ for `permhash()`.\n\n**Key APIs:** `crx.is_crx`, `crx.permissions`, `crx.permhash()`\n**Red flags:** `nativeMessaging` + `downloads`, `debugger` permission, content scripts on `\u003Call_urls>`\n\n```yara\nimport \"crx\"\n\nrule SUSP_CRX_HighRiskPerms {\n    condition:\n        crx.is_crx and\n        for any perm in crx.permissions : (perm == \"debugger\")\n}\n```\n\nSee [crx-module.md](references\u002Fcrx-module.md) for the full API, permission risk assessment, and example rules.\n\n## Android DEX Analysis (dex module)\n\nRequires YARA-X v1.11.0+. **Not compatible with legacy YARA's dex module** — the API is completely different.\n\n**Key APIs:** `dex.is_dex`, `dex.contains_class()`, `dex.contains_method()`, `dex.contains_string()`\n**Red flags:** single-letter class names (obfuscation), `DexClassLoader` reflection, encrypted assets\n\n```yara\nimport \"dex\"\n\nrule SUSP_DEX_DynamicLoading {\n    condition:\n        dex.is_dex and\n        dex.contains_class(\"Ldalvik\u002Fsystem\u002FDexClassLoader;\")\n}\n```\n\nSee [dex-module.md](references\u002Fdex-module.md) for the full API, obfuscation detection, and example rules.\n\n## Migrating from Legacy YARA\n\n99% rule compatibility, but stricter validation:\n\n```bash\nyr check --relaxed-re-syntax rules\u002F   # identify issues\n# fix each one, then verify without relaxed mode:\nyr check rules\u002F\n```\n\n| Issue | Legacy | YARA-X Fix |\n|-------|--------|------------|\n| Literal `{` in regex | `\u002F{\u002F` | `\u002F\\{\u002F` |\n| Invalid escapes | `\\R` silently literal | `\\\\R` or `R` |\n| Base64 strings | Any length | 3+ chars required |\n| Negative indexing | `@a[-1]` | `@a[#a - 1]` |\n| Duplicate modifiers | Allowed | Remove duplicates |\n\n`--relaxed-re-syntax` is a diagnostic, not a destination. Fix the regex.\n\n## Naming and Metadata\n\n```\n{CATEGORY}_{PLATFORM}_{FAMILY}_{VARIANT}_{DATE}      e.g. MAL_Win_Emotet_Loader_Jan25\n```\n\n**Categories:** `MAL_` (malware), `HKTL_` (hacking tool), `WEBSHELL_`, `EXPL_`, `SUSP_` (suspicious), `GEN_` (generic). **Platforms:** `Win_`, `Lnx_`, `Mac_`, `Android_`, `CRX_`.\n\nEvery rule needs `description` (starting with \"Detects\"), `author`, `reference`, and `date`:\n\n```yara\nmeta:\n    description = \"Detects Example malware via unique mutex and C2 path\"\n    author = \"Your Name \u003Cemail@example.com>\"\n    reference = \"https:\u002F\u002Fexample.com\u002Fanalysis\"\n    date = \"2025-01-29\"\n```\n\nSee [style-guide.md](references\u002Fstyle-guide.md) for full conventions.\n\n## Workflow\n\n1. **Gather samples** — multiple; single-sample rules are brittle\n2. **Extract candidates** — `yarGen -m samples\u002F --excludegood`\n3. **Validate quality** — apply the [string selection](#string-selection) tests; expect to discard 80% of yarGen output\n4. **Write the rule** — proper metadata, cheap checks first\n5. **Lint and test** — `yr check`, `yr fmt`, the linter script\n6. **Goodware validation** — VirusTotal corpus or local clean files\n7. **Deploy** — full metadata, then monitor for FPs\n\nQuality signals along the way: a rule matching under 50% of known variants is too narrow; one matching goodware is too broad.\n\n**Reviewing a rule someone else wrote** — run both scripts before reading the rule by eye, and quote the codes they emit:\n\n```bash\nuv run {baseDir}\u002Fscripts\u002Fyara_lint.py suspect.yar      # style, metadata, YARA-X compatibility\nuv run {baseDir}\u002Fscripts\u002Fatom_analyzer.py suspect.yar  # atom quality per string\n```\n\nThey catch the mechanical faults — short strings, FP-prone substrings, unbounded quantifiers, expensive terms ahead of cheap ones — so your attention goes to the judgement calls they cannot make: whether the strings identify *this* family, and whether the condition can fire on generic strings alone. Report findings by code (`E002`, `W009`) so the author can look each one up in [style-guide.md](references\u002Fstyle-guide.md).\n\nSee [testing.md](references\u002Ftesting.md) for the validation workflow and [rule-development.md](workflows\u002Frule-development.md) for the full step-by-step guide.\n\n## Common Mistakes\n\n| Mistake | Bad | Good |\n|---------|-----|------|\n| API names as indicators | `\"VirtualAlloc\"` | Hex pattern of call site + unique mutex |\n| Unbounded regex | `\u002Fhttps?:\\\u002F\\\u002F.*\u002F` | `\u002Fhttps?:\\\u002F\\\u002F[a-z0-9]{8,12}\\.onion\u002F` |\n| Missing file type filter | `pe.imports(...)` first | `uint16(0) == 0x5A4D and filesize \u003C 10MB` first |\n| Short strings | `\"abc\"` (3 bytes) | `\"abcdef\"` (4+ bytes) |\n| Unescaped braces (YARA-X) | `\u002Fconfig{key}\u002F` | `\u002Fconfig\\{key\\}\u002F` |\n| Wrong-endian magic bytes | `uint32(0) == 0xCAFEBABE` | `uint32be(0) == 0xCAFEBABE` |\n\n## Quality Checklist\n\nBefore deploying any rule:\n\n- [ ] Name follows `{CATEGORY}_{PLATFORM}_{FAMILY}_{VARIANT}_{DATE}`\n- [ ] Description starts with \"Detects\" and explains what\u002Fhow\n- [ ] All required metadata present (author, reference, date)\n- [ ] Strings are unique — not API names, common paths, or format strings\n- [ ] All strings 4+ bytes with good atom potential\n- [ ] Base64 modifier only on strings with 3+ characters\n- [ ] Regex bounded, anchored to a literal, with `{` escaped\n- [ ] Condition starts with cheap checks (filesize, magic bytes)\n- [ ] Magic-byte constants verified against a known-good sample\n- [ ] Rule matches all target samples\n- [ ] Rule produces zero matches on the goodware corpus\n- [ ] `yr check` and `yr fmt --check` pass\n- [ ] Linter passes with no errors\n- [ ] Peer review completed\n\n## Scripts\n\n```bash\nuv run {baseDir}\u002Fscripts\u002Fyara_lint.py rule.yar      # validate style\u002Fmetadata\nuv run {baseDir}\u002Fscripts\u002Fatom_analyzer.py rule.yar  # check string quality\n```\n\nSee [README.md](..\u002F..\u002FREADME.md#scripts) for detailed script documentation.\n\n## Further Reading\n\n| Topic | Document |\n|-------|----------|\n| Naming and metadata conventions | [style-guide.md](references\u002Fstyle-guide.md) |\n| Performance and atom optimization | [performance.md](references\u002Fperformance.md) |\n| String types and judgment | [strings.md](references\u002Fstrings.md) |\n| Testing and validation | [testing.md](references\u002Ftesting.md) |\n| Chrome extension module (crx) | [crx-module.md](references\u002Fcrx-module.md) |\n| Android DEX module (dex) | [dex-module.md](references\u002Fdex-module.md) |\n| Complete rule development process | [rule-development.md](workflows\u002Frule-development.md) |\n\nThe `examples\u002F` directory holds real, attributed rules worth reading before writing your own:\n\n| Example | Demonstrates | Source |\n|---------|--------------|--------|\n| [MAL_Win_Remcos_Jan25.yar](examples\u002FMAL_Win_Remcos_Jan25.yar) | PE malware: graduated string counts, multiple rules per family | Elastic Security |\n| [MAL_Mac_ProtonRAT_Jan25.yar](examples\u002FMAL_Mac_ProtonRAT_Jan25.yar) | macOS: Mach-O magic bytes, multi-category grouping | Airbnb BinaryAlert |\n| [MAL_NPM_SupplyChain_Jan25.yar](examples\u002FMAL_NPM_SupplyChain_Jan25.yar) | npm supply chain: real attack patterns, ERC-20 selectors | Stairwell Research |\n| [SUSP_JS_Obfuscation_Jan25.yar](examples\u002FSUSP_JS_Obfuscation_Jan25.yar) | JavaScript: obfuscator detection, density-based matching | imp0rtp3, Nils Kuhnert |\n| [SUSP_CRX_SuspiciousPermissions.yar](examples\u002FSUSP_CRX_SuspiciousPermissions.yar) | Chrome extensions: crx module, permissions | Educational |\n\n**Rule repositories to learn from:** [Neo23x0\u002Fsignature-base](https:\u002F\u002Fgithub.com\u002FNeo23x0\u002Fsignature-base) (17,000+ production rules), [elastic\u002Fprotections-artifacts](https:\u002F\u002Fgithub.com\u002Felastic\u002Fprotections-artifacts) (endpoint-tested), [imp0rtp3\u002Fjs-yara-rules](https:\u002F\u002Fgithub.com\u002Fimp0rtp3\u002Fjs-yara-rules) (JavaScript), [InQuest\u002Fawesome-yara](https:\u002F\u002Fgithub.com\u002FInQuest\u002Fawesome-yara) (curated index).\n\n**Guides:** [YARA Style Guide](https:\u002F\u002Fgithub.com\u002FNeo23x0\u002FYARA-Style-Guide) and [YARA Performance Guidelines](https:\u002F\u002Fgithub.com\u002FNeo23x0\u002FYARA-Performance-Guidelines) (Neo23x0), [YARA-X documentation](https:\u002F\u002Fvirustotal.github.io\u002Fyara-x\u002F).\n\n**macOS specifics:** Apple's own production rules ship at `\u002FSystem\u002FLibrary\u002FCoreServices\u002FXProtect.bundle\u002F`; [objective-see](https:\u002F\u002Fobjective-see.org\u002F) publishes macOS malware research and samples.\n",{"name":5,"description":7},"main","d69096e239f2a89aabc2cd078c47664a9d3b1e11","04-安全渗透\u002Fyara-rule-authoring",3,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts","https:\u002F\u002Fgithub.com\u002Flza6","个人vx：Tf00798\r\n个人✈：@TFGY999","2026-10-08 14:29:22",{"source":8,"skillName":5,"commands":33,"prompt":43,"zipAvailable":44},[34,37,40],{"tool":35,"command":36},"npx","npx skills add lza6\u002FArmor-piercing-system-prompts --skill yara-rule-authoring",{"tool":38,"command":39},"bunx","bunx skills add lza6\u002FArmor-piercing-system-prompts --skill yara-rule-authoring",{"tool":41,"command":42},"pnpm","pnpm dlx skills add lza6\u002FArmor-piercing-system-prompts --skill yara-rule-authoring","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F04-安全渗透\u002Fyara-rule-authoring\u002FSKILL.md",true,[46,52,56,60,64,68,72,76,82],{"path":47,"resourceType":48,"resourceTypeDesc":49,"sizeBytes":50,"sourceHtmlUrl":51},"agents\u002Fopenai.yaml","REFERENCE","参考文档",236,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F04-安全渗透\u002Fyara-rule-authoring\u002Fagents\u002Fopenai.yaml",{"path":53,"resourceType":48,"resourceTypeDesc":49,"sizeBytes":54,"sourceHtmlUrl":55},"references\u002Fcrx-module.md",7500,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F04-安全渗透\u002Fyara-rule-authoring\u002Freferences\u002Fcrx-module.md",{"path":57,"resourceType":48,"resourceTypeDesc":49,"sizeBytes":58,"sourceHtmlUrl":59},"references\u002Fdex-module.md",10384,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F04-安全渗透\u002Fyara-rule-authoring\u002Freferences\u002Fdex-module.md",{"path":61,"resourceType":48,"resourceTypeDesc":49,"sizeBytes":62,"sourceHtmlUrl":63},"references\u002Fperformance.md",8733,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F04-安全渗透\u002Fyara-rule-authoring\u002Freferences\u002Fperformance.md",{"path":65,"resourceType":48,"resourceTypeDesc":49,"sizeBytes":66,"sourceHtmlUrl":67},"references\u002Fstrings.md",11868,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F04-安全渗透\u002Fyara-rule-authoring\u002Freferences\u002Fstrings.md",{"path":69,"resourceType":48,"resourceTypeDesc":49,"sizeBytes":70,"sourceHtmlUrl":71},"references\u002Fstyle-guide.md",9484,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F04-安全渗透\u002Fyara-rule-authoring\u002Freferences\u002Fstyle-guide.md",{"path":73,"resourceType":48,"resourceTypeDesc":49,"sizeBytes":74,"sourceHtmlUrl":75},"references\u002Ftesting.md",13376,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F04-安全渗透\u002Fyara-rule-authoring\u002Freferences\u002Ftesting.md",{"path":77,"resourceType":78,"resourceTypeDesc":79,"sizeBytes":80,"sourceHtmlUrl":81},"scripts\u002Fpyproject.toml","SCRIPT","脚本",553,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F04-安全渗透\u002Fyara-rule-authoring\u002Fscripts\u002Fpyproject.toml",{"path":83,"resourceType":48,"resourceTypeDesc":49,"sizeBytes":84,"sourceHtmlUrl":85},"workflows\u002Frule-development.md",13403,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F04-安全渗透\u002Fyara-rule-authoring\u002Fworkflows\u002Frule-development.md",[87,95,100,107,114,121],{"skillNo":88,"name":89,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":91,"categories":92,"keywords":93,"publishedAt":94},"01M7FFG485KY83TD6HSC4YPCMC","obsidian-clipper-template-creator","Guide for creating templates for the Obsidian Web Clipper. Use when you want to create a new clipping template, understand available variables, or format clipped content.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobsidian-clipper-template-creator\u002FSKILL.md",[],[],"2026-11-16 10:05:34",{"skillNo":96,"name":89,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":97,"categories":98,"keywords":99,"publishedAt":94},"01M7FFG0T6AZ0STEJPSB3CX84K","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobsidian-clipper-template-creator-antigravity-awesome-skills-main\u002FSKILL.md",[],[],{"skillNo":101,"name":102,"nameZh":6,"description":103,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":104,"categories":105,"keywords":106,"publishedAt":94},"01M7FFFY0QEM14SKWPDYGMXM2P","python-api","Programmatic Object-Detection-Metrics API guidance for BoundingBox, BoundingBoxes, Evaluator, enums, coordinate conversion, AP\u002FmAP semantics, and source-style import diagnostics.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002Fsub-skills\u002Fpython-api\u002FSKILL.md",[],[],{"skillNo":108,"name":109,"nameZh":6,"description":110,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":111,"categories":112,"keywords":113,"publishedAt":94},"01M7FFFVZQZ2GJ0C0TGP7JHD20","file-evaluation","Folder-based PASCAL VOC AP\u002FmAP evaluation from ground-truth and detection text files.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002Fsub-skills\u002Ffile-evaluation\u002FSKILL.md",[],[],{"skillNo":115,"name":116,"nameZh":6,"description":117,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":118,"categories":119,"keywords":120,"publishedAt":94},"01M7FFFSFNYSE77SJ6PE1CK2DA","object-detection-metrics","Guides legacy Object-Detection-Metrics PASCAL VOC AP\u002FmAP evaluation from detection text folders and direct Python API classes.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002FSKILL.md",[],[],{"skillNo":122,"name":123,"nameZh":6,"description":124,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":125,"categories":126,"keywords":127,"publishedAt":94},"01M7FFFP0GCK1RVXBCPQ8APBMT","nx-workspace-patterns","Configure and optimize Nx monorepo workspaces. Use when setting up Nx, configuring project boundaries, optimizing build caching, or implementing affected commands.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fnx-workspace-patterns\u002FSKILL.md",[],[]]