Generated banner for Yara Rule Authoring
Generated logo for Yara Rule Authoring

Yara Rule Authoring

Trail of BitsOfficialPublished by Trail of Bits

  • Skill
  • Guidelines
  • Security
  • CC-BY-SA-4.0
  • Medium risk
  • Has scripts

From the author

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.
— the description by Trail of Bits

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a framework for creating and maintaining YARA-X detection rules. It covers best practices for string selection, condition design, and metadata, while offering specific guidance for analyzing Windows, macOS, JavaScript, Chrome extensions, and Android DEX files. The skill includes instructions for using provided scripts to lint rules, analyze string atoms, and perform comprehensive reviews to ensure rules meet established authoring standards.

What it does

  • Provides conventions for naming, metadata, and rule structure.
  • Offers techniques for string selection and false positive reduction.
  • Details how to use YARA-X modules for CRX and DEX file analysis.
  • Includes scripts for linting, atom analysis, and rule validation.
  • Explains how to migrate legacy YARA rules to the YARA-X format.
  • Outlines methods for testing rules against goodware corpora.

When to use it

  • When writing new YARA-X rules for malware detection.
  • When reviewing or optimizing existing YARA-X rulesets.
  • When converting threat intelligence or IOCs into detection signatures.
  • When debugging false positives in existing detection rules.
  • When analyzing Chrome extensions or Android applications for malicious patterns.

Advantages

  • Standardizes rule quality through linting and atom analysis.
  • Reduces false positives by enforcing specific string and condition requirements.
  • Provides clear guidance on YARA-X module usage for complex file formats.
  • Facilitates consistent rule maintenance and peer review.

Usage examples

“How do I check my YARA-X rule for syntax errors and formatting?”
The agent will instruct you to use 'yr check rule.yar' for syntax validation and 'yr fmt -w rule.yar' to standardize the rule's formatting.
“What is the best way to review a YARA-X rule for performance and style?”
The agent will guide you to use the provided review script, which runs linting and atom analysis to identify issues like short strings or unbounded regex.
“How can I detect malicious Chrome extensions using YARA-X?”
The agent will explain how to import the 'crx' module and use fields like 'crx.permissions' to flag high-risk extension behaviors.
“How do I migrate a legacy YARA rule to YARA-X?”
The agent will provide steps to use 'yr check --relaxed-re-syntax' to identify compatibility issues and explain how to fix them manually.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/trailofbits/yara-rule-authoring/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip yara-rule-authoring.zip -d .agents/skills

Documentation by Trail of Bits

YARA-X Rule Authoring

Write detection rules that catch malware without drowning in false positives.

Resolve the linter, atom analyzer, and review helper from this installed SKILL.md's directory. In commands below, replace each <resolved-...-path> with that script's absolute path and keep the quotes. The rule file or directory is still relative to your working directory unless you pass an absolute input path.

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 for existing rules.

Core Principles

  1. 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.

  2. Target specific families, not categories — "Detects ransomware" catches everything and nothing. "Detects LockBit 3.0 configuration extraction routine" catches what you want.

  3. 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.

  4. Short-circuit with cheap checks first — filesize (instant), then magic bytes (nearly instant), then strings (cheap), then modules (expensive).

  5. Metadata is documentation — Future you (and your team) need to know what this catches, why, and where the sample came from.

When to Use

  • Writing new YARA-X rules for malware detection

  • Reviewing existing rules for quality or performance issues

  • Optimizing slow-running rulesets

  • Converting IOCs or threat intel into detection signatures

  • Debugging false positive issues

  • Preparing rules for production deployment

  • Migrating legacy YARA rules to YARA-X

  • Analyzing Chrome extensions (crx module) or Android apps (dex module)

When NOT to Use

  • Static analysis requiring disassembly → use Ghidra/IDA skills

  • Dynamic malware analysis → use sandbox analysis skills

  • Network-based detection → use Suricata/Snort skills

  • Memory forensics with Volatility → use memory forensics skills

  • Simple hash-based detection → just use hash lists

