Yara Rule Authoring
Trail of BitsOfficialPublished by Trail of Bits
- Skill
- Guidelines
- Security
- CC-BY-SA-4.0
- Medium risk
- Has scripts
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
Download the skill as a ZIP:
https://autogineer.com/agent-skills/trailofbits/yara-rule-authoring/downloadUnzip 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
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.
Target specific families, not categories — "Detects ransomware" catches everything and nothing. "Detects LockBit 3.0 configuration extraction routine" catches what you want.
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.
Short-circuit with cheap checks first —
filesize(instant), then magic bytes (nearly instant), then strings (cheap), then modules (expensive).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:
| Platform | Magic Bytes | Bad Strings | Good Strings |
|---|---|---|---|
| Windows PE | uint16(0) == 0x5A4D | API names, Windows paths | Mutex names, PDB paths |
| macOS Mach-O | uint32(0) == 0xFEEDFACE (32-bit), 0xFEEDFACF (64-bit), uint32be(0) == 0xCAFEBABE (universal) | Common Obj-C methods | Keylogger strings, persistence paths |
| JavaScript/Node | (none needed) | require, fetch, axios | Obfuscator signatures, eval+decode chains |
| npm/pip packages | (none needed) | postinstall, dependencies | Suspicious package names, exfil URLs |
| Office docs | uint32(0) == 0x04034B50 | VBA keywords | Macro auto-exec, encoded payloads |
| VS Code extensions | (none needed) | vscode.workspace | Uncommon activationEvents, hidden file access |
| Chrome extensions | Use crx module | Common Chrome APIs | Permission abuse, manifest anomalies |
| Android apps | Use dex module | Standard DEX structure | Obfuscated classes, suspicious permissions |
uintNN()reads little-endian. Write the constant as the bytes reversed, or useuintNNbe()and write them in file order. A ZIP/OOXML file starts with bytes50 4B 03 04, so it isuint32(0) == 0x04034B50—uint32(0) == 0x504B0304compiles cleanly and never matches anything. The same trap catches Mach-O universal binaries: on disk they areCA FE BA BE, souint32(0) == 0xCAFEBABEis a dead branch; writeuint32be(0) == 0xCAFEBABEoruint32(0) == 0xBEBAFECA. Verify withyr scanagainst 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,kCGEventKeyDownSSH tunnel strings:
ssh -D,tunnel,socksPersistence paths:
~/Library/LaunchAgents,/Library/LaunchDaemonsCredential 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
| Target | Approach |
|---|---|
| npm package | package.json patterns, postinstall/preinstall hooks, exfil combination: fetch + env access + credential paths |
| Chrome extension | crx module |
| Other extension | Manifest patterns, background script behaviors |
| Standalone JS | Obfuscation markers (eval+atob, fromCharCode chains), unique function/variable names, packed payloads |
| Minified/webpack bundle | Unique 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:
| Test | Why it fails | Do instead |
|---|---|---|
| Under 4 bytes | No atom | Find a longer string |
Repeated bytes (0000, 9090) | Weak atom | Add surrounding context |
API name (VirtualAlloc, CreateRemoteThread) | Every packer and installer calls it | Hex pattern of the call site plus a unique marker |
| Appears in Windows system files | Guaranteed FPs | Find something family-specific |
Common path (C:\Windows\, cmd.exe) | Ubiquitous | Find malware-specific paths |
| Appears in other malware families | Not identifying this family | Combine with a family-specific marker |
Everything left — unique to this family — is what the rule should rest on.
Choosing a String Type
| Need | Use |
|---|---|
| Exact ASCII/Unicode text | $s = "MutexName" ascii wide |
| Specific byte sequence | $h = { 4D 5A 90 00 } |
| Byte sequence with variation | Hex 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
| Situation | Use |
|---|---|
| Strings are individually unique to the malware | any of them — each alone is suspicious |
| Strings are common but the combination is suspicious | all of them — require the full pattern |
| Strings have different confidence levels | Group: all of ($core_*) and any of ($variant_*) |
| Seeing false positives | Tighten: 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 categoriesModules vs Byte Checks
| Need | Use |
|---|---|
| imphash, rich header, authenticode | PE module — too complex to replicate |
| Magic bytes or simple offsets | uint16/uint32 — faster, no module overhead |
| Section names/sizes | PE module, but put the magic-byte filter FIRST |
| Chrome extension permissions | crx module — string parsing is fragile |
| LNK target paths | lnk 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#acan reach thousands in large files.Prefer hex over regex where the bytes are fixed.
Before Writing: Is the Sample Packed?
| Signal | What to do |
|---|---|
| Entropy > 7.0 | Likely packed — find the unpacked layer first |
| Few or no readable strings | Likely packed — use entropy, PE structure, or packer signatures |
| UPX/MPRESS/custom packer detected | Target the unpacked payload OR detect the packer itself |
| Readable strings available | Proceed 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 signal | Use |
|---|---|
| High entropy sections | math.entropy() on specific sections |
| Unusual import pattern | pe.imphash() for import-hash clustering |
| PE structure anomalies | Section names, sizes, characteristics |
| Metadata present | Version info, timestamps, resources |
| Nothing unique | This 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
Which string matched? —
yr scan -s rule.yar false_positive.exeIn a legitimate library? — add a
not $fp_vendor_stringexclusionA common development pattern? — replace the string with something more specific
Multiple generic strings matching together? — tighten to require all, plus a unique marker
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.
| Rationalization | Expert 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
| Tool | Purpose |
|---|---|
| yr CLI | yr check (validate), yr fmt (format), yr scan -s (scan, show strings), yr dump -m pe (inspect structure) |
| yarGen | Extract candidate strings: yarGen.py -m samples/ --excludegood |
| FLOSS | Extract obfuscated/stack strings: floss sample.exe — when yarGen comes up empty |
| signature-base | Study quality examples |
| YARA-CI | Goodware 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 timingReach 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/| Issue | Legacy | YARA-X Fix |
|---|---|---|
Literal { in regex | /{/ | /\{/ |
| Invalid escapes | \R silently literal | \\R or R |
| Base64 strings | Any length | 3+ chars required |
| Negative indexing | @a[-1] | @a[#a - 1] |
| Duplicate modifiers | Allowed | Remove 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_Jan25Categories: 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
Gather samples — multiple; single-sample rules are brittle
Extract candidates —
yarGen -m samples/ --excludegoodValidate quality — apply the string selection tests; expect to discard 80% of yarGen output
Write the rule — proper metadata, cheap checks first
Lint and test —
yr check,yr fmt, the linter scriptGoodware validation — VirusTotal corpus or local clean files
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 stringShortcut: "<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
| Mistake | Bad | Good |
|---|---|---|
| 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 filter | pe.imports(...) first | uint16(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 bytes | uint32(0) == 0xCAFEBABE | uint32be(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 checkandyr fmt --checkpass[ ] 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 resultSee README.md for detailed script documentation.
Further Reading
| Topic | Document |
|---|---|
| Naming and metadata conventions | style-guide.md |
| Performance and atom optimization | performance.md |
| String types and judgment | strings.md |
| Testing and validation | testing.md |
| Chrome extension module (crx) | crx-module.md |
| Android DEX module (dex) | dex-module.md |
| Complete rule development process | rule-development.md |
The examples/ directory holds real, attributed rules worth reading before writing your own:
| Example | Demonstrates | Source |
|---|---|---|
| MAL_Win_Remcos_Jan25.yar | PE malware: graduated string counts, multiple rules per family | Elastic Security |
| MAL_Mac_ProtonRAT_Jan25.yar | macOS: Mach-O magic bytes, multi-category grouping | Airbnb BinaryAlert |
| MAL_NPM_SupplyChain_Jan25.yar | npm supply chain: real attack patterns, ERC-20 selectors | Stairwell Research |
| SUSP_JS_Obfuscation_Jan25.yar | JavaScript: obfuscator detection, density-based matching | imp0rtp3, Nils Kuhnert |
| SUSP_CRX_SuspiciousPermissions.yar | Chrome extensions: crx module, permissions | Educational |
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
- ATTRIBUTION.mdAdded by AutoGineer946 B
- LICENSELicence file added by AutoGineer19.7 KiB
- SKILL.md24.2 KiB
- agents/openai.yaml236 B
- assets/trail-of-bits-mark.svg3.0 KiB
- examples/MAL_Mac_ProtonRAT_Jan25.yar3.2 KiB
- examples/MAL_NPM_SupplyChain_Jan25.yar5.3 KiB
- examples/MAL_Win_Remcos_Jan25.yar3.1 KiB
- examples/SUSP_CRX_SuspiciousPermissions.yar4.2 KiB
- examples/SUSP_JS_Obfuscation_Jan25.yar5.7 KiB
- references/crx-module.md7.3 KiB
- references/dex-module.md10.1 KiB
- references/performance.md8.7 KiB
- references/strings.md11.6 KiB
- references/style-guide.md9.3 KiB
- references/testing.md13.1 KiB
- scripts/atom_analyzer.pyScript4.6 KiB
- scripts/pyproject.toml553 B
- scripts/review.shScript2.9 KiB
- scripts/test_yara_rules.pyScript17.7 KiB
- scripts/uv.lock3.4 KiB
- scripts/yara_lint.pyScript4.7 KiB
- scripts/yara_rules.pyScript30.4 KiB
- workflows/rule-development.md13.2 KiB
scripts/test_yara_rules.py
"""Tests for the shared YARA rule parsing and analysis helpers.
Deliberately imports only yara_rules, which has no third-party dependencies, so
these run under the repository's `uv run --no-project --with pytest` harness
without the yara-x wheel.
Each parser test pairs a case that must be detected with the input shape that
used to defeat it, so a regression in the scanners fails here rather than
silently reporting a clean rule.
"""
from __future__ import annotations
import re
from pathlib import Path
import pytest
from yara_rules import ISSUE_CODES
from yara_rules import REPEATED_PATTERNS
from yara_rules import LintResult
from yara_rules import analyze_hex_string
from yara_rules import analyze_text_string
from yara_rules import check_condition_order
from yara_rules import collect_rule_files
from yara_rules import coverage_error
from yara_rules import extract_condition
from yara_rules import extract_metadata
from yara_rules import extract_rule_body
from yara_rules import extract_rule_names
from yara_rules import extract_strings
from yara_rules import find_best_atom
from yara_rules import hex_string_runs
from yara_rules import lint_source
from yara_rules import rule_less_files
from yara_rules import score_atom
from yara_rules import select_exit_code
from yara_rules import strip_comments
def codes(source: str) -> set[str]:
return {issue.code for issue in lint_source(source)}
# --------------------------------------------------------------------------- #
# String parsing
# --------------------------------------------------------------------------- #
REGEX_RULE = """
rule MAL_Win_Slash_Jan25 {
strings:
$url = /https:\\/\\/[a-z0-9]{5,20}\\.onion\\/beacon/ nocase
$cls = /[/a-z]+\\.php/
condition:
filesize < 1MB and any of them
}
"""
def test_regex_value_survives_escaped_slashes():
"""A `\\/` must not terminate the pattern -- the bug that broke every URL regex."""
strings = {s.name: s for s in extract_strings(REGEX_RULE, "MAL_Win_Slash_Jan25")}
assert strings["$url"].type == "regex"
assert strings["$url"].value == r"https:\/\/[a-z0-9]{5,20}\.onion\/beacon"
assert strings["$url"].modifiers == ["nocase"]
def test_regex_value_survives_slash_in_character_class():
strings = {s.name: s for s in extract_strings(REGEX_RULE, "MAL_Win_Slash_Jan25")}
assert strings["$cls"].value == r"[/a-z]+\.php"
def test_unbounded_quantifier_is_flagged_inside_a_url_regex():
"""W008 has to reach past the escaped slashes to see the `.*`."""
source = """
rule MAL_Win_Unbounded_Jan25 {
meta:
description = "Detects a thing via a marker long enough to clear sixty characters easily"
author = "[email protected]"
reference = "https://example.com"
date = "2025-01-01"
strings:
$u = /https:\\/\\/evil\\.com\\/.*/
condition:
filesize < 1MB and $u
}
"""
assert "W008" in codes(source)
def test_bounded_repetition_is_not_flagged_as_unbounded():
source = """
rule MAL_Win_Bounded_Jan25 {
strings:
$u = /https:\\/\\/evil\\.com\\/.{0,40}/
condition:
filesize < 1MB and $u
}
"""
assert "W008" not in codes(source)
def test_escaped_quote_does_not_end_a_text_string():
source = r"""
rule MAL_Win_Quote_Jan25 {
strings:
$s = "say \"hello\" now" ascii
condition:
filesize < 1MB and $s
}
"""
strings = extract_strings(source, "MAL_Win_Quote_Jan25")
assert len(strings) == 1
assert strings[0].value == r"say \"hello\" now"
assert strings[0].modifiers == ["ascii"]
def test_trailing_comment_is_not_read_as_a_modifier():
source = """
rule MAL_Win_Comment_Jan25 {
strings:
$s = "unique_marker_value" ascii // nocase would be wrong here
condition:
filesize < 1MB and $s
}
"""
strings = extract_strings(source, "MAL_Win_Comment_Jan25")
assert strings[0].modifiers == ["ascii"]
def test_brace_inside_a_string_does_not_truncate_the_rule_body():
source = """
rule MAL_Win_Brace_Jan25 {
strings:
$a = "}"
$b = "second_unique_marker"
condition:
filesize < 1MB and all of them
}
"""
names = [s.name for s in extract_strings(source, "MAL_Win_Brace_Jan25")]
assert names == ["$a", "$b"]
assert "all of them" in extract_condition(source, "MAL_Win_Brace_Jan25")
def test_commented_out_rule_is_not_extracted():
source = """
// rule MAL_Win_Ghost_Jan25 { condition: true }
rule MAL_Win_Real_Jan25 { condition: filesize < 1MB }
"""
assert extract_rule_names(source) == ["MAL_Win_Real_Jan25"]
def test_metadata_and_body_are_scoped_to_the_named_rule():
source = """
rule MAL_Win_First_Jan25 {
meta:
description = "Detects the first thing"
condition:
filesize < 1MB
}
rule MAL_Win_Second_Jan25 {
meta:
description = "Detects the second thing"
condition:
filesize < 2MB
}
"""
assert extract_metadata(source, "MAL_Win_Second_Jan25")["description"] == (
"Detects the second thing"
)
assert "2MB" in extract_rule_body(source, "MAL_Win_Second_Jan25")
def test_tagged_rule_header_is_parsed():
source = "rule MAL_Win_Tagged_Jan25 : apt loader { condition: filesize < 1MB }"
assert extract_rule_names(source) == ["MAL_Win_Tagged_Jan25"]
assert "filesize" in extract_condition(source, "MAL_Win_Tagged_Jan25")
# --------------------------------------------------------------------------- #
# Issue messages
# --------------------------------------------------------------------------- #
def test_messages_contain_no_leftover_double_braces():
"""Implicit f-string/plain-string concatenation used to leak `{{1,N}}` verbatim."""
source = """
rule badname {
strings:
$u = /evil.*/
$s = "ab"
condition:
$u or $s
}
"""
issues = lint_source(source)
assert issues, "fixture should produce issues"
for issue in issues:
assert "{{" not in issue.message
assert "}}" not in issue.message
# --------------------------------------------------------------------------- #
# Condition ordering (W009)
# --------------------------------------------------------------------------- #
@pytest.mark.parametrize(
"condition",
[
"filesize < 5MB and uint16(0) == 0x5A4D and $mutex",
"uint32(0) == 0xFEEDFACF and any of ($lib*)",
"crx.is_crx and 2 of ($miner*)",
'filesize < 1MB and pe.imphash() == "abc"',
],
)
def test_cheap_prefilter_first_is_accepted(condition):
assert list(check_condition_order("R", condition)) == []
@pytest.mark.parametrize(
"condition",
[
'pe.imports("kernel32.dll", "VirtualAlloc") and $mutex and filesize < 5MB',
"any of them",
"$a and $b and filesize < 1MB",
"for any i in (0..#s1) : (@s1[i] < 1000) and filesize < 1MB",
],
)
def test_expensive_term_before_any_prefilter_is_flagged(condition):
issues = list(check_condition_order("R", condition))
assert [i.code for i in issues] == ["W009"]
def test_condition_order_check_is_wired_into_lint_source():
source = """
rule MAL_Win_Order_Jan25 {
meta:
description = "Detects a thing via a marker long enough to clear sixty characters easily"
author = "[email protected]"
reference = "https://example.com"
date = "2025-01-01"
strings:
$mutex = "Global\\\\UniqueMarker"
condition:
pe.imphash() == "abc" and $mutex and filesize < 5MB
}
"""
assert "W009" in codes(source)
# --------------------------------------------------------------------------- #
# Atom analysis
# --------------------------------------------------------------------------- #
def test_jump_breaks_byte_adjacency():
"""`4D 5A [2-4] 50 45` is two runs; the bytes either side are never one atom."""
runs = hex_string_runs("4D 5A [2-4] 50 45")
assert [run.data for run in runs] == [b"\x4d\x5a", b"\x50\x45"]
def test_alternation_breaks_byte_adjacency():
runs = hex_string_runs("4D 5A 90 00 ( 50 45 | 4E 45 )")
assert runs[0].data == b"\x4d\x5a\x90\x00"
assert len(runs) > 1
def test_hex_string_split_by_a_jump_has_no_four_byte_atom():
source = """
rule MAL_Win_Jump_Jan25 {
strings:
$h = { 4D 5A [2-4] 50 45 }
condition:
filesize < 1MB and $h
}
"""
string = extract_strings(source, "MAL_Win_Jump_Jan25")[0]
runs = hex_string_runs(string.value)
assert all(find_best_atom(run.data, run.wildcards) == (None, 0) for run in runs)
def test_nibble_wildcard_counts_as_a_wildcard():
runs = hex_string_runs("4D 5? 90 00 41 42 43")
assert runs[0].wildcards == [1]
def test_hex_tokens_without_whitespace_are_parsed():
runs = hex_string_runs("4D5A9000")
assert runs[0].data == b"\x4d\x5a\x90\x00"
def test_repeated_bytes_score_worse_than_unique_bytes():
_, null_score = find_best_atom(b"\x00\x00\x00\x00", [])
_, unique_score = find_best_atom(b"\x4d\x5a\x91\x03", [])
assert null_score < unique_score
# --------------------------------------------------------------------------- #
# Scan targets and exit codes
# --------------------------------------------------------------------------- #
def test_directory_with_no_rules_is_an_error_not_a_clean_run(tmp_path):
(tmp_path / "notes.md").write_text("no rules here")
files, error = collect_rule_files(tmp_path)
assert files == []
assert error is not None and "nothing was inspected" in error
def test_directory_with_rules_collects_them(tmp_path):
(tmp_path / "a.yar").write_text("rule A { condition: true }")
(tmp_path / "nested").mkdir()
(tmp_path / "nested" / "b.yara").write_text("rule B { condition: true }")
files, error = collect_rule_files(tmp_path)
assert error is None
assert [f.name for f in files] == ["a.yar", "b.yara"]
def test_missing_path_is_an_error(tmp_path):
files, error = collect_rule_files(tmp_path / "absent")
assert files == []
assert error is not None
WARNINGS_ONLY_RULE = """
rule badname {
meta:
description = "Detects a thing via a marker long enough to clear sixty characters easily"
author = "[email protected]"
date = "2025-01-01"
strings:
$s = "unique_marker_value"
condition:
filesize < 1MB and $s
}
"""
def test_exit_code_reflects_severity():
clean = LintResult(file="clean.yar")
warned = LintResult(file="warn.yar")
warned.issues.extend(lint_source(WARNINGS_ONLY_RULE))
assert warned.warning_count > 0
assert warned.error_count == 0
assert select_exit_code([clean], strict=False) == 0
assert select_exit_code([warned], strict=False) == 0
assert select_exit_code([warned], strict=True) == 1
def test_unreadable_file_fails_even_without_issues():
broken = LintResult(file="x.yar", parse_error="Cannot read file")
assert select_exit_code([broken], strict=False) == 1
# lint_file returns early on a read error without setting `rules`, so the
# default has to be 0 -- otherwise coverage_error credits a rule nobody saw.
assert broken.rules == 0
# --------------------------------------------------------------------------- #
# Documentation sync
# --------------------------------------------------------------------------- #
STYLE_GUIDE = Path(__file__).resolve().parent.parent / "references" / "style-guide.md"
# Fixtures chosen to drive every check the linter implements at least once.
CODE_FIXTURES = (
'rule badname { strings: $s = "ab" $h = { 4D 5A } condition: $s and $h }',
"""
rule GHOST_Win_Thing_Jan25 {
meta:
description = "short"
strings:
$a = "cmd.exe"
$b = "??? placeholder value" nocase xor
$c = "ab" base64
$w = { ?? ?? 4D 5A 90 00 }
$r = /https:\\/\\/evil\\.com\\/.*/
condition:
$a and entrypoint == 0 and @a[-1] > 0
}
""",
"""
rule MAL_Win_Verbose_Jan25 {
meta:
description = "Detects %s"
author = "[email protected]"
reference = "https://example.com"
date = "2025-01-01"
strings:
$s = "unique_marker_value"
condition:
filesize < 1MB and $s
}
""".replace("%s", "x" * 420),
)
def documented_codes() -> set[str]:
table = STYLE_GUIDE.read_text()
return set(re.findall(r"^\|\s*([EWI]\d{3})\s*\|", table, re.MULTILINE))
def test_style_guide_table_matches_the_code_registry():
assert documented_codes() == set(ISSUE_CODES), (
"references/style-guide.md and yara_rules.ISSUE_CODES have drifted"
)
def test_every_emitted_code_is_registered():
emitted = {issue.code for fixture in CODE_FIXTURES for issue in lint_source(fixture)}
assert emitted, "fixtures should emit codes"
assert emitted <= set(ISSUE_CODES), f"unregistered codes: {emitted - set(ISSUE_CODES)}"
def test_fixtures_exercise_every_check_except_compilation():
"""E000 comes from yara_x, which these dependency-free tests cannot import."""
emitted = {issue.code for fixture in CODE_FIXTURES for issue in lint_source(fixture)}
assert set(ISSUE_CODES) - emitted == {"E000"}
# --------------------------------------------------------------------------- #
# Exit codes
# --------------------------------------------------------------------------- #
ERROR_RULE = """
rule MAL_Win_Short_Jan25 {
meta:
description = "Detects a thing via a marker long enough to clear sixty characters easily"
author = "[email protected]"
reference = "https://example.com"
date = "2025-01-01"
strings:
$s = "ab"
condition:
filesize < 1MB and $s
}
"""
def test_exit_code_fails_on_an_error_severity_issue():
"""The linter's main contract: an error exits 1 even without --strict."""
result = LintResult(file="err.yar")
result.issues.extend(lint_source(ERROR_RULE))
assert result.error_count > 0
assert select_exit_code([result], strict=False) == 1
# --------------------------------------------------------------------------- #
# Atom scoring
# --------------------------------------------------------------------------- #
def test_null_bytes_lower_the_atom_score():
assert score_atom(b"\x01\x02\x00\x03") < score_atom(b"\x01\x02\x04\x03")
def test_every_repeated_byte_pattern_scores_zero():
for pattern, _label in REPEATED_PATTERNS:
assert score_atom(pattern) == 0, f"{pattern!r} should be unusable as an atom"
def test_a_common_sequence_lowers_the_atom_score():
assert score_atom(b"This") < score_atom(b"Thiz")
def test_all_printable_atoms_score_below_binary_ones():
assert score_atom(b"abcd") < score_atom(b"\x01\x02\x03\x04")
def test_a_low_scoring_atom_is_an_error_and_a_middling_one_a_warning():
repeated = analyze_text_string("$s", "aaaaaa", [])
middling = analyze_text_string("$s", "abab", [])
assert [i.severity for i in repeated.issues] == ["error"]
assert [i.severity for i in middling.issues] == ["warning"]
def test_a_short_text_string_cannot_yield_an_atom():
analysis = analyze_text_string("$s", "ab", [])
assert analysis.byte_count == 2
assert [i.severity for i in analysis.issues] == ["error"]
assert analysis.best_atom is None
assert "only 2 bytes" in analysis.issues[0].message
def test_a_short_hex_string_cannot_yield_an_atom():
"""The diagnostic has to say "too short", not blame wildcards there are none of."""
analysis = analyze_hex_string("$h", "{ 4D 5A }")
assert analysis.byte_count == 2
assert [i.severity for i in analysis.issues] == ["error"]
assert analysis.best_atom is None
assert "only 2 bytes" in analysis.issues[0].message
assert "wildcard" not in analysis.issues[0].message
def test_high_wildcard_density_is_flagged():
analysis = analyze_hex_string("$h", "{ 4D 5A 90 00 ?? ?? ?? ?? ?? }")
assert analysis.best_atom == "4D5A9000"
assert any("wildcard density" in i.message for i in analysis.issues)
# --------------------------------------------------------------------------- #
# Scanners
# --------------------------------------------------------------------------- #
BLOCK_COMMENT_SOURCE = """
/* rule GHOST_Win_Commented_Jan25 { condition: true } */
rule MAL_Win_Real_Jan25 { condition: true }
"""
def test_a_rule_inside_a_block_comment_is_not_a_rule():
assert extract_rule_names(BLOCK_COMMENT_SOURCE) == ["MAL_Win_Real_Jan25"]
def test_block_comments_keep_their_line_breaks():
blanked = strip_comments(BLOCK_COMMENT_SOURCE)
assert blanked.count("\n") == BLOCK_COMMENT_SOURCE.count("\n")
assert "GHOST" not in blanked
CHAR_CLASS_RULE = """
rule MAL_Win_CharClass_Jan25 {
strings:
$r = /a[/]bcdef/
condition:
$r
}
"""
def test_a_slash_inside_a_character_class_does_not_end_the_regex():
strings = extract_strings(CHAR_CLASS_RULE, "MAL_Win_CharClass_Jan25")
assert [s.value for s in strings] == ["a[/]bcdef"]
# --------------------------------------------------------------------------- #
# Rule coverage across a run
# --------------------------------------------------------------------------- #
def test_a_run_that_inspected_no_rules_is_an_error():
assert coverage_error({"a.yar": 0}) is not None
assert coverage_error({"a.yar": 0, "b.yar": 0}) is not None
def test_inspecting_no_files_reports_that_rather_than_an_empty_file_list():
message = coverage_error({})
assert message is not None
assert "no files" in message
def test_a_rule_less_file_alongside_real_rules_is_not_an_error():
"""A shared `import "pe"` header holds no rules; the directory is still healthy."""
assert coverage_error({"imports.yar": 0, "rules.yar": 3}) is None
def test_the_coverage_error_names_the_files_it_inspected():
message = coverage_error({"b.yar": 0, "a.yar": 0})
assert message is not None
assert "a.yar" in message
assert "b.yar" in message
def test_rule_less_files_are_listed_for_reporting():
counts = {"imports.yar": 0, "rules.yar": 2, "empty.yar": 0}
assert rule_less_files(counts) == ["empty.yar", "imports.yar"]
assert rule_less_files({"rules.yar": 2}) == []
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