Platform Considerations

YARA works on any file type. Adapt patterns to your target:

PlatformMagic BytesBad StringsGood Strings
Windows PEuint16(0) == 0x5A4DAPI names, Windows pathsMutex names, PDB paths
macOS Mach-Ouint32(0) == 0xFEEDFACE (32-bit), 0xFEEDFACF (64-bit), uint32be(0) == 0xCAFEBABE (universal)Common Obj-C methodsKeylogger strings, persistence paths
JavaScript/Node(none needed)require, fetch, axiosObfuscator signatures, eval+decode chains
npm/pip packages(none needed)postinstall, dependenciesSuspicious package names, exfil URLs
Office docsuint32(0) == 0x04034B50VBA keywordsMacro auto-exec, encoded payloads
VS Code extensions(none needed)vscode.workspaceUncommon activationEvents, hidden file access
Chrome extensionsUse crx moduleCommon Chrome APIsPermission abuse, manifest anomalies
Android appsUse dex moduleStandard DEX structureObfuscated classes, suspicious permissions

uintNN() reads little-endian. Write the constant as the bytes reversed, or use uintNNbe() and write them in file order. A ZIP/OOXML 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.

macOS Malware Detection

No dedicated Mach-O module exists yet — use magic bytes plus string patterns. Good indicators:

  • Keylogger artifacts: CGEventTapCreate, kCGEventKeyDown

  • SSH tunnel strings: ssh -D, tunnel, socks

  • Persistence paths: ~/Library/LaunchAgents, /Library/LaunchDaemons

  • Credential theft: security find-generic-password, keychain

// Pattern from Airbnb BinaryAlert
rule SUSP_Mac_ProtonRAT
{
    strings:
        $lib1 = "SRWebSocket" ascii          // Library indicators
        $lib2 = "SocketRocket" ascii
        $behav1 = "SSH tunnel not launched" ascii   // Behavioral indicators
        $behav2 = "Keylogger" ascii
    condition:
        (uint32(0) == 0xFEEDFACF or uint32be(0) == 0xCAFEBABE) and
        any of ($lib*) and any of ($behav*)
}
JavaScript Detection
TargetApproach
npm packagepackage.json patterns, postinstall/preinstall hooks, exfil combination: fetch + env access + credential paths
Chrome extensioncrx module
Other extensionManifest patterns, background script behaviors
Standalone JSObfuscation markers (eval+atob, fromCharCode chains), unique function/variable names, packed payloads
Minified/webpack bundleUnique strings that survive bundling (URLs, magic values); avoid function names — they get mangled

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.

Bad JS strings: require, fetch, axios (too common); Buffer, crypto (legitimate uses everywhere); process.env alone (need specific env var names).

String Selection

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.

Reject a candidate string when any of these holds:

TestWhy it failsDo instead
Under 4 bytesNo atomFind a longer string
Repeated bytes (0000, 9090)Weak atomAdd surrounding context
API name (VirtualAlloc, CreateRemoteThread)Every packer and installer calls itHex pattern of the call site plus a unique marker
Appears in Windows system filesGuaranteed FPsFind something family-specific
Common path (C:\Windows\, cmd.exe)UbiquitousFind malware-specific paths
Appears in other malware familiesNot identifying this familyCombine with a family-specific marker

Everything left — unique to this family — is what the rule should rest on.

Choosing a String Type
NeedUse
Exact ASCII/Unicode text$s = "MutexName" ascii wide
Specific byte sequence$h = { 4D 5A 90 00 }
Byte sequence with variationHex wildcards: { 4D 5A ?? ?? 50 45 }
Pattern with structure (URLs, paths)Bounded regex: /https:\/\/[a-z]{5,20}\.onion/
Unknown encoding (XOR, base64)Modifier: $s = "config" xor(0x00-0xFF)

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.

Condition Design

Order for short-circuit: filesize <, magic bytes, strings, modules. If the condition runs past 5 lines, split into multiple rules.

all of vs any of
SituationUse
Strings are individually unique to the malwareany of them — each alone is suspicious
Strings are common but the combination is suspiciousall of them — require the full pattern
Strings have different confidence levelsGroup: all of ($core_*) and any of ($variant_*)
Seeing false positivesTighten: any → all, add more required strings

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.

Grouping by Confidence

Different indicator types carry different weight — a C2 domain might be definitive while library imports need corroboration. Grouping by prefix lets you express graduated requirements:

strings:
    $a1 = "SRWebSocket" ascii            // Category A: library indicators
    $a2 = "SocketRocket" ascii
    $b1 = "SSH tunnel" ascii             // Category B: behavioral
    $b2 = "keylogger" ascii nocase
    $c1 = /https:\/\/[a-z0-9]{8,16}\.onion/   // Category C: C2

condition:
    filesize < 10MB and
    any of ($a*) and any of ($b*)        // Evidence from BOTH categories
Modules vs Byte Checks
NeedUse
imphash, rich header, authenticodePE module — too complex to replicate
Magic bytes or simple offsetsuint16/uint32 — faster, no module overhead
Section names/sizesPE module, but put the magic-byte filter FIRST
Chrome extension permissionscrx module — string parsing is fragile
LNK target pathslnk module — the format is complex

"Avoid the magic module — use explicit hex checks instead" — Neo23x0. Generalize it: if uint32() can do the job, don't load a module.

Performance
  • Regex must be anchored to a 4+ byte literal. Without one it evaluates at every file offset — catastrophic. Write /mshta\.exe http:\/\/.../, not /http:\/\/.../. If you can't anchor, use a hex pattern with wildcards.

  • Bound every regex quantifier — .{0,30}, never .*. Unbounded regex is both a performance disaster and a memory explosion.

  • Bound loops with filesize — filesize < 100KB and for all i in (1..#a) : .... Unbounded #a can reach thousands in large files.

  • Prefer hex over regex where the bytes are fixed.

Before Writing: Is the Sample Packed?

SignalWhat to do
Entropy > 7.0Likely packed — find the unpacked layer first
Few or no readable stringsLikely packed — use entropy, PE structure, or packer signatures
UPX/MPRESS/custom packer detectedTarget the unpacked payload OR detect the packer itself
Readable strings availableProceed with string-based detection

Don't write rules against packed layers. The packing changes; the payload doesn't.

When Strings Fail, Pivot to Structure

If extraction returns only API names and generic paths:

Available signalUse
High entropy sectionsmath.entropy() on specific sections
Unusual import patternpe.imphash() for import-hash clustering
PE structure anomaliesSection names, sizes, characteristics
Metadata presentVersion info, timestamps, resources
Nothing uniqueThis sample may not be detectable with YARA alone

"One can try to use other file properties, such as metadata, entropy, import hashes or other data which stays constant." — Kaspersky Applied YARA Training

Debugging False Positives

  1. Which string matched? — yr scan -s rule.yar false_positive.exe

  2. In a legitimate library? — add a not $fp_vendor_string exclusion

  3. A common development pattern? — replace the string with something more specific

  4. Multiple generic strings matching together? — tighten to require all, plus a unique marker

  5. Malware using a common technique? — target its specific implementation details, not the technique

When to Abandon the Approach
  • Extraction returns only API names and paths → pivot to structure

  • Can't find 3 unique strings → probably packed; target the unpacked version or detect the packer

  • Rule matches goodware → 1-2 matches: investigate and tighten; 3-5: find different indicators; 6+: start over

  • Performance is terrible after optimization → architecture problem; split into focused rules or add strict pre-filters

  • The description is hard to write → the rule is too vague. If you can't explain what it catches, it catches too much

Rationalizations to Reject

When you catch yourself thinking these, stop and reconsider.

RationalizationExpert Response
"This generic string is unique enough" / "This hex pattern is unique"Unique in one sample ≠ unique across the ecosystem. Test against goodware; your intuition is wrong.
"yarGen gave me these strings"yarGen suggests, you validate. Check each one manually — expect to discard 80%.
"It works on my 10 samples"10 samples ≠ production. Use a goodware corpus.
"One rule to catch all variants"Causes FP floods. Target specific families.
"I'll make it more specific if we get FPs" / "I'll add more conditions later"Write tight rules upfront. A weak rule deployed is damage done, and FPs burn trust.
"This is just for hunting"Hunting rules become detection rules. Same quality bar.
"The API name makes it malicious"Legitimate software uses the same APIs. Need behavioral context.
"any of them is fine for these common strings"Common strings + any = FP flood. Use any of only for individually unique strings.
"This regex is specific enough"/fetch.*token/ matches all auth code. Add an exfil destination requirement.
"I'll use .* for flexibility"Unbounded regex = performance disaster plus memory explosion. Use .{0,30}.
"The JavaScript looks clean"Attackers poison legitimate code with injects. Check for eval+decode chains.
"Performance doesn't matter"One slow rule slows the entire ruleset. Optimize atoms.
"I'll use --relaxed-re-syntax everywhere"Masks real bugs. Fix the regex instead of hiding the problem.
"PEiD rules still work"Obsolete. 32-bit packers aren't relevant.

Toolkit

ToolPurpose
yr CLIyr check (validate), yr fmt (format), yr scan -s (scan, show strings), yr dump -m pe (inspect structure)
yarGenExtract candidate strings: yarGen.py -m samples/ --excludegood
FLOSSExtract obfuscated/stack strings: floss sample.exe — when yarGen comes up empty
signature-baseStudy quality examples
YARA-CIGoodware corpus testing before deployment

Master these five. Don't get distracted by tool catalogs.

Development cycle:

yr check rule.yar                                   # syntax, with precise line numbers
yr fmt -w rule.yar                                  # standardize formatting
yr dump -m pe sample.exe --output-format yaml       # inspect structure, no dummy rule needed
time yr scan -s rule.yar corpus/                    # scan with timing

Reach 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.

Version-gated features: private $helper = "pattern" matches but stays out of output (v1.3.0+); // suppress: slow_pattern silences a specific warning inline (v1.4.0+); filesize < 10_000_000 numeric underscores (v1.5.0+). $_unused also suppresses unused-string warnings.

Chrome Extension Analysis (crx module)

Requires YARA-X v1.5.0+, or v1.11.0+ for permhash().

Key APIs: crx.is_crx, crx.permissions, crx.permhash() Red flags: nativeMessaging + downloads, debugger permission, content scripts on <all_urls>

import "crx"

rule SUSP_CRX_HighRiskPerms {
    condition:
        crx.is_crx and
        for any perm in crx.permissions : (perm == "debugger")
}

See crx-module.md for the full API, permission risk assessment, and example rules.

Android DEX Analysis (dex module)

Requires YARA-X v1.11.0+. Not compatible with legacy YARA's dex module — the API is completely different.

Key APIs: dex.is_dex, dex.contains_class(), dex.contains_method(), dex.contains_string() Red flags: single-letter class names (obfuscation), DexClassLoader reflection, encrypted assets

import "dex"

rule SUSP_DEX_DynamicLoading {
    condition:
        dex.is_dex and
        dex.contains_class("Ldalvik/system/DexClassLoader;")
}

See dex-module.md for the full API, obfuscation detection, and example rules.

Migrating from Legacy YARA

99% rule compatibility, but stricter validation:

yr check --relaxed-re-syntax rules/   # identify issues
# fix each one, then verify without relaxed mode:
yr check rules/
IssueLegacyYARA-X Fix
Literal { in regex/{//\{/
Invalid escapes\R silently literal\\R or R
Base64 stringsAny length3+ chars required
Negative indexing@a[-1]@a[#a - 1]
Duplicate modifiersAllowedRemove duplicates

--relaxed-re-syntax is a diagnostic, not a destination. Fix the regex.

Naming and Metadata

{CATEGORY}_{PLATFORM}_{FAMILY}_{VARIANT}_{DATE}      e.g. MAL_Win_Emotet_Loader_Jan25

Categories: MAL_ (malware), HKTL_ (hacking tool), WEBSHELL_, EXPL_, SUSP_ (suspicious), GEN_ (generic). Platforms: Win_, Lnx_, Mac_, Android_, CRX_.

Every rule needs description (starting with "Detects"), author, reference, and date:

meta:
    description = "Detects Example malware via unique mutex and C2 path"
    author = "Your Name <[email protected]>"
    reference = "https://example.com/analysis"
    date = "2025-01-29"

See style-guide.md for full conventions.

Workflow

  1. Gather samples — multiple; single-sample rules are brittle

  2. Extract candidates — yarGen -m samples/ --excludegood

  3. Validate quality — apply the string selection tests; expect to discard 80% of yarGen output

  4. Write the rule — proper metadata, cheap checks first

  5. Lint and test — yr check, yr fmt, the linter script

  6. Goodware validation — VirusTotal corpus or local clean files

  7. Deploy — full metadata, then monitor for FPs

Quality signals along the way: a rule matching under 50% of known variants is too narrow; one matching goodware is too broad.

Reviewing a rule someone else wrote — run both scripts before reading the rule by eye, and quote the codes they emit:

uv run "<resolved-yara-lint-path>" suspect.yar      # style, metadata, YARA-X compatibility
uv run "<resolved-atom-analyzer-path>" suspect.yar  # atom quality per string

Shortcut: "<resolved-review-path>" suspect.yar (a rule file or a directory) runs yr check, yr fmt --check, the linter and the atom analyzer in one call and prints one JSON object, {"target": ..., "checks": {"yr_check", "yr_format", "lint", "atoms"}}, each with status (the tool's exit code) and its output. It exits 0 when every check passes, 1 when any check fails, and 2 for a missing, empty or unreadable input (nothing was inspected). Quote the codes from checks.lint.output exactly as with the separate scripts.

They 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.

See testing.md for the validation workflow and rule-development.md for the full step-by-step guide.

Common Mistakes

MistakeBadGood
API names as indicators"VirtualAlloc"Hex pattern of call site + unique mutex
Unbounded regex/https?:\/\/.*//https?:\/\/[a-z0-9]{8,12}\.onion/
Missing file type filterpe.imports(...) firstuint16(0) == 0x5A4D and filesize < 10MB first
Short strings"abc" (3 bytes)"abcdef" (4+ bytes)
Unescaped braces (YARA-X)/config{key}//config\{key\}/
Wrong-endian magic bytesuint32(0) == 0xCAFEBABEuint32be(0) == 0xCAFEBABE

Quality Checklist

Before deploying any rule:

  • [ ] Name follows {CATEGORY}_{PLATFORM}_{FAMILY}_{VARIANT}_{DATE}

  • [ ] Description starts with "Detects" and explains what/how

  • [ ] All required metadata present (author, reference, date)

  • [ ] Strings are unique — not API names, common paths, or format strings

  • [ ] All strings 4+ bytes with good atom potential

  • [ ] Base64 modifier only on strings with 3+ characters

  • [ ] Regex bounded, anchored to a literal, with { escaped

  • [ ] Condition starts with cheap checks (filesize, magic bytes)

  • [ ] Magic-byte constants verified against a known-good sample

  • [ ] Rule matches all target samples

  • [ ] Rule produces zero matches on the goodware corpus

  • [ ] yr check and yr fmt --check pass

  • [ ] Linter passes with no errors

  • [ ] Peer review completed

Scripts

uv run "<resolved-yara-lint-path>" rule.yar      # validate style/metadata
uv run "<resolved-atom-analyzer-path>" rule.yar  # check string quality
"<resolved-review-path>" rule.yar                # all four checks, one JSON result

See README.md for detailed script documentation.

Further Reading

TopicDocument
Naming and metadata conventionsstyle-guide.md
Performance and atom optimizationperformance.md
String types and judgmentstrings.md
Testing and validationtesting.md
Chrome extension module (crx)crx-module.md
Android DEX module (dex)dex-module.md
Complete rule development processrule-development.md

The examples/ directory holds real, attributed rules worth reading before writing your own:

ExampleDemonstratesSource
MAL_Win_Remcos_Jan25.yarPE malware: graduated string counts, multiple rules per familyElastic Security
MAL_Mac_ProtonRAT_Jan25.yarmacOS: Mach-O magic bytes, multi-category groupingAirbnb BinaryAlert
MAL_NPM_SupplyChain_Jan25.yarnpm supply chain: real attack patterns, ERC-20 selectorsStairwell Research
SUSP_JS_Obfuscation_Jan25.yarJavaScript: obfuscator detection, density-based matchingimp0rtp3, Nils Kuhnert
SUSP_CRX_SuspiciousPermissions.yarChrome extensions: crx module, permissionsEducational

Rule repositories to learn from: Neo23x0/signature-base (17,000+ production rules), elastic/protections-artifacts (endpoint-tested), imp0rtp3/js-yara-rules (JavaScript), InQuest/awesome-yara (curated index).

Guides: YARA Style Guide and YARA Performance Guidelines (Neo23x0), YARA-X documentation.

macOS specifics: Apple's own production rules ship at /System/Library/CoreServices/XProtect.bundle/; objective-see publishes macOS malware research and samples.

Files

references/style-guide.md

YARA Naming and Metadata

Consistent naming for maintainable rule sets.

Naming Convention

{CATEGORY}_{PLATFORM}_{FAMILY}_{VARIANT}_{DATE}
ComponentDescriptionExamples
CATEGORYThreat classificationMAL, HKTL, WEBSHELL, EXPL, SUSP
PLATFORMTarget OS/environmentWin, Lnx, Mac, Android, Multi
FAMILYMalware family nameEmotet, CobaltStrike, LockBit
VARIANTSpecific variant/componentLoader, Beacon, Config
DATECreation date (MonthYear format)Jan25, May23
Category Prefixes
PrefixMeaningUse When
MAL_Confirmed malwareVerified malicious code
HKTL_Hacking toolDual-use tools (Mimikatz, Cobalt Strike)
WEBSHELL_Web shellPHP/ASP/JSP backdoors
EXPL_ExploitExploit code or shellcode
VULN_VulnerableVulnerable software patterns
SUSP_SuspiciousLower confidence, may FP
PUA_Potentially unwantedAdware, bundleware
GEN_GenericBroad detection category
Additional Classifiers

Append when relevant:

ClassifierMeaning
APT_APT-associated
CRIME_Cybercrime operation
RANSOM_Ransomware
RAT_Remote access trojan
MINER_Cryptominer
STEALER_Information stealer
LOADER_Loader/dropper
C2_Command and control
Platform Indicators
IndicatorPlatform
Win_Windows
Lnx_Linux
Mac_macOS
Android_Android
iOS_iOS
Multi_Cross-platform
PE_PE file format
ELF_ELF file format
PS_PowerShell
DOC_Office documents
PDF_PDF files
JAR_Java archives
Examples
// Good names (all include date suffix)
MAL_Win_Emotet_Loader_Jan25
HKTL_Win_CobaltStrike_Beacon_Jan25
WEBSHELL_PHP_Generic_Eval_Jan25
APT_Win_Lazarus_AppleJeus_Config_Jan25
RANSOM_Win_LockBit3_Decryptor_Jan25
SUSP_PE_Packed_UPX_Anomaly_Jan25

// Bad names
malware_detector              // Too vague
rule1                         // Meaningless
detect_bad_stuff              // Unprofessional
EMOTET_RULE                   // Missing category/platform/date
CobaltStrike_Beacon           // Missing category/date

Metadata Requirements

Required Fields

Every rule MUST have:

meta:
    description = "Detects X malware via Y unique feature"
    author = "Your Name <[email protected]>"  // OR "@twitter_handle"
    reference = "https://analysis-report-url.com"
    date = "2025-01-29"
Description Guidelines
  • Start with "Detects" — Consistent, scannable format

  • Length: 60-400 characters — Brief but informative

  • Explain WHAT and HOW — What it catches and the distinguishing feature

// Good descriptions
description = "Detects Emotet loader via unique XOR decryption routine and mutex pattern"
description = "Detects CobaltStrike beacon by watermark bytes in PE overlay"
description = "Detects generic PHP webshell using eval with base64_decode pattern"

// Bad descriptions
description = "Malware"                    // Too short
description = "This rule detects..."       // Redundant
description = "Catches bad stuff"          // Unprofessional
description = "Might be malware"           // Low confidence = use SUSP_ prefix
Optional Fields
meta:
    // Sample identification (hash field can repeat)
    hash = "abc123def456..."               // SHA256 of reference sample
    hash = "789xyz..."                     // Additional samples (repeat field)

    // Confidence scoring
    score = 75                             // 0-100, use thresholds

    // Versioning
    modified = "2025-01-30"                // Last update date
    version = "1.2"                        // Rule version
    old_rule_name = "Previous_Rule_Name"   // For renamed rules (searchability)

    // Classification
    tags = "apt, lazarus, loader"          // Comma-separated
    tlp = "WHITE"                          // Traffic Light Protocol

    // MITRE ATT&CK
    mitre_attack = "T1055"                 // Technique ID
Score Thresholds
ScoreMeaningAction
0-25Low confidenceHunting only, expect FPs
26-50MediumInvestigate, don't auto-quarantine
51-75HighAlert SOC, likely malicious
76-100CriticalAuto-quarantine appropriate

Common Naming Mistakes

Bad NameProblemCorrected
Emotet_DetectorMissing category, platform, dateMAL_Win_Emotet_Loader_Jan25
MAL_Suspicious_File"Suspicious" is vagueMAL_Win_Lazarus_Downloader_Jan25
rule1No semantic meaningHKTL_Multi_Mimikatz_CredDump_Jan25
MALWARE_windows_trojanWrong case, wrong orderMAL_Win_Trojan_Generic_Jan25
emotet_loaderAll lowercaseMAL_Win_Emotet_Loader_Jan25
EmoteTLoaderCamelCaseMAL_Win_Emotet_Loader_Jan25
MAL Win EmotetSpacesMAL_Win_Emotet_Loader_Jan25
CobaltStrike_BeaconMissing category and dateHKTL_Win_CobaltStrike_Beacon_Jan25

Linter Error Codes

The yara_lint.py script produces these codes:

CodeSeverityIssueFix
E000ErrorYARA-X compilation errorRead the compiler's source location; it points at the exact token
E001ErrorMissing required metadata field (description, author, date)Add the missing field
E002ErrorText string shorter than 4 bytesUse a longer string, or a hex pattern with surrounding context
E003ErrorHex string shorter than 4 bytesExtend the pattern to 4+ fixed bytes
E006Errorbase64 modifier on a string shorter than 3 charactersYARA-X requires 3+ chars; lengthen or drop the modifier
E008ErrorNegative array indexing, unsupported in YARA-X@a[-1] → @a[#a - 1]
W001WarningRule name does not follow CATEGORY_PLATFORM_FAMILY_DATERename using a standard prefix
W002WarningDescription does not start with 'Detects'Rewrite the description
W003WarningDescription shorter than 60 charactersExplain what it catches and how
W004WarningMissing 'reference' metadataAdd a URL to the analysis or source
W005WarningString contains an FP-prone substringReplace with a family-specific indicator
W006WarningHex string starts with a wildcardMove fixed bytes to the front for a better atom
W007WarningDeprecated feature used in conditionReplace entrypoint with pe.entry_point; drop PEiD patterns
W008WarningUnbounded regex quantifier (.* or .+)Add length bounds: .{0,100}
W009WarningCondition reaches pattern or module state before any cheap pre-filterLead with filesize < or a uintNN magic-byte check
I001InfoUnrecognized category prefixUse a standard prefix or document the custom one
I002InfoDescription longer than 400 charactersTrim to the distinguishing detail
I003Infonocase on a string longer than 20 charactersConfirm case actually varies across samples
I004Infoxor without an explicit key rangeUse xor(0xNN) once you know the key

scripts/test_yara_rules.py asserts this table and the linter's code registry stay in sync, so a check cannot be added or removed without updating both.

PR Review Checklist

When reviewing YARA rules in PRs:

Naming & Metadata
  • [ ] Name matches {CATEGORY}_{PLATFORM}_{FAMILY}_{DATE} format

  • [ ] Category prefix is from approved list (or justified)

  • [ ] Description starts with "Detects" and is 60-400 chars

  • [ ] Author includes contact (email or @handle)

  • [ ] Reference URL is provided and accessible

  • [ ] Date matches rule creation/modification date

  • [ ] Hash field contains valid SHA256 of primary sample

String Quality
  • [ ] All strings ≥4 bytes

  • [ ] No API names used as indicators

  • [ ] No common paths or executables

  • [ ] Regex patterns are bounded

  • [ ] Base64 modifier only on 3+ char strings

Condition Quality
  • [ ] Starts with filesize < check

  • [ ] Has magic bytes check before module use

  • [ ] Uses and instead of implicit conjunction

  • [ ] Expensive operations come last

Testing Evidence
  • [ ] Matches all target samples (list sample hashes)

  • [ ] Zero matches on goodware corpus (state corpus tested)

  • [ ] yr check passes

  • [ ] yr fmt --check passes

  • [ ] Linter passes

Enforcing Style in CI

Pre-commit Hook

Add to .pre-commit-config.yaml:

repos:
  - repo: local
    hooks:
      - id: yara-lint
        name: YARA Lint
        entry: uv run yara_lint.py --strict
        language: system
        files: \.yar$
        types: [file]
GitHub Actions
- name: Lint YARA rules
  run: |
    uv run yara_lint.py --strict rules/
    yr check rules/
    yr fmt --check rules/

Block PRs that fail linting. No exceptions for "quick fixes."

Anti-Patterns

Naming
  • All lowercase: emotet_loader

  • CamelCase: EmoteTLoader

  • No category: Emotet_Jan25

  • Spaces or special chars: MAL Win Emotet

  • Reserved words: rule, strings, condition

Metadata
  • Missing description

  • Description doesn't start with "Detects"

  • No author attribution

  • No reference URL

  • Outdated date (not updated when rule modified)

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs Python

Security

What our scanner noticed· Medium risk

  • References to credential files
  • Scripts that your agent may run

This skill includes scripts that your agent may run. Read them before you use it.

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Published by
Trail of Bits
Publisher
Trail of Bits (Official)
Source
trailofbits/skills · plugins/yara-authoring/skills/yara-rule-authoring · commit e4dd0bb
Licence
Creative Commons Attribution-ShareAlike 4.0 International (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Trail of Bits or Trail of Bits.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download yara-rule-authoring.zip